From 92d4225a82fa3ac32b285fa1be8f5ccdfebb0bec Mon Sep 17 00:00:00 2001 From: Mohaimen Hasan Date: Tue, 17 Nov 2026 14:52:13 +0600 Subject: [PATCH] Role Permission all gap resolve --- HRM.DA/DA/Users/UserRoleDA.cs | 22 +++++ HRM.DA/Service/Users/UserRoleService.cs | 87 +++++++++++++++++-- HRM.DA/Service/Users/UserService.cs | 25 ++++++ .../user-access-type.component.ts | 24 +++++ .../user-role-entry.component.ts | 16 +++- .../user-role-list.component.ts | 15 +++- .../users/users-list/users-list.component.ts | 52 +++++++---- HRM.UI/Controllers/Auth/AuthController.cs | 41 +++++++++ 8 files changed, 258 insertions(+), 24 deletions(-) diff --git a/HRM.DA/DA/Users/UserRoleDA.cs b/HRM.DA/DA/Users/UserRoleDA.cs index cbd5ca7..fbb3d22 100644 --- a/HRM.DA/DA/Users/UserRoleDA.cs +++ b/HRM.DA/DA/Users/UserRoleDA.cs @@ -193,6 +193,28 @@ namespace HRM.DA tc.ExecuteNonQuery("DELETE FROM UserRole WHERE UserRoleID=%n", userRoleID); } + // Inside the maker's write transaction: counts the user's changes of one role type waiting for approval + // and keeps that range locked until commit, so a second maker sending at the same moment waits here + // and then sees the first change (instead of making a second pending change). + internal static int CountPendingLocked(TransactionContext tc, int userID, EnumRoleType roleType) + { + object o = tc.ExecuteScalar( + "SELECT COUNT(*) FROM UserRole WITH (UPDLOCK, HOLDLOCK)" + + " WHERE UserID=%n AND Status IN (%n, %n) AND RoleID IN (SELECT RoleID FROM Role WHERE RoleType=%n)", + userID, (int)EnumAuthStatus.NewNotYetApprove, (int)EnumAuthStatus.DeletedNotYetApprove, (int)roleType); + return o == null || o == DBNull.Value ? 0 : Convert.ToInt32(o); + } + + // Same idea for a Self Service employee with no login yet: counts the employee's logins and keeps them + // locked, so two makers cannot both create a login for the same employee. + internal static int CountEmployeeLoginsLocked(TransactionContext tc, int employeeID) + { + object o = tc.ExecuteScalar( + "SELECT COUNT(*) FROM Users WITH (UPDLOCK, HOLDLOCK) WHERE EmployeeID=%n AND UserType=%n", + employeeID, (int)EnumUserType.Employee); + return o == null || o == DBNull.Value ? 0 : Convert.ToInt32(o); + } + internal static int CountByUser(TransactionContext tc, int userID) { object o = tc.ExecuteScalar("SELECT COUNT(*) FROM UserRole WHERE UserID=%n", userID); diff --git a/HRM.DA/Service/Users/UserRoleService.cs b/HRM.DA/Service/Users/UserRoleService.cs index 2d8cb41..f7c1675 100644 --- a/HRM.DA/Service/Users/UserRoleService.cs +++ b/HRM.DA/Service/Users/UserRoleService.cs @@ -515,9 +515,18 @@ namespace HRM.DA if (IsSelfService(subject)) { int employeeID = subject.EmployeeID ?? 0; + Employee emp = null; if (employeeID <= 0 && (subject.UserID ?? 0) > 0) - employeeID = new UserService().Get(subject.UserID.Value)?.EmployeeID ?? 0; - Employee emp = new EmployeeService().Get(employeeID); + { + // Opened from the list by the employee's login: older logins have no EmployeeID and + // are tied to the employee only by LoginID = EmployeeNo. + User subjectLogin = new UserService().Get(subject.UserID.Value); + employeeID = subjectLogin?.EmployeeID ?? 0; + if (employeeID <= 0 && !string.IsNullOrWhiteSpace(subjectLogin?.LoginID)) + emp = new EmployeeService().GetByEmployeeNo(subjectLogin.LoginID); + } + if (emp == null || emp.ID <= 0) + emp = new EmployeeService().Get(employeeID); if (emp == null || emp.ID <= 0) throw new InvalidOperationException("Employee not found."); state.EmployeeID = emp.ID; @@ -603,6 +612,18 @@ namespace HRM.DA DateTime now = DateTime.Now; tc = TransactionContext.Begin(true); + // Checked again inside the transaction, with a lock: another maker may be sending a change for + // the same person at this very moment. + if (newLogin != null) + { + if (UserRoleDA.CountEmployeeLoginsLocked(tc, state.EmployeeID ?? 0) > 0) + throw new InvalidOperationException("Someone else has just sent a role change for this employee. Open the employee again to see it."); + } + else if (UserRoleDA.CountPendingLocked(tc, state.UserID ?? 0, request.RoleType) > 0) + { + throw new InvalidOperationException("This person already has a role change waiting for approval."); + } + int userID = state.UserID ?? 0; if (newLogin != null) userID = new UserService().Save(tc, newLogin); @@ -639,7 +660,7 @@ namespace HRM.DA public void Approve(UserRoleSubject subject, int approverID) { TransactionContext tc = null; - Employee loginToMail = null; + User loginToMail = null; try { UserRoleState state = this.GetRoleState(subject); @@ -650,7 +671,7 @@ namespace HRM.DA // A login made by the maker for a Self Service employee is switched on now, and mailed as before. if (IsSelfService(subject) && state.LoginWaiting) { - loginToMail = new EmployeeService().Get(state.EmployeeID ?? 0); + loginToMail = new UserService().Get(userID); } int? notifyEmployeeID = IsSelfService(subject) ? state.EmployeeID : new UserService().Get(userID)?.EmployeeID; @@ -682,8 +703,8 @@ namespace HRM.DA #endregion } - if (loginToMail != null && loginToMail.ID > 0) - this.MailNewLogin(new List { loginToMail }); + if (loginToMail != null) + this.MailNewEmployeeLogin(loginToMail); } public void Reject(UserRoleSubject subject, int approverID) @@ -721,6 +742,24 @@ namespace HRM.DA } } + /// + /// User page rejected a new login (Status 2): its role changes waiting for approval are rejected too, + /// in the caller's transaction, exactly as User Role Permission's Reject does them (given roles go, + /// removals stay live), one row at a time (see UserRoleDA). Returns how many rows were decided. + /// + internal int RejectPendingRolesOfLogin(TransactionContext tc, int userID) + { + List pending = ReadRows(tc, true, userID, null); + foreach (UserRoleRequest row in pending) + { + if (row.RequestType == EnumUserRoleRequestType.Remove) + UserRoleDA.RestoreRow(tc, row.ID); + else + UserRoleDA.DeleteRow(tc, row.ID); + } + return pending.Count; + } + public List GetPending() { List items = new List(); @@ -774,6 +813,8 @@ namespace HRM.DA string description = roleType == EnumRoleType.Admin ? (hasRoleName ? $"You have been granted Admin access with the role: {roleName}." : "You have been granted a new Admin role.") : (hasRoleName ? $"You have been assigned to the Self Service role: {roleName}." : "You have been assigned a new Self Service role."); + // The menu is loaded at sign-in, so the new role shows from the next sign-in. + description += " Sign out and sign in again to see it in your menu."; var notification = new EmployeeNotification { @@ -791,6 +832,40 @@ namespace HRM.DA new EmployeeNotificationService().Insert(tc, notification); } + /// + /// Sends the existing employee login e-mail (MailNewLogin: Login ID + the birth-date password) when a + /// new Self Service employee login is switched on, from either page that can do it: User Role + /// Permission approval or User page approval. Sent only while the login still has that first + /// birth-date password, i.e. it was made by User Role Permission; any other login is left alone, + /// so a wrong password is never mailed. Never throws. + /// + internal void MailNewEmployeeLogin(User login) + { + try + { + if (login == null || login.UserType != EnumUserType.Employee) + return; + + Employee emp = null; + if ((login.EmployeeID ?? 0) > 0) + emp = new EmployeeService().Get(login.EmployeeID.Value); + if ((emp == null || emp.ID <= 0) && !string.IsNullOrWhiteSpace(login.LoginID)) + emp = new EmployeeService().GetByEmployeeNo(login.LoginID); + if (emp == null || emp.ID <= 0) + return; + + string firstPassword = Ease.Core.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", MakePassWord(emp.BirthDate)); + if (login.Password != firstPassword) + return; + + this.MailNewLogin(new List { emp }); + } + catch (Exception e) + { + ExceptionLog.Write(e); + } + } + // The login e-mail the old Save sent to newly created employee logins (now sent on approval). private void MailNewLogin(List oemps) { diff --git a/HRM.DA/Service/Users/UserService.cs b/HRM.DA/Service/Users/UserService.cs index b34c0aa..bba637d 100644 --- a/HRM.DA/Service/Users/UserService.cs +++ b/HRM.DA/Service/Users/UserService.cs @@ -809,15 +809,27 @@ namespace HRM.DA TransactionContext tc = null; try { + // The login as it is before this change: rejecting a new Employee login (Status 2) also rejects + // its role changes waiting in User Role Permission (below), so the two never disagree. + User before = this.Get(oUser.ID); + tc = TransactionContext.Begin(true); UserDA.DoActiveAndIntacive(tc, oUser); + if (before != null && before.UserType == EnumUserType.Employee + && before.UserStatus == EnumAuthStatus.NewNotYetApprove + && oUser.UserStatus == EnumAuthStatus.Rejected) + { + new UserRoleService().RejectPendingRolesOfLogin(tc, oUser.ID); + } tc.End(); } catch (Exception ex) { + if (tc != null) + tc.HandleError(); throw new Exception(ex.Message); } @@ -1046,8 +1058,13 @@ namespace HRM.DA public void Approve(User oUser) { TransactionContext tc = null; + User before = null; try { + // The login as it is before this approval: a new login (Status 2) being switched on may need + // its login e-mail (below). + before = this.Get(oUser.ID); + tc = TransactionContext.Begin(true); UserDA.Approve(tc, oUser); tc.End(); @@ -1061,6 +1078,14 @@ namespace HRM.DA throw new ServiceException(e.Message, e); #endregion } + + // A new Self Service employee login (made by User Role Permission) approved here gets the same + // login e-mail it gets when its roles are approved first; MailNewEmployeeLogin decides and never throws. + if (before != null && before.UserStatus == EnumAuthStatus.NewNotYetApprove + && oUser.UserStatus == EnumAuthStatus.Approved) + { + new UserRoleService().MailNewEmployeeLogin(before); + } } diff --git a/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.ts b/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.ts index a3f3696..f0abf08 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.ts +++ b/HRM.UI/ClientApp/src/app/authentication/user-access-type/user-access-type.component.ts @@ -191,6 +191,18 @@ export class UserAccessTypeComponent implements OnInit { this.notificationService.showWarning('Select at least one user.'); return; } + const count = ids.length + (ids.length == 1 ? ' user' : ' users'); + const question = approve + ? `Are you sure you want to approve the access changes of ${count}?` + : `Are you sure you want to reject the access changes of ${count}?`; + this.notificationService.showActiveConfirm('Confirmation', question).then((isConfirmed) => { + if (isConfirmed) { + this.sendBulkDecision(approve, ids); + } + }); + } + + private sendBulkDecision(approve: boolean, ids: number[]): void { const call = approve ? this.useService.ApproveUserAccessTypes(ids) : this.useService.RejectUserAccessTypes(ids); let result: any; this.loadingPanel.ShowLoadingPanel = true; @@ -396,6 +408,18 @@ export class UserAccessTypeComponent implements OnInit { if (userID == undefined || !this.hasPending) { return; } + const who = this.selectedUser?.userName ?? ''; + const question = approve + ? `Are you sure you want to approve the access change of ${who}?` + : `Are you sure you want to reject the access change of ${who}?`; + this.notificationService.showActiveConfirm('Confirmation', question).then((isConfirmed) => { + if (isConfirmed) { + this.sendDecision(approve, userID); + } + }); + } + + private sendDecision(approve: boolean, userID: number): void { const call = approve ? this.useService.ApproveUserAccessType(userID) : this.useService.RejectUserAccessType(userID); this.loadingPanel.ShowLoadingPanel = true; call.subscribe( diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.ts b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.ts index c2350d9..dbdc6ba 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.ts +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-entry/user-role-entry.component.ts @@ -330,6 +330,18 @@ export class UserRoleEntryComponent implements OnInit { if (!this.hasPending) { return; } + const who = this.state?.personName ?? ''; + const question = approve + ? `Are you sure you want to approve the role change of ${who}?` + : `Are you sure you want to reject the role change of ${who}?`; + this.notificationService.showActiveConfirm('Confirmation', question).then((isConfirmed) => { + if (isConfirmed) { + this.sendDecision(approve); + } + }); + } + + private sendDecision(approve: boolean): void { const call = approve ? this.userService.ApproveUserRole(this.subject()) : this.userService.RejectUserRole(this.subject()); this.loadingPanel.ShowLoadingPanel = true; call.subscribe( @@ -340,7 +352,9 @@ export class UserRoleEntryComponent implements OnInit { }, () => { this.loadingPanel.ShowLoadingPanel = false; - this.notificationService.showSuccess(approve ? 'Approved. The roles are now live.' : 'Rejected. The roles stay as they were.'); + this.notificationService.showSuccess(approve + ? 'Approved. The roles are now live; the person sees the new menu from their next sign-in.' + : 'Rejected. The roles stay as they were.'); this.saveCompleted.emit(true); } ); diff --git a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.ts b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.ts index 7d61995..ede33fa 100644 --- a/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.ts +++ b/HRM.UI/ClientApp/src/app/authentication/user-role/user-role-list/user-role-list.component.ts @@ -284,6 +284,18 @@ export class UserRoleListComponent implements OnInit { this.notificationService.showWarning('Select at least one person.'); return; } + const count = groups.length + (groups.length == 1 ? ' person' : ' people'); + const question = approve + ? `Are you sure you want to approve the role changes of ${count}?` + : `Are you sure you want to reject the role changes of ${count}?`; + this.notificationService.showActiveConfirm('Confirmation', question).then((isConfirmed) => { + if (isConfirmed) { + this.sendBulkDecision(approve, groups); + } + }); + } + + private sendBulkDecision(approve: boolean, groups: PendingGroup[]): void { const subjects = groups.map(g => this.toSubject(g)); const call = approve ? this.userService.ApproveUserRoles(subjects) : this.userService.RejectUserRoles(subjects); let result: any; @@ -300,7 +312,8 @@ export class UserRoleListComponent implements OnInit { const failed: any[] = result?.failed ?? []; if (done > 0) { this.notificationService.showSuccess( - (approve ? 'Approved' : 'Rejected') + ' for ' + done + (done == 1 ? ' person.' : ' people.')); + (approve ? 'Approved' : 'Rejected') + ' for ' + done + (done == 1 ? ' person.' : ' people.') + + (approve ? ' New menus show from their next sign-in.' : '')); } if (failed.length > 0) { this.notificationService.showError(failed.map(f => diff --git a/HRM.UI/ClientApp/src/app/authentication/users/users-list/users-list.component.ts b/HRM.UI/ClientApp/src/app/authentication/users/users-list/users-list.component.ts index c076e9b..91ad70a 100644 --- a/HRM.UI/ClientApp/src/app/authentication/users/users-list/users-list.component.ts +++ b/HRM.UI/ClientApp/src/app/authentication/users/users-list/users-list.component.ts @@ -373,22 +373,30 @@ export class UsersListComponent implements OnInit { ouser.modifiedBy = oselecteduser.userID; ouser.modifiedDate = new Date(); - this.loadingPanel.ShowLoadingPanel = true; - this.userService.ApproveUser(ouser).subscribe( - (x: User) => { - const index = this.users.findIndex(u => u.id === id); - if (index >= 0) { - this.users[index] = x ?? ouser; - } - this.rebuildRows(); - this.loadingPanel.ShowLoadingPanel = false; - this.notificationService.showSuccess('Approved successfully.'); - }, - (x) => { - this.loadingPanel.ShowLoadingPanel = false; - this.notificationService.showError(x.error); - }, - ); + const question = this.actionselected == "deactivate-approve" + ? `Are you sure you want to approve the deactivation of ${oselecteduser.userName ?? ''} (${oselecteduser.loginID ?? ''})?` + : `Are you sure you want to approve ${oselecteduser.userName ?? ''} (${oselecteduser.loginID ?? ''})?`; + this.notificationService.showActiveConfirm('Confirmation', question).then((isConfirmed) => { + if (!isConfirmed) { + return; + } + this.loadingPanel.ShowLoadingPanel = true; + this.userService.ApproveUser(ouser).subscribe( + (x: User) => { + const index = this.users.findIndex(u => u.id === id); + if (index >= 0) { + this.users[index] = x ?? ouser; + } + this.rebuildRows(); + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showSuccess('Approved successfully.'); + }, + (x) => { + this.loadingPanel.ShowLoadingPanel = false; + this.notificationService.showError(x.error); + }, + ); + }); } // ---------- deactivate ---------- @@ -442,7 +450,19 @@ export class UsersListComponent implements OnInit { changed.modifiedBy = target.userID; changed.modifiedDate = new Date(); + if (this.actionselected == 'reject') { + this.notificationService.showActiveConfirm('Confirmation', + `Are you sure you want to reject ${target.userName ?? ''} (${target.loginID ?? ''})?`).then((isConfirmed) => { + if (isConfirmed) { + this.saveStatusChange(target, changed); + } + }); + return; + } + this.saveStatusChange(target, changed); + } + private saveStatusChange(target: User, changed: User) { this.loadingPanel.ShowLoadingPanel = true; this.userService.DoActiveAndIntacive(changed).subscribe( () => { diff --git a/HRM.UI/Controllers/Auth/AuthController.cs b/HRM.UI/Controllers/Auth/AuthController.cs index c584379..58e9d04 100644 --- a/HRM.UI/Controllers/Auth/AuthController.cs +++ b/HRM.UI/Controllers/Auth/AuthController.cs @@ -294,6 +294,14 @@ namespace HRM.UI.Controllers if (userForLoginDto.IsSSO) { userFromRepo = _userService.GetByEmail(userForLoginDto.Email); + // Same rule as the password sign-in (UserDA.GetByLoginIDAndPassword: Status 1 or 5): a login that + // is not switched on (waiting for approval, rejected, inactive, ...) cannot sign in by SSO either. + if (userFromRepo != null + && userFromRepo.UserStatus != EnumAuthStatus.Active + && userFromRepo.UserStatus != EnumAuthStatus.Approved) + { + userFromRepo = null; + } if (userFromRepo != null && userForLoginDto.nextPayProcessDate == null) { List payrollTypes = new List(); @@ -1409,6 +1417,12 @@ namespace HRM.UI.Controllers try { + // Admin screens only (Employee Profile's access permission): a self-service login may not read roles. + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (currentUser.UserType == EnumUserType.Employee) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see user roles."); + } ouroles = this._userRoleService.Get(searchEmps); } catch (Exception e) @@ -1427,6 +1441,12 @@ namespace HRM.UI.Controllers int? nroleid = GlobalFunctions.GetApiDefaultIntData(roleid); try { + // Only the User Role Permission page reads this list (super users only, like its other endpoints). + CurrentUser currentUser = CurrentUser.GetCurrentUser(HttpContext.User); + if (!CanManageUserRole(currentUser)) + { + return StatusCode(StatusCodes.Status403Forbidden, "You are not allowed to see user roles."); + } items = this._userRoleService.Get(roletype, nuserid, nroleid); // employee Name, Login-Status, status1, statu2, statu3 @@ -1791,6 +1811,27 @@ namespace HRM.UI.Controllers ? "You cannot approve a change you made yourself. Another user must approve it." : "You cannot reject a change you made yourself. Another user must reject it."; + if (approve) + { + // A role given in this change must still be approved now: it may have been edited (and be + // waiting for its own approval) on the Role page since the change was sent. + List giving = state.Pending + .Where(p => p.RequestType == EnumUserRoleRequestType.Add) + .Select(p => p.RoleID).Distinct().ToList(); + if (giving.Count > 0) + { + List allRoles = this._roleService.GetAllRole(); + foreach (int roleID in giving) + { + Role role = allRoles.FirstOrDefault(r => r.ID == roleID); + if (role == null) + return "A role in this change no longer exists. Reject the change and send it again."; + if (role.RoleStatus != EnumAuthStatus.Approved && role.RoleStatus != EnumAuthStatus.Active) + return "Role '" + role.Name + "' is not approved now (it may be waiting for its own approval on the Role page), so it cannot be given yet. Approve the role first, or reject this change."; + } + } + } + if (approve) this._userRoleService.Approve(subject, currentUser.UserID); else