correction

This commit is contained in:
salauddin.shamim 2026-11-12 14:58:04 +06:00
parent f36dab75f3
commit 2e028a211c
26 changed files with 1086 additions and 33 deletions

View File

@ -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

View File

@ -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 `<Feature>_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_<db>.txt`, `TablesWithoutPK_<db>.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: `<app-loading-panel></app-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 `<app-loading-panel>` 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

View File

@ -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; }
/// <summary>Mobile / tab device id; null for a browser login.</summary>
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<BadLoginAttemptInfo> Get();
int Save(BadLoginAttemptInfo item);
void Save(BadLoginAttemptInfo item);
void SaveInThread(BadLoginAttemptInfo item);
List<BadLoginAttemptInfo> Get(DateTime dtFrom, DateTime dtTo);
void Delete(int id);
List<BadLoginAttemptInfo> GetAuditTrail(DateTime dtFrom, DateTime dtTo);
}
#endregion

View File

@ -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; }
/// <summary>Mobile / tab device id; null for a browser login.</summary>
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<UserLogInInfo> GetAuditTrail(DateTime dtFrom, DateTime dtTo);
}
#endregion

View File

@ -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",
},
}
},

View File

@ -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
}
}

View File

@ -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);

View File

@ -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<T>(DataReader oReader)
@ -125,19 +127,58 @@ namespace HRM.DA
return BadLoginAttemptInfos;
}
public int Save(BadLoginAttemptInfo oBadLoginAttemptInfo)
public List<BadLoginAttemptInfo> GetAuditTrail(DateTime dtFrom, DateTime dtTo)
{
List<BadLoginAttemptInfo> items = new List<BadLoginAttemptInfo>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(BadLoginAttemptInfoDA.GetAuditTrail(tc, dtFrom, dtTo));
while (dr.Read())
{
BadLoginAttemptInfo item = this.CreateObject<BadLoginAttemptInfo>(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();
}
/// <summary>
/// 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).
/// </summary>
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)
{

View File

@ -0,0 +1,111 @@
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace HRM.DA
{
/// <summary>
/// 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 <c>new</c>, not through DI, so they read the
/// request through the one <see cref="IHttpContextAccessor"/> that Startup hands to
/// <see cref="Configure"/>. 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 <c>Environment.MachineName</c> / <c>Dns.GetHostName()</c> are the name of
/// the web SERVER, never the user's computer.
/// </summary>
public static class ClientRequestInfo
{
/// <summary>Headers a mobile / tab app may send its device id in (first one found wins).</summary>
private static readonly string[] DeviceIdHeaders = { "X-Device-Id", "DeviceId", "DeviceID", "Device-Id" };
/// <summary>A reverse-DNS lookup that has no answer can hang for seconds; never wait longer than this.</summary>
private static readonly TimeSpan HostLookupTimeout = TimeSpan.FromSeconds(2);
private static IHttpContextAccessor _accessor;
/// <summary>Called once from Startup.Configure.</summary>
public static void Configure(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
/// <summary>The current request, or null outside a request (background thread, console job).</summary>
private static HttpContext Current => _accessor?.HttpContext;
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>The device id a mobile / tab app sent as a request header, or null (browser).</summary>
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;
}
/// <summary>
/// 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 <see cref="HostLookupTimeout"/>,
/// so call it off the request thread where possible.
/// </summary>
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<IPHostEntry> 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;
}
}
}

View File

@ -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<UserLogInInfo> GetAuditTrail(DateTime dtFrom, DateTime dtTo)
{
List<UserLogInInfo> items = new List<UserLogInInfo>();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(UserLogInInfoDA.GetAuditTrail(tc, dtFrom, dtTo));
while (dr.Read())
{
UserLogInInfo item = this.CreateObject<UserLogInInfo>(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
/// <summary>
/// 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.
/// </summary>
public static void CaptureRequestInfo(UserLogInInfo oUserLogInInfo)
{
if (string.IsNullOrWhiteSpace(oUserLogInInfo.IPAddress))
oUserLogInInfo.IPAddress = ClientRequestInfo.GetIPAddress();
if (string.IsNullOrWhiteSpace(oUserLogInInfo.DeviceId))
oUserLogInInfo.DeviceId = ClientRequestInfo.GetDeviceId();
}
/// <summary>
/// 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.
/// </summary>
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

View File

@ -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();
}

View File

@ -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 = '';
}
}

View File

@ -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<User[]>('/Authentication/getAllUsers');
}
/** Dates are sent as dd-MMM-yyyy; both days are inclusive. */
getUserAuditTrail(fromDate: Date, toDate: Date) {
return this.apiService.httpGet<UserLogInInfo[]>('/Authentication/getUserAuditTrail/' +
this.apiService.getApiDateString(fromDate) + '/' + this.apiService.getApiDateString(toDate));
}
getBadLoginAuditTrail(fromDate: Date, toDate: Date) {
return this.apiService.httpGet<BadLoginAttemptInfo[]>('/Authentication/getBadLoginAuditTrail/' +
this.apiService.getApiDateString(fromDate) + '/' + this.apiService.getApiDateString(toDate));
}
getBookmarks() {
return this.apiService.httpGet<Bookmark[]>('/Authentication/getBookmarks');
}

