ALTER PROCEDURE [dbo].[WZ_ACCOUNT_SecurityCheckForLock] @in_CustomerID int,
@in_IP varchar(100),
@in_Country varchar(50),
@Out_NeedLock int out
AS
BEGIN
SET NOCOUNT ON;
-- this procedure is local to SQL
-- select 0 as ResultCode
-- account is fine by default
set @Out_NeedLock = 0
-- get last login info
declare @lastloginCountry varchar(32) = ''
select @lastloginCountry=lastloginCountry from Accounts where CustomerID=@in_CustomerID
-- decouple IPs
declare @ip1 varchar(32) -- last login ip 'X.y.z.w'
declare @ip2 varchar(32) -- last login ip 'x.Y.z.w'
declare @ip3 varchar(32) -- last login ip 'x.y.Z.w'
declare @ip4 varchar(32) -- last login ip 'x.y.z.W'
declare @ip5 varchar(32) -- same for @in_IP
declare @ip6 varchar(32)
declare @ip7 varchar(32)
declare @ip8 varchar(32)
declare @n1 int
declare @n2 int
declare @n3 int
set @n1 = charindex('.', @in_IP)
set @ip5 = substring(@in_IP, 1, @n1 - 1)
set @n2 = charindex('.', @in_IP, @n1 + 1)
set @ip6 = substring(@in_IP, @n1 + 1, @n2 - 1 - @n1)
set @n3 = charindex('.', @in_IP, @n2 + 1)
set @ip7 = substring(@in_IP, @n2 + 1, @n3 - 1 - @n2)
set @ip8 = substring(@in_IP, @n3 + 1, 999)
declare @Network varchar(32) = @ip5 + '.' + @ip6
-- do not lock if we have that IP whitelisted
if exists (select CustomerID from AccountIpWhitelist where CustomerID=@in_CustomerID ) begin
return
end
-- lock if country changed
if (@lastloginCountry <> '' and @in_Country <> '' and @lastloginCountry <> @in_Country)
begin
set @Out_NeedLock = 1
exec WZ_ACCOUNT_SecurityLock @in_CustomerID, @in_IP, @in_Country
return
end
-- lock if first 2 octets is changed
if(@ip1 <> @ip5 or @ip2 <> @ip6)
begin
-- special case - we ignore first login attempt if password was reset and add that network to whitelist
begin
insert into AccountIpWhitelist values (@in_CustomerID, GETDATE(), @Network, @in_Country)
return
end
-- ip changed, block
set @Out_NeedLock = 0
exec WZ_ACCOUNT_SecurityLock @in_CustomerID, @in_IP, @in_Country
return
end
-- for first time logins - if there was no whitelist entries - add current IP there
declare @NumEntries int = 0
select @NumEntries=COUNT(*) from AccountIpWhitelist where CustomerID=@in_CustomerID
if(@NumEntries = 0) begin
insert into AccountIpWhitelist values (@in_CustomerID, GETDATE(), @Network, @in_Country)
end
return
END