diff --git a/BadLoginAttemptInfo_ClientInfo_DB_Changes.sql b/BadLoginAttemptInfo_ClientInfo_DB_Changes.sql new file mode 100644 index 0000000..203603d --- /dev/null +++ b/BadLoginAttemptInfo_ClientInfo_DB_Changes.sql @@ -0,0 +1,59 @@ +/* ============================================================================ + 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 diff --git a/CLAUDE.md b/CLAUDE.md index 601991f..f71d747 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -436,6 +436,16 @@ calendar's Users dropdown once came back silently empty for exactly this reason. column: use the pattern in `CalendarItemDA.UserEmailExpression`, which checks `COL_LENGTH` once per process and builds `COALESCE(EmailAddress, Email)` from whichever columns exist. Server-side SQL errors that the UI swallows land in `HRM.UI/Log/Error.log` (`ExceptionLog`), the first place to look. +Two places don't follow that pattern yet. `UserDA.Insert` writes only `Email`, so creating a user fails on a +database that lacks it (the pending `UsersEmailColumn_DB_Changes.sql` adds it; its header wrongly says Insert +writes both columns). `UserService.MapObject` +reads only `Email` (the `EmailAddress` line is commented out), so the user list's `email` is blank wherever +addresses live in `EmailAddress`. + +Gotcha in user approval: `UserDA.Approve` always sets `Status = Approved` (5), whatever the request was. So +"approving" an `Inactive_Not_Yet_Approve` (9) or `Inactive` (8) user **re-activates** them, and a deactivation +can never actually be approved. The user list labels that action "Re-activate" for this reason; the fix +belongs in the server. `PayrollTypeID` is the scoping key threaded through most payroll/attendance queries — when adding a query that returns employee data, check whether existing siblings filter by it. Reading `EmployeeID` @@ -545,8 +555,10 @@ Schema/proc changes are hand-authored `.sql` scripts named `_DB_Changes each database **manually**. They live in two places and the distinction is the whole point: - **Repo root** — the *pending* ones. `ls *_DB_Changes.sql` shows what has not been applied yet - (at the initial import there were none). Write new scripts here, in the same commit as the code - that needs them. + Write new scripts here, in the same commit as the code that needs them. The root also holds + generated DB analysis reports (`UnusedTables_.txt`, `TablesWithoutPK_.txt`). They are + input for clean-up decisions, not proof a table is safe to drop: they only scan `HRM.DA/DA` SQL and + DB objects, and `HangFire.*` is used by the library itself. - **[`db/Script/`](db/Script)** — the archive of shipped ones (`Calendar`, `MenuIcon`, `AttendanceLeaveSummaryLM`, `TaxParameterEssDeadline`, `PMS_SquareAlign_IDP`, `EmpHistoricalData`). Read them for precedent — they are the best worked examples of house style — but don't re-run one @@ -659,6 +671,9 @@ What the earlier 19 → 21 upgrade fixed in place, so don't undo it: under `src/`). Always edit the `.ts`; never the generated `.js`. - Long-running actions show the shared loading panel: `` in the template plus `loadingPanel.ShowLoadingPanel = true/false` around the call (~395 templates use it). + The flag must be on the injected **`loadingPanelService`** (`hrm-loding panel/loding.panel.service.ts`), + which is what `` reads. `UntilityHandlerService` has a same-named + `ShowLoadingPanel` that nothing renders, so ~10 older components that set it never show a spinner. Wrap every button/API action that can take a moment, and clear the flag in the error path too. ### App bootstrap and the initial route diff --git a/HRM.BO/Basic/BadLoginAttemptInfo.cs b/HRM.BO/Basic/BadLoginAttemptInfo.cs index 2d563c2..86b5a58 100644 --- a/HRM.BO/Basic/BadLoginAttemptInfo.cs +++ b/HRM.BO/Basic/BadLoginAttemptInfo.cs @@ -24,6 +24,17 @@ namespace HRM.BO public DateTime AttemptTime { get; set; } public string PCNumber { get; set; } + // Client of the failed login (BadLoginAttemptInfo_ClientInfo_DB_Changes.sql). + // Filled by BadLoginAttemptInfoService.Save from the HTTP request when not set. + public string IPAddress { get; set; } + /// Mobile / tab device id; null for a browser login. + public string DeviceId { get; set; } + + // Display only, not persisted: filled by GetAuditTrail (joined from Users) + // for the System Audit Trail screen. + public string LoginID { get; set; } + public string UserName { get; set; } + //#region Service Factory IBadLoginAttemptInfoService : IBadLoginAttemptInfoService @@ -46,9 +57,11 @@ namespace HRM.BO { BadLoginAttemptInfo Get(int id); List Get(); - int Save(BadLoginAttemptInfo item); + void Save(BadLoginAttemptInfo item); + void SaveInThread(BadLoginAttemptInfo item); List Get(DateTime dtFrom, DateTime dtTo); void Delete(int id); + List GetAuditTrail(DateTime dtFrom, DateTime dtTo); } #endregion diff --git a/HRM.BO/Basic/UserLogInInfo.cs b/HRM.BO/Basic/UserLogInInfo.cs index 8024e0c..70fd6c6 100644 --- a/HRM.BO/Basic/UserLogInInfo.cs +++ b/HRM.BO/Basic/UserLogInInfo.cs @@ -28,6 +28,18 @@ namespace HRM.BO public DateTime? LogoutTime { get; set; } public EnumLogoutType? LogoutType { get; set; } public string PCNumber { get; set; } + // Client of the login (UserLoginInfo_ClientInfo_DB_Changes.sql). + // Filled by UserLogInInfoService.Save from the HTTP request when not set. + public string IPAddress { get; set; } + /// Mobile / tab device id; null for a browser login. + public string DeviceId { get; set; } + #endregion + + #region Audit Trail (display only, not persisted) + + // Filled only by GetAuditTrail (joined from Users) for the System Audit Trail screen. + public string LoginID { get; set; } + public string UserName { get; set; } #endregion @@ -58,6 +70,7 @@ namespace HRM.BO void Delete(int id); void UpdateLogoutTime(int nLoginID); long NoofLogin(int nUserID); + List GetAuditTrail(DateTime dtFrom, DateTime dtTo); } #endregion diff --git a/HRM.BO/User/Role.cs b/HRM.BO/User/Role.cs index b426fef..5c48a2a 100644 --- a/HRM.BO/User/Role.cs +++ b/HRM.BO/User/Role.cs @@ -394,6 +394,13 @@ namespace HRM.BO routerLink = "/authentication/data-permssion", icon = "pi pi-fw pi-database", }, + new WebMenuItem() + { + uniqueName = "WEB.01.08", + label = "Audit log", + routerLink = "/authentication/system-auditlog", + icon = "pi pi-fw pi-database", + }, } }, diff --git a/HRM.DA/DA/Basic/BadLoginAttemptInfoDA.cs b/HRM.DA/DA/Basic/BadLoginAttemptInfoDA.cs index d1e4b98..521fd12 100644 --- a/HRM.DA/DA/Basic/BadLoginAttemptInfoDA.cs +++ b/HRM.DA/DA/Basic/BadLoginAttemptInfoDA.cs @@ -19,8 +19,9 @@ namespace HRM.DA internal static void Insert(TransactionContext tc, BadLoginAttemptInfo item) { - tc.ExecuteNonQuery("INSERT INTO BadLoginAttemptInfo(SlID, UserID, AttemptTime, PCNumber)" + - " VALUES(%n, %n, %D,%s)", item.ID, item.UserID, item.AttemptTime, item.PCNumber); + tc.ExecuteNonQuery("INSERT INTO BadLoginAttemptInfo(LoginID, AttemptTime, PCNumber, IPAddress, DeviceId)" + + " VALUES(%s, %D, %s, %s, %s)", + item.LoginID, item.AttemptTime, item.PCNumber, item.IPAddress, item.DeviceId); } #endregion @@ -46,6 +47,20 @@ namespace HRM.DA "select * from BadLoginAttemptInfo where AttemptTime between %D AND %D order by AttemptTime", dtf, dtt); } + // System Audit Trail: every bad login attempt in the date range (both days + // inclusive), with the user's LoginID / Name, newest first. + internal static IDataReader GetAuditTrail(TransactionContext tc, DateTime dtFrom, DateTime dtTo) + { + string sql = SQLParser.MakeSQL( + @"SELECT a.*, u.LoginID, u.UserName + FROM BadLoginAttemptInfo a + LEFT JOIN Users u ON u.LoginID = a.LoginID + WHERE a.AttemptTime >= %d AND a.AttemptTime < %d + ORDER BY a.AttemptTime DESC", + dtFrom.Date, dtTo.Date.AddDays(1)); + return tc.ExecuteReader(sql); + } + #endregion } } \ No newline at end of file diff --git a/HRM.DA/DA/Basic/UserLogInInfoDA.cs b/HRM.DA/DA/Basic/UserLogInInfoDA.cs index 0eb4111..9e3547c 100644 --- a/HRM.DA/DA/Basic/UserLogInInfoDA.cs +++ b/HRM.DA/DA/Basic/UserLogInInfoDA.cs @@ -20,9 +20,10 @@ namespace HRM.DA internal static void Insert(TransactionContext tc, UserLogInInfo item) { string sql = SQLParser.MakeSQL( - @"INSERT INTO UserLoginInfo(SLID, UserID, LoginTime, PCNumber,LogoutTime,LogoutType) - VALUES(%n, %n, %D,%s, %D,%n)", - item.ID, item.UserID, item.LoginTime, item.PCNumber, item.LogoutTime, item.LogoutType); + @"INSERT INTO UserLoginInfo(SLID, UserID, LoginTime, PCNumber, LogoutTime, LogoutType, IPAddress, DeviceId) + VALUES(%n, %n, %D, %s, %D, %n, %s, %s)", + item.ID, item.UserID, item.LoginTime, item.PCNumber, item.LogoutTime, item.LogoutType, + item.IPAddress, item.DeviceId); tc.ExecuteNonQuery(sql); } @@ -91,6 +92,20 @@ namespace HRM.DA dtf, dtt); } + // System Audit Trail: every login in the date range (both days inclusive), + // with the user's LoginID / Name, newest first. + internal static IDataReader GetAuditTrail(TransactionContext tc, DateTime dtFrom, DateTime dtTo) + { + string sql = SQLParser.MakeSQL( + @"SELECT a.*, u.LoginID, u.UserName + FROM UserLoginInfo a + LEFT JOIN Users u ON u.UserID = a.UserID + WHERE a.LoginTime >= %d AND a.LoginTime < %d + ORDER BY a.LoginTime DESC", + dtFrom.Date, dtTo.Date.AddDays(1)); + return tc.ExecuteReader(sql); + } + internal static long NoofLogin(TransactionContext tc, int UserID) { string sql = SQLParser.MakeSQL("SELECT Count(*) FROM UserLoginInfo WHERE UserID=%n ", UserID); diff --git a/HRM.DA/Service/Basic/BadLoginAttemptInfoService.cs b/HRM.DA/Service/Basic/BadLoginAttemptInfoService.cs index 7b18a44..b2f07ca 100644 --- a/HRM.DA/Service/Basic/BadLoginAttemptInfoService.cs +++ b/HRM.DA/Service/Basic/BadLoginAttemptInfoService.cs @@ -16,9 +16,11 @@ namespace HRM.DA private void MapObject(BadLoginAttemptInfo oBadLoginAttemptInfo, DataReader oReader) { base.SetObjectID(oBadLoginAttemptInfo, oReader.GetInt32("SlID").Value); - oBadLoginAttemptInfo.UserID = oReader.GetInt32("UserID", 0); + oBadLoginAttemptInfo.LoginID = oReader.GetString("LoginID"); oBadLoginAttemptInfo.AttemptTime = oReader.GetDateTime("AttemptTime").Value; oBadLoginAttemptInfo.PCNumber = oReader.GetString("PCNumber"); + oBadLoginAttemptInfo.IPAddress = oReader.GetString("IPAddress"); + oBadLoginAttemptInfo.DeviceId = oReader.GetString("DeviceId"); } protected override T CreateObject(DataReader oReader) @@ -125,19 +127,58 @@ namespace HRM.DA return BadLoginAttemptInfos; } - public int Save(BadLoginAttemptInfo oBadLoginAttemptInfo) + public List GetAuditTrail(DateTime dtFrom, DateTime dtTo) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(BadLoginAttemptInfoDA.GetAuditTrail(tc, dtFrom, dtTo)); + while (dr.Read()) + { + BadLoginAttemptInfo item = this.CreateObject(dr); + item.LoginID = dr.GetString("LoginID"); + item.UserName = dr.GetString("UserName"); + items.Add(item); + } + dr.Close(); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + return items; + } + + public void Save(BadLoginAttemptInfo oBadLoginAttemptInfo) { TransactionContext tc = null; try { + // IP / device id come from the request (only reachable here when Save runs on + // the request thread; SaveInThread captures them before it leaves it). The + // computer name is a reverse-DNS lookup of that IP, done here because it can + // take a moment and SaveInThread runs this off the request thread. + CaptureRequestInfo(oBadLoginAttemptInfo); + if (string.IsNullOrWhiteSpace(oBadLoginAttemptInfo.PCNumber)) + oBadLoginAttemptInfo.PCNumber = ClientRequestInfo.ResolveComputerName(oBadLoginAttemptInfo.IPAddress); + tc = TransactionContext.Begin(true); - int id = tc.GenerateID("BadLoginAttemptInfo", "SlID"); - base.SetObjectID(oBadLoginAttemptInfo, id); BadLoginAttemptInfoDA.Insert(tc, oBadLoginAttemptInfo); tc.End(); - return oBadLoginAttemptInfo.ID; + } catch (Exception e) { @@ -152,6 +193,30 @@ namespace HRM.DA } } + public void SaveInThread(BadLoginAttemptInfo oBadLoginAttemptInfo) + { + // Read the request NOW: by the time the thread runs, the request may be over. + CaptureRequestInfo(oBadLoginAttemptInfo); + + System.Threading.Thread saveThread = new System.Threading.Thread(() => Save(oBadLoginAttemptInfo)) + { + IsBackground = true + }; + + saveThread.Start(); + } + + /// + /// Fills IPAddress and DeviceId from the current request, keeping whatever the caller + /// already set (e.g. the mobile login knows the DeviceID from its request body). + /// + private static void CaptureRequestInfo(BadLoginAttemptInfo oBadLoginAttemptInfo) + { + if (string.IsNullOrWhiteSpace(oBadLoginAttemptInfo.IPAddress)) + oBadLoginAttemptInfo.IPAddress = ClientRequestInfo.GetIPAddress(); + if (string.IsNullOrWhiteSpace(oBadLoginAttemptInfo.DeviceId)) + oBadLoginAttemptInfo.DeviceId = ClientRequestInfo.GetDeviceId(); + } public void Delete(int id) { diff --git a/HRM.DA/Service/Basic/ClientRequestInfo.cs b/HRM.DA/Service/Basic/ClientRequestInfo.cs new file mode 100644 index 0000000..77aff0a --- /dev/null +++ b/HRM.DA/Service/Basic/ClientRequestInfo.cs @@ -0,0 +1,111 @@ +using System; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; + +namespace HRM.DA +{ + /// + /// Who is on the other end of the current HTTP request: IP address, device id + /// (mobile / tab) and computer name. + /// + /// Services in HRM.DA are created with new, not through DI, so they read the + /// request through the one that Startup hands to + /// . Read it on the request thread only: once the request + /// has finished (e.g. inside a background save thread) there is no context left. + /// + /// Note Environment.MachineName / Dns.GetHostName() are the name of + /// the web SERVER, never the user's computer. + /// + public static class ClientRequestInfo + { + /// Headers a mobile / tab app may send its device id in (first one found wins). + private static readonly string[] DeviceIdHeaders = { "X-Device-Id", "DeviceId", "DeviceID", "Device-Id" }; + + /// A reverse-DNS lookup that has no answer can hang for seconds; never wait longer than this. + private static readonly TimeSpan HostLookupTimeout = TimeSpan.FromSeconds(2); + + private static IHttpContextAccessor _accessor; + + /// Called once from Startup.Configure. + public static void Configure(IHttpContextAccessor accessor) + { + _accessor = accessor; + } + + /// The current request, or null outside a request (background thread, console job). + private static HttpContext Current => _accessor?.HttpContext; + + /// + /// The client's IP: the first X-Forwarded-For entry when behind a proxy / load balancer + /// (the same rule as the login rate limiter in Startup), else the socket's remote address. + /// + public static string GetIPAddress() + { + HttpContext context = Current; + if (context == null) + return null; + + string forwarded = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); + if (!string.IsNullOrWhiteSpace(forwarded)) + { + string first = forwarded.Split(',')[0].Trim(); + if (first != string.Empty) + return first; + } + + IPAddress remote = context.Connection.RemoteIpAddress; + if (remote == null) + return null; + if (remote.IsIPv4MappedToIPv6) + remote = remote.MapToIPv4(); + return remote.Equals(IPAddress.IPv6Loopback) + ? IPAddress.Loopback.ToString() // "::1" -> "127.0.0.1" + : remote.ToString(); + } + + /// The device id a mobile / tab app sent as a request header, or null (browser). + public static string GetDeviceId() + { + HttpContext context = Current; + if (context == null) + return null; + + foreach (string header in DeviceIdHeaders) + { + string value = context.Request.Headers[header].FirstOrDefault(); + if (!string.IsNullOrWhiteSpace(value)) + return value.Trim(); + } + return null; + } + + /// + /// The client's computer name by reverse DNS of its IP. Works on a company network + /// whose DNS registers workstations; otherwise (internet, mobile data) there is no + /// name and the IP itself is returned. Blocks for at most , + /// so call it off the request thread where possible. + /// + public static string ResolveComputerName(string ipAddress) + { + if (string.IsNullOrWhiteSpace(ipAddress) || !IPAddress.TryParse(ipAddress, out IPAddress ip)) + return ipAddress; + + if (IPAddress.IsLoopback(ip)) + return Environment.MachineName; // the user is on the server itself + + try + { + Task lookup = Dns.GetHostEntryAsync(ip); + if (lookup.Wait(HostLookupTimeout) && !string.IsNullOrWhiteSpace(lookup.Result?.HostName)) + return lookup.Result.HostName; + } + catch (Exception) + { + // No PTR record / DNS unreachable: fall back to the IP. + } + return ipAddress; + } + } +} diff --git a/HRM.DA/Service/Basic/UserLogInInfoService.cs b/HRM.DA/Service/Basic/UserLogInInfoService.cs index 03a7ac8..b20d3f1 100644 --- a/HRM.DA/Service/Basic/UserLogInInfoService.cs +++ b/HRM.DA/Service/Basic/UserLogInInfoService.cs @@ -19,6 +19,8 @@ namespace HRM.DA oUserLogInInfo.UserID = oReader.GetInt32("UserID", 0); oUserLogInInfo.LoginTime = oReader.GetDateTime("LoginTime").Value; oUserLogInInfo.PCNumber = oReader.GetString("PCNumber"); + oUserLogInInfo.IPAddress = oReader.GetString("IPAddress"); + oUserLogInInfo.DeviceId = oReader.GetString("DeviceId"); if (oReader.GetDateTime("LogoutTime") != null) oUserLogInInfo.LogoutTime = Convert.ToDateTime(oReader.GetString("LogoutTime")); oUserLogInInfo.LogoutType = oReader.GetString("LogoutType") == null @@ -217,6 +219,39 @@ namespace HRM.DA return UserLogInInfos; } + public List GetAuditTrail(DateTime dtFrom, DateTime dtTo) + { + List items = new List(); + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader dr = new DataReader(UserLogInInfoDA.GetAuditTrail(tc, dtFrom, dtTo)); + while (dr.Read()) + { + UserLogInInfo item = this.CreateObject(dr); + item.LoginID = dr.GetString("LoginID"); + item.UserName = dr.GetString("UserName"); + items.Add(item); + } + dr.Close(); + tc.End(); + } + catch (Exception e) + { + #region Handle Exception + + if (tc != null) + tc.HandleError(); + ExceptionLog.Write(e); + throw new ServiceException(e.Message, e); + + #endregion + } + + return items; + } + public long NoofLogin(int nUserID) { long nCount = 0; @@ -247,6 +282,10 @@ namespace HRM.DA TransactionContext tc = null; try { + // Before the transaction: the computer-name lookup can take a moment. + if (oUserLogInInfo.IsNew) + FillClientInfo(oUserLogInInfo); + tc = TransactionContext.Begin(true); if (oUserLogInInfo.IsNew) { @@ -280,6 +319,7 @@ namespace HRM.DA { if (oUserLogInInfo.IsNew) { + FillClientInfo(oUserLogInInfo); UserLogInInfoDA.Insert(tc, oUserLogInInfo); } else UserLogInInfoDA.Update(tc, oUserLogInInfo); @@ -300,6 +340,31 @@ namespace HRM.DA + /// + /// Fills IPAddress and DeviceId from the current HTTP request, keeping whatever the + /// caller already set (e.g. the mobile login knows the DeviceID from its request body). + /// Call it on the request thread BEFORE handing the login to a background thread + /// (UserService.SaveLoginfo): once the request is over there is nothing left to read. + /// + public static void CaptureRequestInfo(UserLogInInfo oUserLogInInfo) + { + if (string.IsNullOrWhiteSpace(oUserLogInInfo.IPAddress)) + oUserLogInInfo.IPAddress = ClientRequestInfo.GetIPAddress(); + if (string.IsNullOrWhiteSpace(oUserLogInInfo.DeviceId)) + oUserLogInInfo.DeviceId = ClientRequestInfo.GetDeviceId(); + } + + /// + /// IP / device id from the request (when still reachable), then the computer name: + /// reverse DNS of that IP, or the IP itself when the network has no name for it. + /// + private static void FillClientInfo(UserLogInInfo oUserLogInInfo) + { + CaptureRequestInfo(oUserLogInInfo); + if (string.IsNullOrWhiteSpace(oUserLogInInfo.PCNumber)) + oUserLogInInfo.PCNumber = ClientRequestInfo.ResolveComputerName(oUserLogInInfo.IPAddress); + } + public void Delete(int id) { //Not Needed diff --git a/HRM.DA/Service/Users/UserService.cs b/HRM.DA/Service/Users/UserService.cs index d37d59a..b34c0aa 100644 --- a/HRM.DA/Service/Users/UserService.cs +++ b/HRM.DA/Service/Users/UserService.cs @@ -437,9 +437,7 @@ namespace HRM.DA UserLogInInfo login = new UserLogInInfo(); login.UserID = userID; login.LoginTime = DateTime.Now; - login.PCNumber = Environment.MachineName + " ," + - System.Net.Dns.GetHostName() + " ," + - Environment.GetEnvironmentVariable("COMPUTERNAME"); + UserLogInInfoService.CaptureRequestInfo(login); // on the request thread, before the save thread Thread myNewThread = new Thread(() => SaveLoginfo(login)); myNewThread.Start(); } @@ -496,6 +494,7 @@ namespace HRM.DA login.UserID = oUser.ID; login.LoginTime = DateTime.Now; + UserLogInInfoService.CaptureRequestInfo(login); // on the request thread, before the save thread Thread myNewThread = new Thread(() => SaveLoginfo(login)); myNewThread.Start(); @@ -552,6 +551,7 @@ namespace HRM.DA login.UserID = oUser.ID; login.LoginTime = DateTime.Now; + UserLogInInfoService.CaptureRequestInfo(login); // on the request thread, before the save thread Thread myNewThread = new Thread(() => SaveLoginfo(login)); myNewThread.Start(); } @@ -589,6 +589,7 @@ namespace HRM.DA login.UserID = oUser.ID; login.LoginTime = DateTime.Now; login.PCNumber = hostName; + UserLogInInfoService.CaptureRequestInfo(login); // on the request thread, before the save thread Thread myNewThread = new Thread(() => SaveLoginfo(login)); myNewThread.Start(); } @@ -640,9 +641,10 @@ namespace HRM.DA public void SaveLoginfo(UserLogInInfo oTran) { - oTran.PCNumber = Environment.MachineName + " ," + - System.Net.Dns.GetHostName() + " ," + - Environment.GetEnvironmentVariable("COMPUTERNAME"); + // PCNumber used to be Environment.MachineName / Dns.GetHostName() - the web + // SERVER's name, the same for every login. UserLogInInfoService.Save now fills it + // with the client's computer name (reverse DNS of its IP) unless the caller set it + // (GetByLoginIDAndPasswordAndHostName passes the host name it was given). new UserLogInInfoService().Save(oTran); //if(GlobalFunctions.defaultConfigVal == null) //{ @@ -983,7 +985,16 @@ namespace HRM.DA if (tc != null) tc.HandleError(); ExceptionLog.Write(e); - throw new ServiceException(e.Message, e); + + // Unique index Unique_EmpNo on dbo.USERS: this employee already has a user. + for (Exception inner = e; inner != null; inner = inner.InnerException) + { + if (inner.Message.IndexOf("Cannot insert duplicate key row", StringComparison.OrdinalIgnoreCase) >= 0 + && inner.Message.IndexOf("Unique_EmpNo", StringComparison.OrdinalIgnoreCase) >= 0) + throw new ServiceException("User already exist in the system", e); + } + + throw new ServiceException("Failed to Create/Update user.", e); #endregion } } @@ -1144,6 +1155,7 @@ namespace HRM.DA login.UserID = oUser.ID; login.LoginTime = DateTime.Now; + UserLogInInfoService.CaptureRequestInfo(login); // on the request thread, before the save thread Thread myNewThread = new Thread(() => SaveLoginfo(login)); myNewThread.Start(); } diff --git a/HRM.UI/ClientApp/src/app/_models/Authentication/auditTrail.ts b/HRM.UI/ClientApp/src/app/_models/Authentication/auditTrail.ts new file mode 100644 index 0000000..d2ec992 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/_models/Authentication/auditTrail.ts @@ -0,0 +1,49 @@ +import { BaseObject } from '../Basic/baseObject'; + +/** One successful login (dbo.UserLoginInfo), as returned by api/Authentication/getUserAuditTrail. */ +export class UserLogInInfo extends BaseObject { + userID: number; + loginTime: Date; + logoutTime?: Date; + logoutType?: number; + pcNumber: string; + ipAddress: string; + /** Mobile / tab device id; null for a browser login. */ + deviceId: string; + loginID: string; + userName: string; + constructor() { + super(); + this.userID = 0; + this.loginTime = undefined; + this.logoutTime = undefined; + this.logoutType = undefined; + this.pcNumber = ''; + this.ipAddress = ''; + this.deviceId = ''; + this.loginID = ''; + this.userName = ''; + } +} + +/** One failed login (dbo.BadLoginAttemptInfo), as returned by api/Authentication/getBadLoginAuditTrail. */ +export class BadLoginAttemptInfo extends BaseObject { + userID: number; + attemptTime: Date; + pcNumber: string; + ipAddress: string; + /** Mobile / tab device id; null for a browser login. */ + deviceId: string; + loginID: string; + userName: string; + constructor() { + super(); + this.userID = 0; + this.attemptTime = undefined; + this.pcNumber = ''; + this.ipAddress = ''; + this.deviceId = ''; + this.loginID = ''; + this.userName = ''; + } +} diff --git a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts index 32122f3..56990b7 100644 --- a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts @@ -12,6 +12,7 @@ import { PayrollType } from '../../_models/Authentication/payrollType'; import { UserRole } from '../../_models/Authentication/UserRole'; import { UserAccessType } from '../../_models/Authentication/UserAccessType'; import { PasswordHistory } from '../../_models/Authentication/passwordHistory'; +import { UserLogInInfo, BadLoginAttemptInfo } from '../../_models/Authentication/auditTrail'; import { Router } from '@angular/router'; import { Bookmark } from '../../_models/Basic/bookmark'; import { Subject } from 'rxjs'; @@ -136,6 +137,15 @@ export class AuthService { GetAllUsers() { return this.apiService.httpGet('/Authentication/getAllUsers'); } + /** Dates are sent as dd-MMM-yyyy; both days are inclusive. */ + getUserAuditTrail(fromDate: Date, toDate: Date) { + return this.apiService.httpGet('/Authentication/getUserAuditTrail/' + + this.apiService.getApiDateString(fromDate) + '/' + this.apiService.getApiDateString(toDate)); + } + getBadLoginAuditTrail(fromDate: Date, toDate: Date) { + return this.apiService.httpGet('/Authentication/getBadLoginAuditTrail/' + + this.apiService.getApiDateString(fromDate) + '/' + this.apiService.getApiDateString(toDate)); + } getBookmarks() { return this.apiService.httpGet('/Authentication/getBookmarks'); } diff --git a/HRM.UI/ClientApp/src/app/authentication/authentication-routing.module.ts b/HRM.UI/ClientApp/src/app/authentication/authentication-routing.module.ts index f237c8f..b105506 100644 --- a/HRM.UI/ClientApp/src/app/authentication/authentication-routing.module.ts +++ b/HRM.UI/ClientApp/src/app/authentication/authentication-routing.module.ts @@ -9,6 +9,7 @@ import { UserRoleComponent } from './user-role/user-role.component'; import { UserAccessTypeComponent } from './user-access-type/user-access-type.component'; import {ChangePasswordComponent} from './change-password/change-password.component'; import { DataPermssionComponent } from './data-permssion/data-permssion.component'; +import { SystemAuditTrailComponent } from './system-audittrail/system.audittrail.component'; @@ -20,6 +21,7 @@ export const routes: Routes = [ { path: 'user-access-type', component: UserAccessTypeComponent, canActivate: [AuthGuard] }, { path: 'change-password', component: ChangePasswordComponent, canActivate: [AuthGuard] }, { path: 'data-permssion', component: DataPermssionComponent, canActivate: [AuthGuard] }, + { path: 'system-auditlog', component: SystemAuditTrailComponent, canActivate: [AuthGuard] }, ]; diff --git a/HRM.UI/ClientApp/src/app/authentication/authentication.module.ts b/HRM.UI/ClientApp/src/app/authentication/authentication.module.ts index df61079..27e348b 100644 --- a/HRM.UI/ClientApp/src/app/authentication/authentication.module.ts +++ b/HRM.UI/ClientApp/src/app/authentication/authentication.module.ts @@ -107,6 +107,9 @@ import { LoadingPanelModule } from '../hrm-loding panel/loading-panel.module'; import { DataPermssionComponent } from './data-permssion/data-permssion.component'; import { CheckBoxModule } from '@progress/kendo-angular-inputs'; import { KENDO_TREEVIEW } from '@progress/kendo-angular-treeview'; +import { LayoutModule } from '@progress/kendo-angular-layout'; +import { ExcelExportModule } from '@progress/kendo-angular-excel-export'; +import { SystemAuditTrailComponent } from './system-audittrail/system.audittrail.component'; @NgModule({ @@ -201,6 +204,8 @@ import { KENDO_TREEVIEW } from '@progress/kendo-angular-treeview'; //SharedModule, //BodyModule, LoadingPanelModule, + LayoutModule, + ExcelExportModule, //InputTextareaModule, ], @@ -219,7 +224,8 @@ import { KENDO_TREEVIEW } from '@progress/kendo-angular-treeview'; UserAccessTypeComponent, ChangePasswordComponent, UserComponent, - DataPermssionComponent + DataPermssionComponent, + SystemAuditTrailComponent ], providers: [ AppWindowPopUp, diff --git a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.html b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.html new file mode 100644 index 0000000..a0c3b56 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.html @@ -0,0 +1,169 @@ + + +
+ + + + + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + + + + + + {{ userGrid.filteredCount | number }} of {{ userGrid.rows.length | number }} records + + + + + + + + + + + + + + + {{ userGrid.loaded ? 'No login found for this date range.' : 'Select a date range and press Load.' }} + + + + + + + + + + + + + + + +
+
+ + + + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + + + + + + {{ badGrid.filteredCount | number }} of {{ badGrid.rows.length | number }} records + + + + + + + + + + + + + + {{ badGrid.loaded ? 'No bad login attempt found for this date range.' : 'Select a date range and press Load.' }} + + + + + + + + + + + + + + +
+
+ +
+
diff --git a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.scss b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.scss new file mode 100644 index 0000000..16ce36b --- /dev/null +++ b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.scss @@ -0,0 +1,18 @@ +.audit-trail-filter { + margin: 0.5rem 0 0.75rem; + align-items: center; +} + +.audit-trail-label { + margin: auto; +} + +.audit-trail-search { + width: 280px; +} + +.audit-trail-count { + margin-left: 0.5rem; + font-size: 0.875rem; + opacity: 0.75; +} diff --git a/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.ts b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.ts new file mode 100644 index 0000000..88a2187 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/authentication/system-audittrail/system.audittrail.component.ts @@ -0,0 +1,236 @@ +import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; +import { DataStateChangeEvent, GridComponent, GridDataResult } from '@progress/kendo-angular-grid'; +import { type ExcelExportData } from '@progress/kendo-angular-excel-export'; +import { process, State } from '@progress/kendo-data-query'; +import { ApiService } from '../../app.api.service'; +import { AuthService } from '../../_services/auth/auth.service'; +import { HRMNotificationService } from '../../app.notification.service'; +import { loadingPanelService } from '../../hrm-loding panel/loding.panel.service'; +import { UserLogInInfo, BadLoginAttemptInfo } from '../../_models/Authentication/auditTrail'; + +/** Rows per virtual "page" - enough to fill the grid viewport a few times over. */ +const PAGE_SIZE = 60; + +/** Above this many rows a PDF (every row is rendered to the DOM first) would hang the browser. */ +const PDF_ROW_LIMIT = 5000; + +/** One grid row, the same shape for both tabs. */ +export interface AuditTrailRow { + loginID: string; + userName: string; + punchTime: Date; + pcNumber: string; + ipAddress: string; + deviceId: string; +} + +/** + * State of one audit-trail grid: all loaded rows, the toolbar search, and the + * grid's sort / filter / virtual-scroll state. Everything is done client side over + * the rows of the selected date range. + */ +export class AuditTrailGrid { + rows: AuditTrailRow[] = []; + private searched: AuditTrailRow[] = []; + searchText = ''; + loaded = false; + state: State = { skip: 0, take: PAGE_SIZE, sort: [{ field: 'punchTime', dir: 'desc' }], filter: { logic: 'and', filters: [] } }; + view: GridDataResult = { data: [], total: 0 }; + + constructor(private searchFields: (keyof AuditTrailRow)[]) { } + + setRows(rows: AuditTrailRow[]): void { + this.rows = rows; + this.loaded = true; + this.state = { ...this.state, skip: 0 }; + this.applySearch(); + } + + onSearch(text: string): void { + this.searchText = text ?? ''; + this.state = { ...this.state, skip: 0 }; + this.applySearch(); + } + + /** Fired for virtual scrolling, sorting, column filters and the PDF export's "all pages" pass. */ + onStateChange(state: DataStateChangeEvent): void { + this.state = state; + this.refresh(); + } + + /** Rows left after the search and the column filters (what Excel / PDF export). */ + get filteredCount(): number { + return this.view.total; + } + + /** Excel exports every searched + filtered + sorted row, not just the rendered page. */ + allData = (): ExcelExportData => ({ + data: process(this.searched, { sort: this.state.sort, filter: this.state.filter }).data + }); + + private applySearch(): void { + const text = this.searchText.trim().toLowerCase(); + this.searched = text === '' + ? this.rows + : this.rows.filter(r => this.searchFields.some(f => AuditTrailGrid.searchValue(r, f).includes(text))); + this.refresh(); + } + + private refresh(): void { + this.view = process(this.searched, this.state); + } + + private static searchValue(row: AuditTrailRow, field: keyof AuditTrailRow): string { + const value = row[field]; + if (value === undefined || value === null) { + return ''; + } + if (value instanceof Date) { + return AuditTrailGrid.formatDate(value).toLowerCase(); + } + return value.toString().toLowerCase(); + } + + /** dd-MMM-yyyy hh:mm:ss AM - the same text the grid shows, so the search matches what is on screen. */ + static formatDate(d: Date): string { + const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + const pad = (n: number) => (n < 10 ? '0' : '') + n; + const h = d.getHours() % 12 === 0 ? 12 : d.getHours() % 12; + return pad(d.getDate()) + '-' + months[d.getMonth()] + '-' + d.getFullYear() + ' ' + + pad(h) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + ' ' + (d.getHours() < 12 ? 'AM' : 'PM'); + } +} + +@Component({ + selector: 'app-system-audittrail', + templateUrl: './system.audittrail.component.html', + styleUrls: ['./system.audittrail.component.scss'], + changeDetection: ChangeDetectionStrategy.Eager, + standalone: false, +}) +export class SystemAuditTrailComponent implements OnInit { + + readonly pageSize = PAGE_SIZE; + readonly gridDateFormat = '{0:dd-MMM-yyyy hh:mm:ss a}'; + readonly excelDateFormat = 'dd-mmm-yyyy hh:mm:ss AM/PM'; + + userFromDate: Date; + userToDate: Date; + userGrid = new AuditTrailGrid(['loginID', 'userName', 'punchTime', 'pcNumber', 'ipAddress', 'deviceId']); + + badFromDate: Date; + badToDate: Date; + badGrid = new AuditTrailGrid(['loginID', 'punchTime', 'pcNumber', 'ipAddress', 'deviceId']); + + constructor(public apiService: ApiService, + public authService: AuthService, + public notificationService: HRMNotificationService, + public loadingPanel: loadingPanelService) { + this.apiService.selectedMenuName = 'System audit log'; + } + + ngOnInit(): void { + const today = new Date(); + today.setHours(0, 0, 0, 0); + const weekAgo = new Date(today); + weekAgo.setDate(weekAgo.getDate() - 7); + + this.userFromDate = new Date(weekAgo); + this.userToDate = new Date(today); + this.badFromDate = new Date(weekAgo); + this.badToDate = new Date(today); + this.loadingPanel.ShowLoadingPanel = false; + } + + // -- Tab 1: User Audit Trail --------------------------------------------- + + loadUserAuditTrail(): void { + if (!this.validDateRange(this.userFromDate, this.userToDate)) { + return; + } + this.loadingPanel.ShowLoadingPanel = true; + this.authService.getUserAuditTrail(this.userFromDate, this.userToDate).subscribe({ + next: (items: UserLogInInfo[]) => { + this.userGrid.setRows((items ?? []).map(x => ({ + loginID: x.loginID ?? '', + userName: x.userName ?? '', + punchTime: x.loginTime ? new Date(x.loginTime) : null, + pcNumber: x.pcNumber ?? '', + ipAddress: x.ipAddress ?? '', + deviceId: x.deviceId ?? '' + }))); + this.loadingPanel.ShowLoadingPanel = false; + }, + error: (err) => { + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showError(err?.error ?? 'Could not load the user audit trail.'); + } + }); + } + + // -- Tab 2: Bad Login Attempt -------------------------------------------- + + loadBadLoginAttempts(): void { + if (!this.validDateRange(this.badFromDate, this.badToDate)) { + return; + } + this.loadingPanel.ShowLoadingPanel = true; + this.authService.getBadLoginAuditTrail(this.badFromDate, this.badToDate).subscribe({ + next: (items: BadLoginAttemptInfo[]) => { + this.badGrid.setRows((items ?? []).map(x => ({ + loginID: x.loginID ?? '', + userName: x.userName ?? '', + punchTime: x.attemptTime ? new Date(x.attemptTime) : null, + pcNumber: x.pcNumber ?? '', + ipAddress: x.ipAddress ?? '', + deviceId: x.deviceId ?? '' + }))); + this.loadingPanel.ShowLoadingPanel = false; + }, + error: (err) => { + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showError(err?.error ?? 'Could not load the bad login attempts.'); + } + }); + } + + // -- Shared ---------------------------------------------------------------- + + /** PDF renders every row into the page first, so refuse it for very large results. */ + exportPdf(grid: GridComponent, auditGrid: AuditTrailGrid): void { + if (auditGrid.filteredCount === 0) { + this.notificationService.showError('There is no data to export.'); + return; + } + if (auditGrid.filteredCount > PDF_ROW_LIMIT) { + this.notificationService.showError('PDF export is limited to ' + PDF_ROW_LIMIT.toLocaleString() + + ' rows (' + auditGrid.filteredCount.toLocaleString() + ' now). Narrow the date range, search or filter, or use Export to Excel.'); + return; + } + grid.saveAsPDF(); + } + + exportExcel(grid: GridComponent, auditGrid: AuditTrailGrid): void { + if (auditGrid.filteredCount === 0) { + this.notificationService.showError('There is no data to export.'); + return; + } + grid.saveAsExcel(); + } + + fileName(prefix: string, from: Date, to: Date, ext: string): string { + return prefix + '_' + this.apiService.getApiDateString(from) + '_to_' + this.apiService.getApiDateString(to) + '.' + ext; + } + + private validDateRange(from: Date, to: Date): boolean { + if (!from || !to) { + this.notificationService.showError('Please select From date and To date.'); + return false; + } + if (from.getTime() > to.getTime()) { + this.notificationService.showError('From date can not be after To date.'); + return false; + } + return true; + } +} diff --git a/HRM.UI/ClientApp/src/app/authentication/users/users-entry/users-entry.component.html b/HRM.UI/ClientApp/src/app/authentication/users/users-entry/users-entry.component.html index 8d33723..a12cffd 100644 --- a/HRM.UI/ClientApp/src/app/authentication/users/users-entry/users-entry.component.html +++ b/HRM.UI/ClientApp/src/app/authentication/users/users-entry/users-entry.component.html @@ -40,7 +40,13 @@
- + + @if (fromValidator.get('email')?.invalid && fromValidator.get('email')?.value) { + + Please enter a valid e-mail address. + + }