Forget Password

This commit is contained in:
Mohaimen Hasan 2026-11-24 12:01:14 +06:00
parent 2fabc526bd
commit e6fd563fe9
26 changed files with 1094 additions and 167 deletions

View File

@ -0,0 +1,18 @@
namespace HRM.BO.Configuration
{
/// <summary>
/// "ForgotPasswordSettings" section of appsettings.json.
/// </summary>
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;
}
}
}

View File

@ -513,6 +513,7 @@ namespace HRM.BO
List<Employee> 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);

View File

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

View File

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

View File

@ -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<Employee>(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;

View File

@ -637,7 +637,71 @@ namespace HRM.DA
return oUser;
}
/// <summary>
/// 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.
/// </summary>
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<User>(oreader);
oUser.Employee = oEmployee;
}
oreader.Close();
}
if (oUser == null)
{
oreader = new DataReader(UserDA.GetActiveByLoginID(tc, loginID, EnumUserType.User));
if (oreader.Read())
{
oUser = this.CreateObject<User>(oreader);
}
oreader.Close();
}
if (oUser == null)
{
oreader = new DataReader(UserDA.GetActiveByLoginID(tc, loginID, EnumUserType.SuperUser));
if (oreader.Read())
{
oUser = this.CreateObject<User>(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)
{

View File

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

View File

@ -112,7 +112,8 @@ export class AuthService {
GetAllEmpNotYetUser() {
return this.apiService.httpGet<User[]>('/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<any>('/Authentication/logOut', {}).subscribe({ error: () => {} });
}
@ -290,6 +293,12 @@ export class AuthService {
forgotPassword(data: any) {
return this.apiService.httpPost<any>('/Authentication/forgotPassword', data);
}
validateResetPasswordToken(data: any) {
return this.apiService.httpPost<any>('/Authentication/validateResetPasswordToken', data);
}
resetPassword(data: any) {
return this.apiService.httpPost<any>('/Authentication/resetPassword', data);
}
getVersionNumber() {
return this.apiService.httpGet<string>('/Authentication/getVersionNumber');
}

View File

@ -1,4 +1,4 @@
<div class="layout-wrapper" [hidden]="isLoginForm() || forgotpassword()" (click)="onLayoutClick()"
<div class="layout-wrapper" [hidden]="isLoginForm() || forgotpassword() || isResetPassword()" (click)="onLayoutClick()"
[ngClass]="{'layout-static': isStatic(),
'layout-overlay': isOverlay(),
'layout-overlay-active': overlayMenuActive,
@ -40,3 +40,6 @@
</div>
<app-login [hidden]="!isLoginForm()"></app-login>
<app-forgot-password [hidden]="!forgotpassword()"></app-forgot-password>
@if (isResetPassword()) {
<app-reset-password></app-reset-password>
}

View File

@ -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: <app>/#/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;

View File

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

View File

@ -66,6 +66,15 @@ export const routes: Routes = [
title: 'Forgot Password'
}
},
{
// Password reset link from the email. Rendered by app.main (<app-reset-password>) 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 },

View File

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

View File

@ -1,74 +1,44 @@
<div class="example">
<form class="k-form" [formGroup]="forgotPasswordForm">
<fieldset class="k-form-fieldset">
<legend class="k-form-legend">Forgot your password?</legend>
<div class="login-body">
<div class="login-panel"></div>
<div class="login-content forgot-content" style="margin-top: 100px;">
<img src="assets/layout/images/banner.png" alt="Banner" />
<!--<kendo-avatar initials="EG"
width="80px"
height="80px"
shape="circle"></kendo-avatar>-->
<kendo-formfield>
<kendo-label [for]="employeeId" text="Employee Id"></kendo-label>
<!--<kendo-textbox formControlName="employeeId" [(ngModel)]="employeeId"
[clearButton]="true"
#employeeId
required></kendo-textbox>-->
<input type="text" formControlName="employeeId" [(ngModel)]="employeeId" style="width: 100%" kendoTextBox required>
<!--<kendo-formhint>Employee Id</kendo-formhint>-->
<kendo-formerror>Error: Employee Id is required</kendo-formerror>
</kendo-formfield>
<kendo-formfield>
<kendo-label [for]="emailAddress" text="Email Address"> </kendo-label>
<!--<kendo-textbox formControlName="emailAddress" [(ngModel)]="emailAddress"
#emailAddress
required
[clearButton]="true">
</kendo-textbox>-->
<input type="text" formControlName="emailAddress" [(ngModel)]="emailAddress" style="width: 100%" kendoTextBox required >
<!--<kendo-formhint>Email Address</kendo-formhint>-->
<kendo-formerror>Error: Email Address is required</kendo-formerror>
</kendo-formfield>
<h2 class="forgot-title">Forgot Password?</h2>
<!-- Step 1: ask for the Login ID -->
@if (!sentToEmail) {
<p>Enter your Login ID. A password reset link will be sent to the email address registered for your account.</p>
<div class="k-form-buttons">
<button class="k-button k-primary gh-submit" (click)="onSubmit()">Submit</button>
<button class="k-button gh-back" (click)="onGoBack()">Go Back</button>
</div>
</fieldset>
</form>
</div>
<!--<form [formGroup]="forgotPasswordForm">
<div class="col-8 p-offset-2">
<div class="card">
<div class="grid">
<div class="col-12">
<h1 class="p1">Forgot your password?</h1>
<h4>*Please fill following information and click send button. If your information is valid, system will send your current
password to your email address</h4>
<form [formGroup]="forgotPasswordForm" (ngSubmit)="onSubmit()" novalidate>
<div class="login-input-wrapper">
<label for="fpLoginId" class="forgot-label">Login ID</label>
<input id="fpLoginId" type="text" autocomplete="username" placeholder="Login ID" kendoTextBox
formControlName="loginId" maxlength="100" class="login-cotrol forgot-input"
[class.forgot-invalid]="showError('loginId')" />
@if (showError('loginId')) {
<small class="forgot-error">Login ID is required</small>
}
</div>
<div class="col-12">
<fieldset>
<legend>Account Information</legend>
<div class="grid">
<div class="col-2">
<label>Employee Id</label>
</div>
<div class="col-10">
<input type="text" formControlName="employeeId" [(ngModel)]="employeeId" style="width: 100%" pInputText>
</div>
<div class="col-2">
<Label>Email Address</Label>
</div>
<div class="col-10">
<input type="text" formControlName="emailAddress" [(ngModel)]="emailAddress" style="width: 100%" pInputText>
</div>
</div>
</fieldset>
</div>
<button type="button" label="Submit" (click)="onSubmit()" style="margin-right: 10px;" icon="pi pi-angle-right" pButton></button>
<button type="button" label="Go Back" (click)="onGoBack()" icon="pi pi-step-backward" pButton></button>
<button kendoButton type="submit" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['paperPlane']" [disabled]="isSubmitting">
{{ isSubmitting ? 'Sending...' : 'Send' }}
</button>
<a class="login-forgot" (click)="onGoBack()">&larr; Back to Sign In</a>
</form>
}
<!-- Step 2: link sent - show where (masked) -->
@if (sentToEmail) {
<div class="forgot-success">
<p>A password reset link has been sent to <b>{{ sentToEmail }}</b>.</p>
@if (linkExpiryMinutes) {
<p>The link will expire in <b>{{ linkExpiryMinutes }} minutes</b> and can be used only once.</p>
}
<p>Please check your inbox (and spam / junk folder).</p>
</div>
</div>
<button kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['undo']" (click)="onGoBack()">Back to Sign In</button>
<a class="login-forgot" (click)="onSendAgain()">Didn't get the email? Send again</a>
}
</div>
</form>-->
</div>

View File

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

View File

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

View File

@ -15,7 +15,7 @@
@if (!apiService.isSSO && !showMfaModal) {
<div class="login-content" style="margin-top: 100px;">
<img src="assets/layout/images/banner.png" alt="Banner" [style.width]="bannerWidth" [style.height]="bannerHeight"/>
<p style="color: var(--gh-muted); font-weight: bolder;">Welcome, please use the form to sign-in.</p>
<p class="login-welcome">Welcome, please use the form to sign-in.</p>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div class="login-input-wrapper">
<input type="text" autocomplete="off" placeholder="Username" kendoTextBox formControlName="username"
@ -39,8 +39,8 @@
}
</div>
<button kendoButton themeColor="primary">Sign In</button>
<a (click)="forgetPassword()" style="margin: auto; color: var(--gh-muted); margin-left: 20px; cursor: pointer;" onmouseover="this.style.color='White'" onmouseout="this.style.color='rgb(177, 177, 177)'">Forgot Password?</a>
<p style="margin-top:15px; font-size:12px;">Version: {{ appVersion }}</p>
<a class="login-forgot-link" (click)="forgetPassword()">Forgot Password?</a>
<p class="login-version">Version: {{ appVersion }}</p>
</form>
</div>
}
@ -77,7 +77,7 @@
<div class="mfa-back">
<a class="mfa-link" (click)="onPopUpOTPClose()"><i class="pi pi-arrow-left"></i> Back to Sign In</a>
</div>
<p style="margin-top:15px; font-size:12px;">Version: {{ appVersion }}</p>
<p class="login-version">Version: {{ appVersion }}</p>
</div>
</div>
}

View File

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

View File

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

View File

@ -0,0 +1,70 @@
<div class="login-body">
<div class="login-panel"></div>
<div class="login-content forgot-content" style="margin-top: 100px;">
<img src="assets/layout/images/banner.png" alt="Banner" />
<h2 class="forgot-title">Reset Password</h2>
<!-- Checking the link -->
@if (state === 'validating') {
<p>Verifying your password reset link, please wait...</p>
}
<!-- Invalid / expired / already used -->
@if (state === 'invalid') {
<div class="reset-message reset-message-warn">{{ invalidMessage }}</div>
<button kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['envelop']" (click)="onRequestNewLink()">Request a New Link</button>
<a class="login-forgot" (click)="onBackToLogin()">&larr; Back to Sign In</a>
}
<!-- New password form -->
@if (state === 'form') {
<p>Set a new password for <b>{{ userName || loginID }}</b>@if (userName && loginID) {<span> ({{ loginID }})</span>}.</p>
<form [formGroup]="resetForm" (ngSubmit)="onSubmit()" novalidate>
<!-- lets password managers link the new password to this account -->
<input type="text" class="reset-hidden-username" autocomplete="username" [value]="loginID" readonly tabindex="-1" aria-hidden="true" />
<div class="login-input-wrapper">
<label for="rpNewPassword" class="forgot-label">New Password</label>
<div class="reset-password-box">
<input id="rpNewPassword" [type]="showNewPassword ? 'text' : 'password'" autocomplete="new-password"
placeholder="New Password" kendoTextBox formControlName="newPassword" maxlength="30"
class="login-cotrol forgot-input" [class.forgot-invalid]="showError('newPassword')" />
<a class="reset-toggle" (click)="showNewPassword = !showNewPassword">{{ showNewPassword ? 'Hide' : 'Show' }}</a>
</div>
@if (showError('newPassword') && f['newPassword'].errors?.['required']) {
<small class="forgot-error">New Password is required</small>
}
</div>
<div class="login-input-wrapper">
<label for="rpConfirmPassword" class="forgot-label">Confirm Password</label>
<div class="reset-password-box">
<input id="rpConfirmPassword" [type]="showConfirmPassword ? 'text' : 'password'" autocomplete="new-password"
placeholder="Confirm Password" kendoTextBox formControlName="confirmPassword" maxlength="30"
class="login-cotrol forgot-input" [class.forgot-invalid]="showError('confirmPassword') || showMismatch" />
<a class="reset-toggle" (click)="showConfirmPassword = !showConfirmPassword">{{ showConfirmPassword ? 'Hide' : 'Show' }}</a>
</div>
@if (showError('confirmPassword')) {
<small class="forgot-error">Confirm Password is required</small>
}
@if (!showError('confirmPassword') && showMismatch) {
<small class="forgot-error">Confirm Password does not match the New Password</small>
}
</div>
<button kendoButton type="submit" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['save']" [disabled]="isSubmitting">
{{ isSubmitting ? 'Saving...' : 'Change Password' }}
</button>
<a class="login-forgot" (click)="onBackToLogin()">&larr; Back to Sign In</a>
</form>
}
<!-- Done -->
@if (state === 'done') {
<div class="reset-message reset-message-ok">Your password has been changed successfully. Please sign in with your new password.</div>
<button kendoButton type="button" themeColor="primary" [svgIcon]="apiService.KendoSVGIcon['user']" (click)="onBackToLogin()">Go to Sign In</button>
}
</div>
</div>

View File

@ -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: <app>/#/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']);
}
}

View File

@ -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> _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> 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.";
/// <summary>
/// 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.
/// </summary>
[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>();
string emailAddress = (string) item["emailAddress"].ToObject<string>();
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 = "<p> <b>User Log-in ID : </b> " + employeeId + "</p>";
mailSender.Body += "<p> <b>Password : </b> " + password + "</p>";
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);
}
}
/// <summary>
/// Step 2: the reset page calls this as soon as it opens - decrypts and validates the link.
/// </summary>
[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);
}
}
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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 "<div style=\"font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#333;\">"
+ "<p>Dear " + name + ",</p>"
+ "<p>We received a request to reset the password of your HR software account "
+ "(Login ID: <b>" + loginId + "</b>).</p>"
+ "<p>Please click the button below to set a new password. This link will expire in <b>"
+ expiryMinutes + " minutes</b> and can be used only once.</p>"
+ "<p style=\"margin:24px 0;\"><a href=\"" + link + "\" target=\"_blank\" "
+ "style=\"background:#1a73e8;color:#ffffff;padding:10px 22px;border-radius:4px;text-decoration:none;font-weight:bold;\">"
+ "Reset Password</a></p>"
+ "<p>If the button does not work, copy and paste this link into your browser:<br/>"
+ "<a href=\"" + link + "\" target=\"_blank\">" + link + "</a></p>"
+ "<p>If you did not request a password reset, please ignore this email. Your password will not be changed.</p>"
+ "<p><br/>This is a system generated mail, Please do not reply.</p>"
+ "</div>";
}
// 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()