View File

@ -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] },
];

View File

@ -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,

View File

@ -0,0 +1,169 @@
<app-loading-panel></app-loading-panel>
<div class="card card-w-title audit-trail">
<kendo-tabstrip [keepTabContent]="true">
<!-- ── Tab 1: User Audit Trail (dbo.UserLoginInfo) ── -->
<kendo-tabstrip-tab title="User Audit Trail" [selected]="true">
<ng-template kendoTabContent>
<div class="grid audit-trail-filter">
<div class="col-12 md:col-1 audit-trail-label">
<label for="dtUserFrom">From Date</label>
</div>
<div class="col-12 md:col-3">
<kendo-datepicker id="dtUserFrom" [(ngModel)]="userFromDate" [format]="'dd-MMM-yyyy'" [max]="userToDate"
style="width: 100%"></kendo-datepicker>
</div>
<div class="col-12 md:col-1 audit-trail-label">
<label for="dtUserTo">To Date</label>
</div>
<div class="col-12 md:col-3">
<kendo-datepicker id="dtUserTo" [(ngModel)]="userToDate" [format]="'dd-MMM-yyyy'" [min]="userFromDate"
style="width: 100%"></kendo-datepicker>
</div>
<div class="col-12 md:col-2">
<button kendoButton themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['search']"
(click)="loadUserAuditTrail()" style="width: 100%;">Load</button>
</div>
</div>
<kendo-grid #userGridRef
[data]="userGrid.view"
[skip]="userGrid.state.skip"
[pageSize]="pageSize"
[sort]="userGrid.state.sort"
[filter]="userGrid.state.filter"
[sortable]="true"
filterable="menu"
scrollable="virtual"
[rowHeight]="36"
[height]="520"
[navigable]="true"
(dataStateChange)="userGrid.onStateChange($event)">
<ng-template kendoGridToolbarTemplate>
<input kendoTextBox class="audit-trail-search" placeholder="Search in all columns..."
[value]="userGrid.searchText" (input)="userGrid.onSearch($any($event.target).value)" />
<span class="audit-trail-count">
{{ userGrid.filteredCount | number }} of {{ userGrid.rows.length | number }} records
</span>
<kendo-grid-spacer></kendo-grid-spacer>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
(click)="exportExcel(userGridRef, userGrid)">Export to Excel</button>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['filePdf']"
(click)="exportPdf(userGridRef, userGrid)">Export to PDF</button>
</ng-template>
<kendo-grid-column field="loginID" title="Login ID" [width]="160"></kendo-grid-column>
<kendo-grid-column field="userName" title="Name" [width]="240"></kendo-grid-column>
<kendo-grid-column field="punchTime" title="Punch Time" [width]="210" filter="date"
[format]="gridDateFormat"></kendo-grid-column>
<kendo-grid-column field="pcNumber" title="Computer" [width]="260"></kendo-grid-column>
<kendo-grid-column field="ipAddress" title="IP Address" [width]="150"></kendo-grid-column>
<kendo-grid-column field="deviceId" title="Device ID" [width]="220"></kendo-grid-column>
<ng-template kendoGridNoRecordsTemplate>
{{ userGrid.loaded ? 'No login found for this date range.' : 'Select a date range and press Load.' }}
</ng-template>
<kendo-grid-excel [fileName]="fileName('UserAuditTrail', userFromDate, userToDate, 'xlsx')"
[fetchData]="userGrid.allData">
<kendo-excelexport-column field="loginID" title="Login ID" [width]="140"></kendo-excelexport-column>
<kendo-excelexport-column field="userName" title="Name" [width]="220"></kendo-excelexport-column>
<kendo-excelexport-column field="punchTime" title="Punch Time" [width]="180"
[cellOptions]="{ format: excelDateFormat }"></kendo-excelexport-column>
<kendo-excelexport-column field="pcNumber" title="Computer" [width]="300"></kendo-excelexport-column>
<kendo-excelexport-column field="ipAddress" title="IP Address" [width]="130"></kendo-excelexport-column>
<kendo-excelexport-column field="deviceId" title="Device ID" [width]="220"></kendo-excelexport-column>
</kendo-grid-excel>
<kendo-grid-pdf [fileName]="fileName('UserAuditTrail', userFromDate, userToDate, 'pdf')"
[allPages]="true" [repeatHeaders]="true" paperSize="A4" [landscape]="true" [scale]="0.7">
<kendo-grid-pdf-margin top="1cm" left="1cm" right="1cm" bottom="1cm"></kendo-grid-pdf-margin>
</kendo-grid-pdf>
</kendo-grid>
</ng-template>
</kendo-tabstrip-tab>
<!-- ── Tab 2: Bad Login Attempt (dbo.BadLoginAttemptInfo) ── -->
<kendo-tabstrip-tab title="Bad Login Attempt">
<ng-template kendoTabContent>
<div class="grid audit-trail-filter">
<div class="col-12 md:col-1 audit-trail-label">
<label for="dtBadFrom">From Date</label>
</div>
<div class="col-12 md:col-3">
<kendo-datepicker id="dtBadFrom" [(ngModel)]="badFromDate" [format]="'dd-MMM-yyyy'" [max]="badToDate"
style="width: 100%"></kendo-datepicker>
</div>
<div class="col-12 md:col-1 audit-trail-label">
<label for="dtBadTo">To Date</label>
</div>
<div class="col-12 md:col-3">
<kendo-datepicker id="dtBadTo" [(ngModel)]="badToDate" [format]="'dd-MMM-yyyy'" [min]="badFromDate"
style="width: 100%"></kendo-datepicker>
</div>
<div class="col-12 md:col-2">
<button kendoButton themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['search']"
(click)="loadBadLoginAttempts()" style="width: 100%;">Load</button>
</div>
</div>
<kendo-grid #badGridRef
[data]="badGrid.view"
[skip]="badGrid.state.skip"
[pageSize]="pageSize"
[sort]="badGrid.state.sort"
[filter]="badGrid.state.filter"
[sortable]="true"
filterable="menu"
scrollable="virtual"
[rowHeight]="36"
[height]="520"
[navigable]="true"
(dataStateChange)="badGrid.onStateChange($event)">
<ng-template kendoGridToolbarTemplate>
<input kendoTextBox class="audit-trail-search" placeholder="Search in all columns..."
[value]="badGrid.searchText" (input)="badGrid.onSearch($any($event.target).value)" />
<span class="audit-trail-count">
{{ badGrid.filteredCount | number }} of {{ badGrid.rows.length | number }} records
</span>
<kendo-grid-spacer></kendo-grid-spacer>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['fileExcel']"
(click)="exportExcel(badGridRef, badGrid)">Export to Excel</button>
<button kendoButton type="button" [svgIcon]="apiService.KendoSVGIcon['filePdf']"
(click)="exportPdf(badGridRef, badGrid)">Export to PDF</button>
</ng-template>
<kendo-grid-column field="loginID" title="Login ID" [width]="200"></kendo-grid-column>
<kendo-grid-column field="punchTime" title="Punch Time" [width]="220" filter="date"
[format]="gridDateFormat"></kendo-grid-column>
<kendo-grid-column field="pcNumber" title="Computer" [width]="280"></kendo-grid-column>
<kendo-grid-column field="ipAddress" title="IP Address" [width]="150"></kendo-grid-column>
<kendo-grid-column field="deviceId" title="Device ID" [width]="220"></kendo-grid-column>
<ng-template kendoGridNoRecordsTemplate>
{{ badGrid.loaded ? 'No bad login attempt found for this date range.' : 'Select a date range and press Load.' }}
</ng-template>
<kendo-grid-excel [fileName]="fileName('BadLoginAttempt', badFromDate, badToDate, 'xlsx')"
[fetchData]="badGrid.allData">
<kendo-excelexport-column field="loginID" title="Login ID" [width]="160"></kendo-excelexport-column>
<kendo-excelexport-column field="punchTime" title="Punch Time" [width]="180"
[cellOptions]="{ format: excelDateFormat }"></kendo-excelexport-column>
<kendo-excelexport-column field="pcNumber" title="Computer" [width]="300"></kendo-excelexport-column>
<kendo-excelexport-column field="ipAddress" title="IP Address" [width]="130"></kendo-excelexport-column>
<kendo-excelexport-column field="deviceId" title="Device ID" [width]="220"></kendo-excelexport-column>
</kendo-grid-excel>
<kendo-grid-pdf [fileName]="fileName('BadLoginAttempt', badFromDate, badToDate, 'pdf')"
[allPages]="true" [repeatHeaders]="true" paperSize="A4" [landscape]="true" [scale]="0.7">
<kendo-grid-pdf-margin top="1cm" left="1cm" right="1cm" bottom="1cm"></kendo-grid-pdf-margin>
</kendo-grid-pdf>
</kendo-grid>
</ng-template>
</kendo-tabstrip-tab>
</kendo-tabstrip>
</div>

