diff --git a/HRM.BO/Configuration/ForgotPasswordSettings.cs b/HRM.BO/Configuration/ForgotPasswordSettings.cs new file mode 100644 index 0000000..f8aa65b --- /dev/null +++ b/HRM.BO/Configuration/ForgotPasswordSettings.cs @@ -0,0 +1,18 @@ +namespace HRM.BO.Configuration +{ + /// + /// "ForgotPasswordSettings" section of appsettings.json. + /// + public class ForgotPasswordSettings + { + public const int DefaultLinkExpiryMinutes = 10; + + // How long the password reset link stays valid (minutes). Missing / 0 / negative = DefaultLinkExpiryMinutes. + public int LinkExpiryMinutes { get; set; } = DefaultLinkExpiryMinutes; + + public int GetLinkExpiryMinutes() + { + return LinkExpiryMinutes > 0 ? LinkExpiryMinutes : DefaultLinkExpiryMinutes; + } + } +} diff --git a/HRM.BO/Employee/Employee.cs b/HRM.BO/Employee/Employee.cs index 42c8ba6..e93399d 100644 --- a/HRM.BO/Employee/Employee.cs +++ b/HRM.BO/Employee/Employee.cs @@ -513,6 +513,7 @@ namespace HRM.BO List GetForSuperUser(); Employee GetByCardID(int id); Employee Get(string emloyeeNo, int payrollTypeID); + Employee GetByEmpNo(string EmpNo); Employee GetFromAll(string emloyeeNo, int payrollTypeID); Employee GetwitoutchekPayrolltype(String employeeNo); Employee GetParentEmployee(int employeeID); diff --git a/HRM.BO/User/Users.cs b/HRM.BO/User/Users.cs index 4954b16..c4ad381 100644 --- a/HRM.BO/User/Users.cs +++ b/HRM.BO/User/Users.cs @@ -136,6 +136,7 @@ namespace HRM.BO public int? EmployeeID { get; set; } public string MobileNo { get; set; } public string Email { get; set; } //erec + public Employee Employee { get; set; } // Not a database field (linked employee, filled where needed e.g. forgot password) //public string EmailAddress { get; set; } public string ADloginID { get; set; } @@ -192,6 +193,7 @@ namespace HRM.BO void Approve(User user); int GetUserId(int employeeid, EnumUserType type); User GetByLoginIDbyEmail(string sEmail); + User GetUserForPasswordReset(string loginID); void DoActiveAndIntacive(User oUser); //void SaveAllUsers(List oUsers); diff --git a/HRM.DA/DA/Users/UserDA.cs b/HRM.DA/DA/Users/UserDA.cs index 2e92e0d..14f7437 100644 --- a/HRM.DA/DA/Users/UserDA.cs +++ b/HRM.DA/DA/Users/UserDA.cs @@ -185,6 +185,13 @@ namespace HRM.DA return tc.ExecuteReader(sql); } + // Active (Active / Approved) user of the given type - same status rule as login + internal static IDataReader GetActiveByLoginID(TransactionContext tc, string sLogInID, EnumUserType type) + { + return tc.ExecuteReader("SELECT * FROM Users WHERE lower(LOGINID)=%s AND UserType=%n AND (Status=%n OR Status=%n)", + sLogInID.ToLower(), type, EnumAuthStatus.Active, EnumAuthStatus.Approved); + } + internal static IDataReader GetByLoginIDByEmail(TransactionContext tc, string sEmail) { string sql = SQLParser.MakeSQL(@"SELECT * FROM Users WHERE lower(Email)=%s", sEmail.ToLower()); diff --git a/HRM.DA/Service/Employee/EmployeeService.cs b/HRM.DA/Service/Employee/EmployeeService.cs index ff0e2b2..23513a2 100644 --- a/HRM.DA/Service/Employee/EmployeeService.cs +++ b/HRM.DA/Service/Employee/EmployeeService.cs @@ -1015,6 +1015,38 @@ namespace HRM.DA return oEmployee; } + public Employee GetByEmpNo(string EmpNo) + { + Employee oEmployee = null; + TransactionContext tc = null; + try + { + tc = TransactionContext.Begin(); + DataReader oreader = new DataReader(EmployeeDA.Get(tc, EmpNo)); + if (oreader.Read()) + { + oEmployee = this.CreateObject(oreader); + } + + oreader.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 oEmployee; + } + public Employee Get(string employeeNo, int payrollTypeID) { Employee oEmployee = null; diff --git a/HRM.DA/Service/Users/UserService.cs b/HRM.DA/Service/Users/UserService.cs index bba637d..c119320 100644 --- a/HRM.DA/Service/Users/UserService.cs +++ b/HRM.DA/Service/Users/UserService.cs @@ -637,7 +637,71 @@ namespace HRM.DA return oUser; } - + + /// + /// Finds the active login account for Forgot Password, in the same priority as login: + /// 1. Employee (Self-Service, UserType 2) - LoginID is the EmployeeNo of a live employee; User.Employee is filled + /// 2. User / Admin (UserType 1) + /// 3. Super User (UserType 0) + /// Returns null when no active (Active / Approved) account is found. + /// + public User GetUserForPasswordReset(string loginID) + { + User oUser = null; + TransactionContext tc = null; + try + { + Employee oEmployee = new EmployeeService().GetByEmpNo(loginID); + + tc = TransactionContext.Begin(); + DataReader oreader; + + if (oEmployee != null) + { + oreader = new DataReader(UserDA.GetActiveByLoginID(tc, loginID, EnumUserType.Employee)); + if (oreader.Read()) + { + oUser = this.CreateObject(oreader); + oUser.Employee = oEmployee; + } + oreader.Close(); + } + + if (oUser == null) + { + oreader = new DataReader(UserDA.GetActiveByLoginID(tc, loginID, EnumUserType.User)); + if (oreader.Read()) + { + oUser = this.CreateObject(oreader); + } + oreader.Close(); + } + + if (oUser == null) + { + oreader = new DataReader(UserDA.GetActiveByLoginID(tc, loginID, EnumUserType.SuperUser)); + if (oreader.Read()) + { + oUser = this.CreateObject(oreader); + } + oreader.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 oUser; + } + public void SaveLoginfo(UserLogInInfo oTran) { diff --git a/HRM.UI/ClientApp/src/app/_models/Authentication/user.ts b/HRM.UI/ClientApp/src/app/_models/Authentication/user.ts index 01dd41f..bb15ab6 100644 --- a/HRM.UI/ClientApp/src/app/_models/Authentication/user.ts +++ b/HRM.UI/ClientApp/src/app/_models/Authentication/user.ts @@ -1,5 +1,6 @@ import { EnumAuthStatus, EnumUserType } from '../enums'; import { BaseObject } from '../Basic/baseObject'; +import { Employee } from '../Employee/employee'; export class User extends BaseObject { @@ -21,6 +22,7 @@ export class User extends BaseObject { isNew: boolean; roleNames: string; public employeeID?: number; + public employee?: Employee; // not a database field (linked employee) public changePasswordAtNextLogon: boolean; public userID: number; public PayrollTypeID?: number; 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 897c8d0..2eb199c 100644 --- a/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts +++ b/HRM.UI/ClientApp/src/app/_services/auth/auth.service.ts @@ -112,7 +112,8 @@ export class AuthService { GetAllEmpNotYetUser() { return this.apiService.httpGet('/Authentication/GetAllEmpNotYetUser'); } - logout() { + // redirectToLogin = false only clears the session (used by the reset-password page, which must stay open) + logout(redirectToLogin: boolean = true) { localStorage.removeItem('forgotpass'); localStorage.removeItem('bookmark'); localStorage.removeItem('token'); @@ -121,7 +122,9 @@ export class AuthService { localStorage.removeItem('notifications'); sessionStorage.removeItem('employeeCommonData'); this.logoutSource.next(); - this.router.navigate(['/login']); + if (redirectToLogin) { + this.router.navigate(['/login']); + } // Clear the HttpOnly JWToken cookie on the server; logout must never fail because of it. this.apiService.httpPost('/Authentication/logOut', {}).subscribe({ error: () => {} }); } @@ -290,6 +293,12 @@ export class AuthService { forgotPassword(data: any) { return this.apiService.httpPost('/Authentication/forgotPassword', data); } + validateResetPasswordToken(data: any) { + return this.apiService.httpPost('/Authentication/validateResetPasswordToken', data); + } + resetPassword(data: any) { + return this.apiService.httpPost('/Authentication/resetPassword', data); + } getVersionNumber() { return this.apiService.httpGet('/Authentication/getVersionNumber'); } diff --git a/HRM.UI/ClientApp/src/app/app.main.component.html b/HRM.UI/ClientApp/src/app/app.main.component.html index 7766917..93c38c2 100644 --- a/HRM.UI/ClientApp/src/app/app.main.component.html +++ b/HRM.UI/ClientApp/src/app/app.main.component.html @@ -1,4 +1,4 @@ -
+@if (isResetPassword()) { + +} diff --git a/HRM.UI/ClientApp/src/app/app.main.component.ts b/HRM.UI/ClientApp/src/app/app.main.component.ts index 653e56e..32398c7 100644 --- a/HRM.UI/ClientApp/src/app/app.main.component.ts +++ b/HRM.UI/ClientApp/src/app/app.main.component.ts @@ -45,12 +45,19 @@ export class AppMainComponent { public app: AppComponent, public authService: AuthService, public _auth : AuthGuard) { - if (performance.navigation.type == performance.navigation.TYPE_RELOAD) { + if (this.isResetPassword()) { + // Opened from the password reset email: drop any old session but stay on the reset page + this.authService.logout(false); + } else if (performance.navigation.type == performance.navigation.TYPE_RELOAD) { } else { this.authService.logout(); } this.IsSelfService(); } + // Password reset link: /#/reset-password?token=... + isResetPassword(): boolean { + return (window.location.hash || '').toLowerCase().startsWith('#/reset-password'); + } IsSelfService(){ const jwtHelper = new JwtHelperService(); const user = jwtHelper.decodeToken(localStorage.getItem('token')); @@ -224,6 +231,9 @@ export class AppMainComponent { return this.app.layoutMode === 'static'; } isLoginForm(): boolean { + if (this.isResetPassword()) { + return false; + } const token = localStorage.getItem('token'); if (token != null) { return false; @@ -238,6 +248,9 @@ export class AppMainComponent { } } forgotpassword(): boolean { + if (this.isResetPassword()) { + return false; + } const token = localStorage.getItem('token'); if (token != null) { return false; diff --git a/HRM.UI/ClientApp/src/app/app.module.ts b/HRM.UI/ClientApp/src/app/app.module.ts index f09c274..5bf426c 100644 --- a/HRM.UI/ClientApp/src/app/app.module.ts +++ b/HRM.UI/ClientApp/src/app/app.module.ts @@ -54,6 +54,7 @@ import {IndicatorsModule} from '@progress/kendo-angular-indicators'; import {UsersService} from './authentication/users/users.service'; import {LoginComponent} from './login.component'; import {ForgotPasswordComponent} from './forgot-password.component'; +import {ResetPasswordComponent} from './reset-password.component'; import {loadingPanelService} from './hrm-loding panel/loding.panel.service'; import {ReportsModule} from './reports/reports.module'; import {PdfViewerModule} from 'ng2-pdf-viewer'; @@ -195,7 +196,8 @@ import { EmpCommonInformationModule } from './ess/emp-common-information/EmpComm DashboardDemoComponent, ProfileUpdateComponent, ForgotPasswordComponent, - + ResetPasswordComponent, + RatingComponent, LoginComponent, ProfileUpdateAdminComponent, diff --git a/HRM.UI/ClientApp/src/app/app.routes.ts b/HRM.UI/ClientApp/src/app/app.routes.ts index 80a85a7..e9a3be4 100644 --- a/HRM.UI/ClientApp/src/app/app.routes.ts +++ b/HRM.UI/ClientApp/src/app/app.routes.ts @@ -66,6 +66,15 @@ export const routes: Routes = [ title: 'Forgot Password' } }, + { + // Password reset link from the email. Rendered by app.main () outside the + // main layout, so this route itself shows nothing - it only lets the URL match. No AuthGuard. + path: 'reset-password', + children: [], + data: { + title: 'Reset Password' + } + }, //{ path: 'panels', component: PanelsDemoComponent }, //{ path: 'overlays', component: OverlaysDemoComponent }, //{ path: 'messages', component: MessagesDemoComponent }, diff --git a/HRM.UI/ClientApp/src/app/forgot-password.component.css b/HRM.UI/ClientApp/src/app/forgot-password.component.css index e5c775b..eaa6c1a 100644 --- a/HRM.UI/ClientApp/src/app/forgot-password.component.css +++ b/HRM.UI/ClientApp/src/app/forgot-password.component.css @@ -1,19 +1,70 @@ -.p1 { - font-family: cursive ; -} +/* Layout/card come from the shared .login-body / .login-content styles (same as the Sign In page). + Only page-specific bits live here. */ - -/* .k-avatar and .k-form-legend are now centralized in src/styles/vendors/kendo/_misc.scss; - .k-button-primary/.k-button.k-primary (+ hover) in src/styles/vendors/kendo/buttons/_variants.scss - (shared with login.component.css and change-password.component.css). */ -.example { +.login-body { position: fixed; - top: 30%; - left: 50%; - /* bring your own prefixes */ - transform: translate(-50%, -50%); + inset: 0; } -.k-form { - width: 240px; +.forgot-title { + margin: 0 0 8px; + color: var(--gh-tb); + font-family: var(--gh-font); + font-size: 20px; + font-weight: 700; +} + +.forgot-label { + display: block; + color: var(--gh-st); + margin-bottom: 4px; + font-size: 13px; + font-weight: 600; +} + +.forgot-input { + width: 100%; +} + +.forgot-invalid { + border-color: var(--gh-dn) !important; +} + +.forgot-error { + display: block; + margin-top: 4px; + color: var(--gh-dn); + font-size: 12px; +} + +.forgot-success { + margin-bottom: 16px; + line-height: 1.5; +} + +.login-forgot { + margin-left: 20px; + color: var(--gh-st); + font-weight: 600; + cursor: pointer; +} + +.login-forgot:hover, +.login-forgot:focus-visible { + color: var(--gh-tb); + text-decoration: underline; +} + +/* Description / success text on the dark background */ +.login-body .login-content.forgot-content p { + color: var(--gh-st); +} + +.login-body .login-content.forgot-content p b { + color: var(--gh-tb); +} + +/* Error text: red lightened toward white so it stays readable on the dark background */ +.forgot-error { + color: color-mix(in srgb, var(--gh-dn) 55%, var(--gh-tb)); } diff --git a/HRM.UI/ClientApp/src/app/forgot-password.component.html b/HRM.UI/ClientApp/src/app/forgot-password.component.html index 64b0506..7384ecb 100644 --- a/HRM.UI/ClientApp/src/app/forgot-password.component.html +++ b/HRM.UI/ClientApp/src/app/forgot-password.component.html @@ -1,74 +1,44 @@ -
-
-
- Forgot your password? +
-
-
- - + @if (sentToEmail) { +
+

A password reset link has been sent to {{ sentToEmail }}.

+ @if (linkExpiryMinutes) { +

The link will expire in {{ linkExpiryMinutes }} minutes and can be used only once.

+ } +

Please check your inbox (and spam / junk folder).

-
+ + + + } ---> + diff --git a/HRM.UI/ClientApp/src/app/forgot-password.component.ts b/HRM.UI/ClientApp/src/app/forgot-password.component.ts index 27d9569..0f40b2e 100644 --- a/HRM.UI/ClientApp/src/app/forgot-password.component.ts +++ b/HRM.UI/ClientApp/src/app/forgot-password.component.ts @@ -1,64 +1,99 @@ import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; -import {FormBuilder, FormGroup, Validators} from '@angular/forms'; -import {HRMNotificationService} from './app.notification.service'; -import {AuthService} from './_services/auth/auth.service'; -import {Router} from '@angular/router'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { HRMNotificationService } from './app.notification.service'; +import { AuthService } from './_services/auth/auth.service'; +import { ApiService } from './app.api.service'; +import { Router } from '@angular/router'; -import { ReactiveFormsModule, FormsModule } from '@angular/forms'; // ReactiveFormsModule এবং FormsModule -import { InputsModule } from '@progress/kendo-angular-inputs'; -import { LabelModule } from '@progress/kendo-angular-label'; @Component({ - selector: 'app-forgot-password', - templateUrl: './forgot-password.component.html', - styleUrls: ['./forgot-password.component.css'], - changeDetection: ChangeDetectionStrategy.Eager, - standalone: false, + selector: 'app-forgot-password', + templateUrl: './forgot-password.component.html', + styleUrls: ['./forgot-password.component.css'], + changeDetection: ChangeDetectionStrategy.Eager, + standalone: false, }) export class ForgotPasswordComponent implements OnInit { forgotPasswordForm: FormGroup; - employeeId = ''; - emailAddress = ''; - constructor(public notificationService: HRMNotificationService, - public authService: AuthService, - public router: Router) { } + submitted = false; + isSubmitting = false; + // Set after the link is mailed: masked address + how long the link is valid + sentToEmail: string = null; + linkExpiryMinutes: number = null; - ngOnInit() { - this.loadForm(); - } - loadForm() { - this.forgotPasswordForm = new FormBuilder().group({ - employeeId: ['', Validators.required], - emailAddress: ['', Validators.required], - }); - } + constructor(public notificationService: HRMNotificationService, + public authService: AuthService, + public apiService: ApiService, + public router: Router, + private fb: FormBuilder) { } + + ngOnInit() { + this.forgotPasswordForm = this.fb.group({ + loginId: ['', Validators.required], + }); + } + + get f() { + return this.forgotPasswordForm.controls; + } + + showError(control: string): boolean { + const c = this.forgotPasswordForm.get(control); + return !!c && c.invalid && (this.submitted || c.touched); + } onSubmit() { - if (!this.forgotPasswordForm.valid) { - this.notificationService.showError('Please fill up the forms properly'); - return; - } - const data = { - employeeId: this.employeeId, - emailAddress: this.emailAddress - }; + this.submitted = true; + if (this.forgotPasswordForm.invalid || this.isSubmitting) { + return; + } - this.authService.forgotPassword(data).subscribe( - () => {}, - (err) => { - console.log(err.error); - this.notificationService.showError(err.error); - }, - () => { - this.notificationService.showSuccess('Successfully sent password to your email address.'); - localStorage.removeItem('forgotpass'); - this.router.navigate(['/login']); - } - ); + const data = { + loginID: (this.f['loginId'].value || '').trim() + }; + if (data.loginID === '') { + this.f['loginId'].setValue(''); + return; + } + + this.isSubmitting = true; + this.authService.forgotPassword(data).subscribe( + (resp: any) => { + this.isSubmitting = false; + this.sentToEmail = resp?.maskedEmail; + this.linkExpiryMinutes = resp?.expiryMinutes; + this.notificationService.showSuccess('Password reset link has been sent to ' + this.sentToEmail); + }, + (err) => { + this.isSubmitting = false; + // 400 = account / email problem the user can act on -> warning; anything else is an error + const message = (err && typeof err.error === 'string' && err.error) ? err.error : 'Could not send the password reset link. Please try again.'; + if (err && err.status === 400) { + this.notificationService.showWarning(message); + } else { + this.notificationService.showError(message); + } + } + ); + } + + onSendAgain() { + this.sentToEmail = null; + this.linkExpiryMinutes = null; + this.submitted = false; } onGoBack() { + this.backToLogin(); + } + + // This component stays mounted (hidden) in app.main, so clear it before leaving + private backToLogin() { + this.submitted = false; + this.isSubmitting = false; + this.sentToEmail = null; + this.linkExpiryMinutes = null; + this.forgotPasswordForm.reset({ loginId: '' }); localStorage.removeItem('forgotpass'); this.router.navigate(['/login']); - } } diff --git a/HRM.UI/ClientApp/src/app/login.component.css b/HRM.UI/ClientApp/src/app/login.component.css index c6fc041..e25515f 100644 --- a/HRM.UI/ClientApp/src/app/login.component.css +++ b/HRM.UI/ClientApp/src/app/login.component.css @@ -113,7 +113,7 @@ color: var(--gh-ht); } .login-body .login-content .mfa-text { - color: var(--gh-muted); + color: var(--gh-st); font-size: 14px; font-weight: bolder; line-height: 1.5; @@ -153,7 +153,7 @@ color: var(--gh-ht); display: flex; align-items: center; gap: 6px; - color: var(--gh-muted); + color: var(--gh-st); font-size: 13px; margin-bottom: 20px; } @@ -164,7 +164,7 @@ color: var(--gh-ht); } .mfa-link { - color: var(--gh-muted); + color: var(--gh-st); cursor: pointer; } @@ -180,3 +180,28 @@ color: var(--gh-ht); .mfa-back .pi { font-size: 11px; } + +/* Sign-in text on the dark login background: light palette colours so it reads clearly */ +.login-body .login-content .login-welcome { + color: var(--gh-st); + font-weight: 600; +} + +.login-forgot-link { + margin: auto 0 auto 20px; + color: var(--gh-st); + font-weight: 600; + cursor: pointer; +} + +.login-forgot-link:hover, +.login-forgot-link:focus-visible { + color: var(--gh-tb); + text-decoration: underline; +} + +.login-body .login-content .login-version { + margin-top: 15px; + font-size: 12px; + color: var(--gh-st); +} diff --git a/HRM.UI/ClientApp/src/app/login.component.html b/HRM.UI/ClientApp/src/app/login.component.html index c860a40..8261465 100644 --- a/HRM.UI/ClientApp/src/app/login.component.html +++ b/HRM.UI/ClientApp/src/app/login.component.html @@ -15,7 +15,7 @@ @if (!apiService.isSSO && !showMfaModal) { } diff --git a/HRM.UI/ClientApp/src/app/login.component.ts b/HRM.UI/ClientApp/src/app/login.component.ts index 1b78686..d6c377e 100644 --- a/HRM.UI/ClientApp/src/app/login.component.ts +++ b/HRM.UI/ClientApp/src/app/login.component.ts @@ -113,7 +113,9 @@ export class LoginComponent implements OnInit { }, () => { this.loadingPanel.ShowLoadingPanel = false; - if (this.apiService.isSSO === true) { + // Not on the password reset page (app.main shows it instead of this form): no SSO redirect there + const onResetPasswordPage = (window.location.hash || '').toLowerCase().startsWith('#/reset-password'); + if (this.apiService.isSSO === true && !onResetPasswordPage) { this.msalBroadcastService.msalSubject$ .pipe(filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),) .subscribe((result: EventMessage) => {}); diff --git a/HRM.UI/ClientApp/src/app/reset-password.component.css b/HRM.UI/ClientApp/src/app/reset-password.component.css new file mode 100644 index 0000000..991efa7 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/reset-password.component.css @@ -0,0 +1,45 @@ +/* Shares the Forgot Password page styles (forgot-password.component.css); only reset-page bits here. */ + +.reset-password-box { + position: relative; +} + +.reset-password-box .forgot-input { + padding-right: 52px; +} + +.reset-toggle { + position: absolute; + top: 50%; + right: 10px; + transform: translateY(-50%); + font-size: 12px; + font-weight: 600; + color: var(--gh-lk); + cursor: pointer; + user-select: none; +} + +.reset-message { + margin-bottom: 16px; + color: var(--gh-st); + padding: 10px 12px; + border-radius: 4px; + line-height: 1.5; +} + +.reset-message-warn { + border: 1px solid var(--gh-dn); +} + +.reset-message-ok { + border: 1px solid var(--gh-ok); +} + +.reset-hidden-username { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; +} diff --git a/HRM.UI/ClientApp/src/app/reset-password.component.html b/HRM.UI/ClientApp/src/app/reset-password.component.html new file mode 100644 index 0000000..d33245d --- /dev/null +++ b/HRM.UI/ClientApp/src/app/reset-password.component.html @@ -0,0 +1,70 @@ + diff --git a/HRM.UI/ClientApp/src/app/reset-password.component.ts b/HRM.UI/ClientApp/src/app/reset-password.component.ts new file mode 100644 index 0000000..70a8d30 --- /dev/null +++ b/HRM.UI/ClientApp/src/app/reset-password.component.ts @@ -0,0 +1,173 @@ +import { Component, HostListener, OnInit, ChangeDetectionStrategy } from '@angular/core'; +import { AbstractControl, FormBuilder, FormGroup, ValidationErrors, Validators } from '@angular/forms'; +import { Router } from '@angular/router'; +import { HRMNotificationService } from './app.notification.service'; +import { AuthService } from './_services/auth/auth.service'; +import { ApiService } from './app.api.service'; + +/** + * Opened from the password reset link in the email: /#/reset-password?token=... + * Shown by app.main outside the main layout (like the login / forgot password pages). + * The token is encrypted on the server; this page only passes it back for validation. + */ +@Component({ + selector: 'app-reset-password', + templateUrl: './reset-password.component.html', + styleUrls: ['./forgot-password.component.css', './reset-password.component.css'], + changeDetection: ChangeDetectionStrategy.Eager, + standalone: false, +}) +export class ResetPasswordComponent implements OnInit { + resetForm: FormGroup; + token: string = null; + state: 'validating' | 'invalid' | 'form' | 'done' = 'validating'; + invalidMessage = ''; + loginID = ''; + userName = ''; + submitted = false; + isSubmitting = false; + showNewPassword = false; + showConfirmPassword = false; + + constructor(private fb: FormBuilder, + private router: Router, + public authService: AuthService, + public apiService: ApiService, + public notificationService: HRMNotificationService) { } + + ngOnInit() { + this.resetForm = this.fb.group({ + // No strength / length rule (same as Change Password): any password the user wants + newPassword: ['', Validators.required], + confirmPassword: ['', Validators.required], + }, { validators: ResetPasswordComponent.passwordsMatch }); + this.loadFromLink(); + } + + // A second reset link opened in the same tab only changes the hash + @HostListener('window:hashchange') + onHashChange() { + const token = ResetPasswordComponent.readTokenFromUrl(); + if (token && token !== this.token) { + this.loadFromLink(); + } + } + + static readTokenFromUrl(): string { + const hash = window.location.hash || ''; + const q = hash.indexOf('?'); + if (q < 0) { + return null; + } + const token = new URLSearchParams(hash.substring(q + 1)).get('token'); + return token ? token.trim() : null; + } + + static passwordsMatch(group: AbstractControl): ValidationErrors | null { + const p = group.get('newPassword')?.value; + const c = group.get('confirmPassword')?.value; + return p && c && p !== c ? { mismatch: true } : null; + } + + get f() { + return this.resetForm.controls; + } + + showError(control: string): boolean { + const c = this.resetForm.get(control); + return !!c && c.invalid && (this.submitted || c.touched); + } + + get showMismatch(): boolean { + const c = this.resetForm.get('confirmPassword'); + return !!this.resetForm.errors?.['mismatch'] && (this.submitted || (!!c && c.touched)); + } + + private loadFromLink() { + this.token = ResetPasswordComponent.readTokenFromUrl(); + this.submitted = false; + this.isSubmitting = false; + this.resetForm.reset({ newPassword: '', confirmPassword: '' }); + + if (!this.token) { + this.setInvalid('This password reset link is invalid. Please request a new one from Forgot Password.'); + return; + } + + this.state = 'validating'; + this.authService.validateResetPasswordToken({ token: this.token }).subscribe( + (resp: any) => { + this.loginID = resp?.loginID || ''; + this.userName = resp?.userName || ''; + this.state = 'form'; + }, + (err) => { + this.setInvalid(this.errorText(err, 'Could not verify the password reset link. Please try again.')); + } + ); + } + + onSubmit() { + this.submitted = true; + if (this.resetForm.invalid || this.isSubmitting) { + return; + } + + const data = { + token: this.token, + newPassword: this.f['newPassword'].value, + confirmPassword: this.f['confirmPassword'].value + }; + + this.isSubmitting = true; + this.authService.resetPassword(data).subscribe( + () => { + this.isSubmitting = false; + this.state = 'done'; + this.resetForm.reset({ newPassword: '', confirmPassword: '' }); + this.notificationService.showSuccess('Your password has been changed successfully. Please sign in with your new password.'); + }, + (err) => { + this.isSubmitting = false; + const message = this.errorText(err, 'Could not change the password. Please try again.'); + if (err && err.status === 400) { + // Link expired / used / invalid while the page was open -> show the link message + if (/reset link|not active/i.test(message)) { + this.setInvalid(message); + } else { + this.notificationService.showWarning(message); + } + } else { + this.notificationService.showError(message); + } + } + ); + } + + onRequestNewLink() { + this.leave(true); + } + + onBackToLogin() { + this.leave(false); + } + + private setInvalid(message: string) { + this.invalidMessage = message; + this.state = 'invalid'; + } + + private errorText(err: any, fallback: string): string { + return (err && typeof err.error === 'string' && err.error) ? err.error : fallback; + } + + // Leave the reset page: to the Forgot Password form or the Sign In form (both shown by app.main) + private leave(toForgotPassword: boolean) { + this.token = null; + this.authService.logout(false); + if (toForgotPassword) { + localStorage.setItem('forgotpass', JSON.stringify(true)); + } + this.router.navigate(['/login']); + } +} diff --git a/HRM.UI/Controllers/Auth/AuthController.cs b/HRM.UI/Controllers/Auth/AuthController.cs index 8e302d3..16902aa 100644 --- a/HRM.UI/Controllers/Auth/AuthController.cs +++ b/HRM.UI/Controllers/Auth/AuthController.cs @@ -29,6 +29,9 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; +using HRM.UI.Helpers; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace HRM.UI.Controllers { @@ -56,6 +59,10 @@ namespace HRM.UI.Controllers private readonly IUserLogInInfoService _userLogInInfoService; private readonly IBadLoginAttemptInfoService _badLoginAttemptInfoService; private readonly ISystemAuditHistoryService _systemAuditHistoryService; + private readonly IOptions _forgotPasswordSettings; + private readonly IWebHostEnvironment _hostEnvironment; + // Angular dev server (ng serve) - the only origin allowed by CORS in development + private const string DevelopmentWebAddress = "http://localhost:4200/"; public AuthController(IConfiguration config, IUserService userService, @@ -75,8 +82,12 @@ namespace HRM.UI.Controllers IMemoryCache cache, IUserLogInInfoService userLogInInfoService, IBadLoginAttemptInfoService badLoginAttemptInfoService, - ISystemAuditHistoryService systemAuditHistoryService) + ISystemAuditHistoryService systemAuditHistoryService, + IOptions forgotPasswordSettings, + IWebHostEnvironment hostEnvironment) { + this._forgotPasswordSettings = forgotPasswordSettings; + this._hostEnvironment = hostEnvironment; _config = config; _jwt = jwtOptions.Value; _userService = userService; @@ -2274,46 +2285,170 @@ namespace HRM.UI.Controllers return Ok(true); } + #region Forgot Password (reset link) + + private const string ResetLinkInvalidMessage = "This password reset link is invalid. Please request a new one from Forgot Password."; + private const string ResetLinkExpiredMessage = "This password reset link has expired. Please request a new one from Forgot Password."; + private const string ResetLinkUsedMessage = "This password reset link has already been used. Please request a new one from Forgot Password."; + + /// + /// Step 1: user gives only the Login ID. The account is found in login priority + /// (Employee -> User/Admin -> Super User) and an encrypted, time-limited reset link is mailed to + /// Employee.EmailAddress (employee) or Users.Email (admin / super user). + /// 400 = a problem the user can act on (shown as a warning), 500 = server / mail error. + /// [HttpPost("forgotPassword")] [AllowAnonymous] - public ActionResult ForgotPassword(dynamic data) + public ActionResult ForgotPassword(ForgotPasswordDto item) { try { - EmailSettings emailSettings = _emailSettings.Value; - var item = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(data)); - string employeeId = (string) item["employeeId"].ToObject(); - string emailAddress = (string) item["emailAddress"].ToObject(); - User user = _userService.GetByLogINID(employeeId, EnumSystemType.Self_Service); + string loginId = (item?.LoginID ?? string.Empty).Trim(); + if (loginId == string.Empty) + { + return BadRequest("Login ID is required."); + } + + User user = _userService.GetUserForPasswordReset(loginId); if (user == null) { - // error message - return StatusCode(StatusCodes.Status500InternalServerError, "Employee-ID not found in the system."); - } - Employee oemp = new EmployeeService().GetByEmail(emailAddress); - if(oemp ==null) - { - return StatusCode(StatusCodes.Status500InternalServerError, "Invalid Email Address"); + return BadRequest("No active user account was found for this Login ID."); } - if(oemp.EmployeeNo.ToLower() != employeeId.ToLower()) + // Same rule as login: an employee whose contract has ended cannot log in + if (user.UserType == EnumUserType.Employee && user.Employee != null + && user.Employee.EndOfContractDate != null && user.Employee.EndOfContractDate < DateTime.Today) { - return StatusCode(StatusCodes.Status500InternalServerError, "Invalid Email Address"); + return BadRequest("No active user account was found for this Login ID."); } - if(oemp.Status != EnumEmployeeStatus.Live) + string emailAddress = (user.UserType == EnumUserType.Employee + ? user.Employee?.EmailAddress + : user.Email) ?? string.Empty; + emailAddress = emailAddress.Trim(); + + if (emailAddress == string.Empty) { - return StatusCode(StatusCodes.Status500InternalServerError, "Invalid Email Address"); + return BadRequest(user.UserType == EnumUserType.Employee + ? "No email address is registered for this employee. Please contact HR to update your email address." + : "No email address is registered for this user. Please contact the system administrator."); + } + if (!MailSender.IsValidEmail(emailAddress)) + { + return BadRequest("The email address registered for this account is not valid. Please contact HR / the system administrator."); } - string password = Ease.NetCore.Utility.Global.CipherFunctions.Decrypt("CeLiMiTeD.AdMIn", user.Password); + int expiryMinutes = _forgotPasswordSettings.Value.GetLinkExpiryMinutes(); + PasswordResetTokenData tokenData = new PasswordResetTokenData + { + UserID = user.ID, + UserType = (int)user.UserType, + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(expiryMinutes).ToUnixTimeSeconds(), + Stamp = PasswordResetTokenHelper.CreateStamp(user.ID, user.Password) + }; + string token = PasswordResetTokenHelper.CreateToken(this.Secret, tokenData); + string resetLink = this.GetResetPasswordPageUrl() + "#/reset-password?token=" + Uri.EscapeDataString(token); + MailSender mailSender = new MailSender(); mailSender.AddTo(emailAddress); - mailSender.Subject = "Your HR software Login Password (Do not replay this mail)"; - mailSender.Body = "

User Log-in ID : " + employeeId + "

"; - mailSender.Body += "

Password : " + password + "

"; - mailSender.SendMail(emailSettings); - System.Threading.Thread.Sleep(500); + mailSender.Subject = "Reset your HR software password (Do not reply to this mail)"; + mailSender.Body = this.GetResetPasswordMailBody(user, resetLink, expiryMinutes); + + // SendMail(settings, "") reports failure (returns false) instead of swallowing it + if (!mailSender.SendMail(_emailSettings.Value, string.Empty)) + { + return StatusCode(StatusCodes.Status500InternalServerError, + "Could not send the email. Please check the email settings or try again later."); + } + + return Ok(new { maskedEmail = MaskEmail(emailAddress), expiryMinutes = expiryMinutes }); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + } + + /// + /// Step 2: the reset page calls this as soon as it opens - decrypts and validates the link. + /// + [HttpPost("validateResetPasswordToken")] + [AllowAnonymous] + public ActionResult ValidateResetPasswordToken(ResetPasswordTokenDto item) + { + try + { + User user; + long expiresAt; + string error = this.ValidateResetToken(item?.Token, out user, out expiresAt); + if (error != null) + { + return BadRequest(error); + } + + return Ok(new + { + loginID = user.LoginID, + userName = user.UserName, + expiresAt = DateTimeOffset.FromUnixTimeSeconds(expiresAt).UtcDateTime + }); + } + catch (Exception e) + { + return StatusCode(StatusCodes.Status500InternalServerError, e.Message); + } + } + + /// + /// Step 3: set the new password. The link is validated again here; once the password changes + /// the link's stamp no longer matches, so the same link cannot be used twice. + /// + [HttpPost("resetPassword")] + [AllowAnonymous] + public ActionResult ResetPassword(ResetPasswordDto item) + { + try + { + User user; + long expiresAt; + string error = this.ValidateResetToken(item?.Token, out user, out expiresAt); + if (error != null) + { + return BadRequest(error); + } + + string newPassword = (item.NewPassword ?? string.Empty).Trim(); + string confirmPassword = (item.ConfirmPassword ?? string.Empty).Trim(); + + if (newPassword == string.Empty || confirmPassword == string.Empty) + { + return BadRequest("New Password and Confirm Password are required."); + } + if (newPassword != confirmPassword) + { + return BadRequest("Confirm Password does not match the New Password."); + } + // No password strength / length rule (same as Change Password) - the user may choose any password + + string oldPassword = user.Password; + string newEncryptedPassword = Ease.NetCore.Utility.Global.CipherFunctions.Encrypt("CeLiMiTeD.AdMIn", newPassword); + if (newEncryptedPassword == oldPassword) + { + return BadRequest("New Password cannot be the same as your current password."); + } + + // Same save path as Change Password + user.Password = newEncryptedPassword; + user.LastPasswordChangedDate = DateTime.Today; + user.ChangePasswordAtNextLogon = false; + _userService.ChangePasswordEss(user); + + PasswordHistory history = new PasswordHistory(); + history.UserID = user.ID; + history.UserPassword = oldPassword; + history.CreatedBy = user.ID; + history.CreatedDate = DateTime.Today; + _passwordHistoryService.Save(history); } catch (Exception e) { @@ -2323,6 +2458,117 @@ namespace HRM.UI.Controllers return Ok(true); } + /// + /// Decrypts the reset token and checks expiry, the account and that the link was not used. + /// Returns null when valid, otherwise the message to show. + /// + private string ValidateResetToken(string token, out User user, out long expiresAt) + { + user = null; + expiresAt = 0; + + PasswordResetTokenData data = PasswordResetTokenHelper.ReadToken(this.Secret, token); + if (data == null || data.UserID <= 0) + { + return ResetLinkInvalidMessage; + } + + expiresAt = data.ExpiresAt; + if (DateTimeOffset.UtcNow.ToUnixTimeSeconds() > data.ExpiresAt) + { + return ResetLinkExpiredMessage; + } + + User ouser = _userService.Get(data.UserID); + if (ouser == null || (int)ouser.UserType != data.UserType) + { + return ResetLinkInvalidMessage; + } + if (ouser.UserStatus != EnumAuthStatus.Active && ouser.UserStatus != EnumAuthStatus.Approved) + { + return "This user account is not active. Please contact the system administrator."; + } + if (ouser.UserType == EnumUserType.Employee) + { + DateTime eocd = _userService.GetEndofContractDate(ouser.LoginID); + if (eocd != DateTime.MinValue && eocd < DateTime.Today) + { + return "This user account is not active. Please contact HR."; + } + } + if (!PasswordResetTokenHelper.IsSameStamp(data.Stamp, PasswordResetTokenHelper.CreateStamp(ouser.ID, ouser.Password))) + { + return ResetLinkUsedMessage; + } + + user = ouser; + return null; + } + + /// + /// Base URL of the web app for the reset link: + /// Development -> the Angular dev server (http://localhost:4200/); + /// otherwise EmailSettings.WebAddress from appsettings (the same address the other notification + /// mails link to), falling back to this request's own address if it is not set. + /// + private string GetResetPasswordPageUrl() + { + if (_hostEnvironment.IsDevelopment()) + { + return DevelopmentWebAddress; + } + + string baseUrl = (_emailSettings.Value.WebAddress ?? string.Empty).Trim(); + if (baseUrl == string.Empty) + { + baseUrl = Request.Scheme + "://" + Request.Host.Value + Request.PathBase.Value; + } + int hashIndex = baseUrl.IndexOf('#'); + if (hashIndex >= 0) + { + baseUrl = baseUrl.Substring(0, hashIndex); + } + return baseUrl.EndsWith("/") ? baseUrl : baseUrl + "/"; + } + + private string GetResetPasswordMailBody(User user, string resetLink, int expiryMinutes) + { + string name = WebUtility.HtmlEncode(string.IsNullOrWhiteSpace(user.UserName) ? user.LoginID : user.UserName); + string loginId = WebUtility.HtmlEncode(user.LoginID); + string link = WebUtility.HtmlEncode(resetLink); + + return "
" + + "

Dear " + name + ",

" + + "

We received a request to reset the password of your HR software account " + + "(Login ID: " + loginId + ").

" + + "

Please click the button below to set a new password. This link will expire in " + + expiryMinutes + " minutes and can be used only once.

" + + "

" + + "Reset Password

" + + "

If the button does not work, copy and paste this link into your browser:
" + + "" + link + "

" + + "

If you did not request a password reset, please ignore this email. Your password will not be changed.

" + + "


This is a system generated mail, Please do not reply.

" + + "
"; + } + + // jo****@company.com - shows the user which mailbox to check without exposing the full address + private static string MaskEmail(string email) + { + int at = email.IndexOf('@'); + if (at <= 0) + { + return "****"; + } + string local = email.Substring(0, at); + string domain = email.Substring(at); + int visible = local.Length <= 2 ? 1 : 2; + return local.Substring(0, visible) + new string('*', Math.Max(4, local.Length - visible)) + domain; + } + + #endregion + [HttpGet] [Route("getVersionNumber")] public ActionResult getVersionNumber() diff --git a/HRM.UI/DTOs/Auth/ForgotPasswordDto.cs b/HRM.UI/DTOs/Auth/ForgotPasswordDto.cs new file mode 100644 index 0000000..e37098a --- /dev/null +++ b/HRM.UI/DTOs/Auth/ForgotPasswordDto.cs @@ -0,0 +1,19 @@ +namespace HRM.UI.DTOs.Auth +{ + public class ForgotPasswordDto + { + public string LoginID { get; set; } + } + + public class ResetPasswordTokenDto + { + public string Token { get; set; } + } + + public class ResetPasswordDto + { + public string Token { get; set; } + public string NewPassword { get; set; } + public string ConfirmPassword { get; set; } + } +} diff --git a/HRM.UI/Helpers/PasswordResetTokenHelper.cs b/HRM.UI/Helpers/PasswordResetTokenHelper.cs new file mode 100644 index 0000000..379904c --- /dev/null +++ b/HRM.UI/Helpers/PasswordResetTokenHelper.cs @@ -0,0 +1,125 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using Newtonsoft.Json; + +namespace HRM.UI.Helpers +{ + /// + /// Data carried (encrypted) inside the password reset link. + /// + public class PasswordResetTokenData + { + public int UserID { get; set; } + public int UserType { get; set; } + // Expiry, Unix time (seconds, UTC) + public long ExpiresAt { get; set; } + // Fingerprint of the password at the time the link was made - changes once the password + // is reset, so a link works only once. + public string Stamp { get; set; } + } + + /// + /// Builds and reads the password reset link token. + /// The token is AES-256-GCM encrypted (confidential + tamper-proof) with a key derived from + /// AppSettings.Secret, and URL-safe Base64 encoded: nonce(12) | tag(16) | cipher text. + /// + public static class PasswordResetTokenHelper + { + private const int NonceSize = 12; + private const int TagSize = 16; + private const string KeyPurpose = "|HRM.ForgotPassword.ResetLink.v1"; + + public static string CreateToken(string secret, PasswordResetTokenData data) + { + byte[] plain = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data)); + byte[] nonce = RandomNumberGenerator.GetBytes(NonceSize); + byte[] cipher = new byte[plain.Length]; + byte[] tag = new byte[TagSize]; + + using (AesGcm aes = new AesGcm(DeriveKey(secret), TagSize)) + { + aes.Encrypt(nonce, plain, cipher, tag); + } + + byte[] token = new byte[NonceSize + TagSize + cipher.Length]; + Buffer.BlockCopy(nonce, 0, token, 0, NonceSize); + Buffer.BlockCopy(tag, 0, token, NonceSize, TagSize); + Buffer.BlockCopy(cipher, 0, token, NonceSize + TagSize, cipher.Length); + return ToBase64Url(token); + } + + /// + /// Decrypts the token. Returns null when it is malformed, was changed, or was not made by this server. + /// (Expiry is checked by the caller so it can show a separate "expired" message.) + /// + public static PasswordResetTokenData ReadToken(string secret, string token) + { + try + { + if (string.IsNullOrWhiteSpace(token)) return null; + + byte[] raw = FromBase64Url(token.Trim()); + if (raw.Length <= NonceSize + TagSize) return null; + + byte[] nonce = new byte[NonceSize]; + byte[] tag = new byte[TagSize]; + byte[] cipher = new byte[raw.Length - NonceSize - TagSize]; + Buffer.BlockCopy(raw, 0, nonce, 0, NonceSize); + Buffer.BlockCopy(raw, NonceSize, tag, 0, TagSize); + Buffer.BlockCopy(raw, NonceSize + TagSize, cipher, 0, cipher.Length); + + byte[] plain = new byte[cipher.Length]; + using (AesGcm aes = new AesGcm(DeriveKey(secret), TagSize)) + { + aes.Decrypt(nonce, cipher, tag, plain); + } + + return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(plain)); + } + catch (Exception) + { + // CryptographicException (tampered / wrong key), FormatException, JsonException ... + return null; + } + } + + /// + /// Fingerprint of the user's current (stored, encrypted) password. + /// + public static string CreateStamp(int userId, string storedPassword) + { + byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(userId + "|" + (storedPassword ?? string.Empty))); + return Convert.ToHexString(hash, 0, 16); + } + + public static bool IsSameStamp(string a, string b) + { + if (a == null || b == null) return false; + return CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(a), Encoding.UTF8.GetBytes(b)); + } + + private static byte[] DeriveKey(string secret) + { + if (string.IsNullOrEmpty(secret)) + throw new InvalidOperationException("AppSettings.Secret is not configured."); + return SHA256.HashData(Encoding.UTF8.GetBytes(secret + KeyPurpose)); + } + + private static string ToBase64Url(byte[] data) + { + return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + + private static byte[] FromBase64Url(string data) + { + string s = data.Replace('-', '+').Replace('_', '/'); + switch (s.Length % 4) + { + case 2: s += "=="; break; + case 3: s += "="; break; + } + return Convert.FromBase64String(s); + } + } +} diff --git a/HRM.UI/Startup.cs b/HRM.UI/Startup.cs index aa9127e..51c9c3b 100644 --- a/HRM.UI/Startup.cs +++ b/HRM.UI/Startup.cs @@ -60,6 +60,7 @@ namespace HRM.UI.Api services.Configure(Configuration.GetSection("AdminPendingJob")); services.Configure(Configuration.GetSection("MobileAppSettings")); services.Configure(Configuration.GetSection("FundInfo")); + services.Configure(Configuration.GetSection("ForgotPasswordSettings")); // Calendar reminders and notifications (Hangfire) services.AddCalendarBackgroundJobs(Configuration, HostingEnvironment); diff --git a/HRM.UI/appsettings.json b/HRM.UI/appsettings.json index 607abe1..fadd8ef 100644 --- a/HRM.UI/appsettings.json +++ b/HRM.UI/appsettings.json @@ -102,6 +102,9 @@ "Profile": "Admin", "MedicalClaim": "x" }, + "ForgotPasswordSettings": { + "LinkExpiryMinutes": 10 + }, "RDLCLocation": "", "AllowedHosts": "*",