View File

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

View File

@ -0,0 +1,125 @@
using System;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
namespace HRM.UI.Helpers
{
/// <summary>
/// Data carried (encrypted) inside the password reset link.
/// </summary>
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; }
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>
/// 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.)
/// </summary>
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<PasswordResetTokenData>(Encoding.UTF8.GetString(plain));
}
catch (Exception)
{
// CryptographicException (tampered / wrong key), FormatException, JsonException ...
return null;
}
}
/// <summary>
/// Fingerprint of the user's current (stored, encrypted) password.
/// </summary>
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);
}
}
}

View File

@ -60,6 +60,7 @@ namespace HRM.UI.Api
services.Configure<AdminPendingJob>(Configuration.GetSection("AdminPendingJob"));
services.Configure<MobileAppSettings>(Configuration.GetSection("MobileAppSettings"));
services.Configure<FundInfo>(Configuration.GetSection("FundInfo"));
services.Configure<ForgotPasswordSettings>(Configuration.GetSection("ForgotPasswordSettings"));
// Calendar reminders and notifications (Hangfire)
services.AddCalendarBackgroundJobs(Configuration, HostingEnvironment);

View File

@ -102,6 +102,9 @@
"Profile": "Admin",
"MedicalClaim": "x"
},
"ForgotPasswordSettings": {
"LinkExpiryMinutes": 10
},
"RDLCLocation": "",
"AllowedHosts": "*",