/* ============================================================================ User login history - client IP address and device id ---------------------------------------------------------------------------- UserLogInInfoService.Save now records where every successful login came from: PCNumber computer name - reverse DNS of the client IP (falls back to the IP when there is no name). It used to hold the web SERVER's name (Environment.MachineName), the same on every row. 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. UserLogInInfoDA.Insert and UserLogInInfoService.MapObject name both new columns, so without them every login-history save (it runs on a background thread, so login itself still works) and the System Audit Trail's "User Audit Trail" tab fail. Companion of BadLoginAttemptInfo_ClientInfo_DB_Changes.sql. Guarded; safe to re-run. ============================================================================ */ IF OBJECT_ID('dbo.UserLoginInfo') IS NULL BEGIN RAISERROR('dbo.UserLoginInfo does not exist on this database.', 16, 1); RETURN; END; GO IF COL_LENGTH('dbo.UserLoginInfo', 'IPAddress') IS NULL BEGIN ALTER TABLE dbo.UserLoginInfo ADD IPAddress NVARCHAR(45) NULL; END; GO IF COL_LENGTH('dbo.UserLoginInfo', 'DeviceId') IS NULL BEGIN ALTER TABLE dbo.UserLoginInfo 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.UserLoginInfo') 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.UserLoginInfo ALTER COLUMN PCNumber NVARCHAR(255) ' + CASE WHEN @isNullable = 1 THEN N'NULL' ELSE N'NOT NULL' END + N';'; EXEC sp_executesql @sql; END; GO