View File

@ -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;
}

View File

@ -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;
}
}

View File

@ -40,7 +40,13 @@
<label for="txtEmail">Email</label>
</div>
<div class="col-12 md:col-4">
<input id="txtEmail" [(ngModel)]="_user.email" type="text" formControlName="email" kendoTextBox style="width: 100%;">
<input id="txtEmail" [(ngModel)]="_user.email" type="email" maxlength="254" placeholder="name@company.com"
formControlName="email" kendoTextBox style="width: 100%;">
@if (fromValidator.get('email')?.invalid && fromValidator.get('email')?.value) {
<small class="p-error">
Please enter a valid e-mail address.
</small>
}
</div>
<!--<div class="col-12 md:col-2" style="margin: auto;">

View File

@ -89,7 +89,12 @@ export class UsersEntryComponent implements OnInit {
password: ['', Validators.required],
confirmPassword: ['', Validators.required],
passwordHints: '',
email: '',
// Optional, but when filled it must be a real address: local@domain.tld
// (Validators.email alone accepts "a@b", so a stricter pattern is used).
email: ['', [
Validators.maxLength(254),
Validators.pattern(/^\s*[A-Za-z0-9._%+-]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*\.[A-Za-z]{2,}\s*$/)
]],
emailAddress: ['', [Validators.email, Validators.maxLength(254)]],
employeeNo: '',
/* status: ['', Validators.required]*/
@ -113,6 +118,10 @@ export class UsersEntryComponent implements OnInit {
this._user.passwordHints = '';
}
if (typeof this._user.email === 'string') {
this._user.email = this._user.email.trim();
}
this._user.changePasswordAtNextLogon = true;
this.userServiceFactory.SaveUser(this._user).subscribe(
(x) => {

View File

@ -162,7 +162,7 @@
</kendo-textarea>
<kendo-dialog-actions layout="end">
<button kendoButton type="button" (click)="onReasonPopUpClose()">Cancel</button>
<button kendoButton type="button" themeColor="error" (click)="onReasonSave()">Send for approval</button>
<button kendoButton type="button" themeColor="error" (click)="onReasonSave()">{{rejectorDeactive}}</button>
</kendo-dialog-actions>
</kendo-dialog>
</div>

View File

@ -67,7 +67,6 @@ export class UsersListComponent implements OnInit {
readonly userTypes = [
{name: 'User', value: EnumUserType.User},
{name: 'Employee', value: EnumUserType.Employee},
{name: 'Super user', value: EnumUserType.SuperUser},
];
readonly exportItems = [
@ -92,6 +91,7 @@ export class UsersListComponent implements OnInit {
private deactivateTarget: User;
currentUser: User;
actionselected: string = '';
rejectorDeactive: string ='Reject'
public state: State = {
skip: 0,
@ -285,7 +285,7 @@ export class UsersListComponent implements OnInit {
}
if (status === EnumAuthStatus.Inactive_Not_Yet_Approve) {
return [
{ text: 'approve', svgIcon: pencilIcon, action: 'approve' },
{ text: 'approve', svgIcon: pencilIcon, action: 'deactivate-approve' },
];
}
@ -300,15 +300,18 @@ export class UsersListComponent implements OnInit {
break;
case 'deactivate':
this.onStatusToggle(row.id);
this.actionselected = "deactivate";
this.actionselected = "deactivate";
this.rejectorDeactive = 'Deactivate';
break;
case 'deactivate-approve':
this.actionselected = "deactivate-approve";
this.Approve(row.id);
this.rejectorDeactive = 'Deactivate';
break;
case 'reject':
this.onStatusToggle(row.id);
this.actionselected = "reject";
this.rejectorDeactive = 'reject';
break;
case 'approve':
this.actionselected = "approve";
@ -359,13 +362,16 @@ export class UsersListComponent implements OnInit {
this.notificationService.showError('Created user and Approve user can\'t be Same.');
return;
}
debugger;
const ouser = Object.assign({}, oselecteduser);
if (this.actionselected == "deactivate-approve") {
ouser.userStatus = EnumAuthStatus.Inactive;
}
else
ouser.userStatus = EnumAuthStatus.Approved;
ouser.userStatus = EnumAuthStatus.Approved;
ouser.modifiedBy = oselecteduser.userID;
ouser.modifiedDate = new Date();
this.loadingPanel.ShowLoadingPanel = true;
this.userService.ApproveUser(ouser).subscribe(
@ -433,6 +439,10 @@ export class UsersListComponent implements OnInit {
}
changed.reason = reason;
changed.modifiedBy = target.userID;
changed.modifiedDate = new Date();
this.loadingPanel.ShowLoadingPanel = true;
this.userService.DoActiveAndIntacive(changed).subscribe(
() => {
@ -440,7 +450,9 @@ export class UsersListComponent implements OnInit {
target.reason = changed.reason;
this.rebuildRows();
this.loadingPanel.ShowLoadingPanel = false;
this.notificationService.showSuccess('Deactivation sent for approval.');
if (this.actionselected == 'reject')
this.notificationService.showSuccess('User rejected successfully.');
else this.notificationService.showSuccess('Deactivation sent for approval.');
this.reasonForStatusChange = '';
this.showReason = false;
},

View File

@ -41,6 +41,8 @@ namespace HRM.UI.Configuration.DI
services.AddTransient<IRoleService, RoleService>();
services.AddTransient<IUserRoleService, UserRoleService>();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IUserLogInInfoService, UserLogInInfoService>();
services.AddTransient<IBadLoginAttemptInfoService, BadLoginAttemptInfoService>();
services.AddTransient<IPasswordHistoryService, PasswordHistoryService>();
services.AddTransient<ISearchEmployeeService, SearchEmployeeService>();
services.AddTransient<IHREmployeeService, HREmployeeService>();

View File

@ -53,6 +53,8 @@ namespace HRM.UI.Controllers
private readonly LDAPAuthService _ldapAuthService;
private readonly ISmsService _smsService;
private readonly IMemoryCache _cache;
private readonly IUserLogInInfoService _userLogInInfoService;
private readonly IBadLoginAttemptInfoService _badLoginAttemptInfoService;
public AuthController(IConfiguration config,
IUserService userService,
@ -69,7 +71,9 @@ namespace HRM.UI.Controllers
IDataPermissionService dataPermissionService,
LDAPAuthService ldapAuthService,
ISmsService smsService,
IMemoryCache cache)
IMemoryCache cache,
IUserLogInInfoService userLogInInfoService,
IBadLoginAttemptInfoService badLoginAttemptInfoService)
{
_config = config;
_jwt = jwtOptions.Value;
@ -88,6 +92,8 @@ namespace HRM.UI.Controllers
this._ldapAuthService = ldapAuthService;
this._smsService = smsService;
_cache = cache;
_userLogInInfoService = userLogInInfoService;
_badLoginAttemptInfoService = badLoginAttemptInfoService;
}
[HttpPost]
@ -400,9 +406,16 @@ namespace HRM.UI.Controllers
//userFromRepo = _userService.GetByLoginIDAndPassword(userForLoginDto.Username.ToLower(), userForLoginDto.Password);
}
if (!isADLogin && userFromRepo == null)
return BadRequest("Login ID/Password is invalid");
if (!isADLogin && userFromRepo == null)
{
new BadLoginAttemptInfoService().SaveInThread(new BadLoginAttemptInfo
{
LoginID = userForLoginDto.Username,
AttemptTime = DateTime.Now,
});
return BadRequest("Login ID/Password is invalid");
}
if (userFromRepo.UserType == EnumUserType.SuperUser )
{
userForLoginDto.payrollTypeid = null;
@ -1758,6 +1771,69 @@ namespace HRM.UI.Controllers
}
}
#region System Audit Trail
// Login history in a date range (both days inclusive). Dates come as dd-MMM-yyyy
// (ApiService.getApiDateString). Self-service (Employee) logins are refused:
// the menu is not a security boundary.
[HttpGet]
[Route("getUserAuditTrail/{fromDate}/{toDate}")]
public ActionResult GetUserAuditTrail(string fromDate, string toDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to view the audit trail.");
List<UserLogInInfo> items = new List<UserLogInInfo>();
try
{
DateTime dFromDate = GlobalFunctions.GetApiDefaultDateData(fromDate);
DateTime dToDate = GlobalFunctions.GetApiDefaultDateData(toDate);
if (dFromDate == DateTime.MinValue || dToDate == DateTime.MinValue)
return StatusCode(StatusCodes.Status400BadRequest, "From date and To date are required.");
if (dFromDate.Date > dToDate.Date)
return StatusCode(StatusCodes.Status400BadRequest, "From date can not be after To date.");
items = _userLogInInfoService.GetAuditTrail(dFromDate, dToDate);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
[HttpGet]
[Route("getBadLoginAuditTrail/{fromDate}/{toDate}")]
public ActionResult GetBadLoginAuditTrail(string fromDate, string toDate)
{
CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User);
if (currentUser.UserType == EnumUserType.Employee)
return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to view the audit trail.");
List<BadLoginAttemptInfo> items = new List<BadLoginAttemptInfo>();
try
{
DateTime dFromDate = GlobalFunctions.GetApiDefaultDateData(fromDate);
DateTime dToDate = GlobalFunctions.GetApiDefaultDateData(toDate);
if (dFromDate == DateTime.MinValue || dToDate == DateTime.MinValue)
return StatusCode(StatusCodes.Status400BadRequest, "From date and To date are required.");
if (dFromDate.Date > dToDate.Date)
return StatusCode(StatusCodes.Status400BadRequest, "From date can not be after To date.");
items = _badLoginAttemptInfoService.GetAuditTrail(dFromDate, dToDate);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(items);
}
#endregion
[HttpGet]
[Route("getSSOStatus")]
[AllowAnonymous]

View File

@ -302,6 +302,10 @@ namespace HRM.UI.Api
services.ConfigureBusinessServices(Configuration);
// HRM.DA services are new-ed up, not injected; ClientRequestInfo reads the
// request (client IP / device id) through this accessor. See Configure().
services.AddHttpContextAccessor();
#endregion
#region Memory Cashing Configuration
@ -326,6 +330,8 @@ namespace HRM.UI.Api
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
ClientRequestInfo.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();

View File

@ -0,0 +1,62 @@
/* ============================================================================
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