/* ============================================================================ Bad login attempt - client IP address and device id ---------------------------------------------------------------------------- BadLoginAttemptInfoService.Save now records who tried to log in: PCNumber computer name - reverse DNS of the client IP (falls back to the IP when there is no name). Can be a fully-qualified host name, so it is widened to NVARCHAR(255) below if it is narrower. IPAddress client IP - first X-Forwarded-For entry, else the connection's remote address. 45 chars fits the longest IPv6 text form. DeviceId mobile / tab device id (request header X-Device-Id / DeviceId, or set by the caller); NULL for a browser login. Run order: run this BEFORE deploying the matching code. BadLoginAttemptInfoDA .Insert and BadLoginAttemptInfoService.MapObject name both new columns, so without them every bad-login save and the System Audit Trail's "Bad Login Attempt" tab fail. Guarded; safe to re-run. ============================================================================ */ IF OBJECT_ID('dbo.BadLoginAttemptInfo') IS NULL BEGIN RAISERROR('dbo.BadLoginAttemptInfo does not exist on this database.', 16, 1); RETURN; END; GO IF COL_LENGTH('dbo.BadLoginAttemptInfo', 'IPAddress') IS NULL BEGIN ALTER TABLE dbo.BadLoginAttemptInfo ADD IPAddress NVARCHAR(45) NULL; END; GO IF COL_LENGTH('dbo.BadLoginAttemptInfo', 'DeviceId') IS NULL BEGIN ALTER TABLE dbo.BadLoginAttemptInfo ADD DeviceId NVARCHAR(200) NULL; END; GO /* Widen PCNumber to NVARCHAR(255) when it is narrower (keeping its nullability), so a long host name can not make the insert fail. MAX (-1) is left alone. */ DECLARE @maxLength SMALLINT, @typeName SYSNAME, @isNullable BIT; SELECT @maxLength = c.max_length, @typeName = t.name, @isNullable = c.is_nullable FROM sys.columns c JOIN sys.types t ON t.user_type_id = c.user_type_id WHERE c.object_id = OBJECT_ID('dbo.BadLoginAttemptInfo') AND c.name = 'PCNumber'; IF @maxLength IS NOT NULL AND @maxLength <> -1 AND ( (@typeName IN ('nvarchar', 'nchar') AND @maxLength < 510) OR (@typeName IN ('varchar', 'char') AND @maxLength < 255) ) BEGIN DECLARE @sql NVARCHAR(400) = N'ALTER TABLE dbo.BadLoginAttemptInfo ALTER COLUMN PCNumber NVARCHAR(255) ' + CASE WHEN @isNullable = 1 THEN N'NULL' ELSE N'NOT NULL' END + N';'; EXEC sp_executesql @sql; END; GO