This commit is contained in:
Mohaimen Hasan 2026-11-03 15:54:54 +06:00
parent 838b8d4480
commit 125d79ed75
8 changed files with 447 additions and 240 deletions

View File

@ -294,8 +294,8 @@ the screens report problems the same way. Neither has a `<Menu>` node yet either
workbook is per salary month (row 1 carries the month, checked against the month posted as the workbook is per salary month (row 1 carries the month, checked against the month posted as the
`salaryMonth` form field). **7** layers, not 8, and layers 4–7 all run once layer 3 passes, so one `salaryMonth` form field). **7** layers, not 8, and layers 4–7 all run once layer 3 passes, so one
upload lists every problem of every row. A blank amount is saved as `NULL` — which needs upload lists every problem of every row. A blank amount is saved as `NULL` — which needs
`HistorySalaryMonthlyAmountNull_DB_Changes.sql` run first. That script was deleted from the root in `HistorySalaryMonthlyAmountNull_DB_Changes.sql` run first. That script is not in this repo — it was
`91369150c` (not archived): recover it with deleted (not archived) in `cel.hrm` commit `91369150c`; recover it from there with
`git show 91369150c^:HistorySalaryMonthlyAmountNull_DB_Changes.sql`. The service opens no transaction itself; `git show 91369150c^:HistorySalaryMonthlyAmountNull_DB_Changes.sql`. The service opens no transaction itself;
the save is `HistorySalaryMonthlyService`'s one all-or-nothing transaction. the save is `HistorySalaryMonthlyService`'s one all-or-nothing transaction.
- **Employee Profile Picture Bulk Upload** (second tab of the Employee Bulk Upload screen; - **Employee Profile Picture Bulk Upload** (second tab of the Employee Bulk Upload screen;
@ -324,8 +324,8 @@ A Google-Calendar-like module (`/calendar/my-calendar`, `/calendar/my-tasks`) on
header like `GeneralMail`), sent by `CalendarJobs.SendScheduleEmail` through `IEmailDispatchService` — so header like `GeneralMail`), sent by `CalendarJobs.SendScheduleEmail` through `IEmailDispatchService` — so
it shows, and is retried, in Mail Manager › Mail Log History. Body/subject tags (`<EMP-NAME>`, it shows, and is retried, in Mail Manager › Mail Log History. Body/subject tags (`<EMP-NAME>`,
`<DEPARTMENT>`, …) are listed and filled in one place, `HRM.DA/Service/Calendar/ScheduleEmailTags.cs`. `<DEPARTMENT>`, …) are listed and filled in one place, `HRM.DA/Service/Calendar/ScheduleEmailTags.cs`.
Schema: `ScheduleEmail_DB_Changes.sql` was deleted from the root once applied (commit `ac179c03e`) Schema: `ScheduleEmail_DB_Changes.sql` is **not** in this repo — it was deleted unarchived in `cel.hrm`;
and **not** archived in `db/Script/` — recover it with `git show 73f466cd0:ScheduleEmail_DB_Changes.sql`. recover it from a `cel.hrm` clone with `git show 73f466cd0:ScheduleEmail_DB_Changes.sql`.
- The organizer is `CreatedBy` **and** an attendee row with `Role = Organizer`. Holidays, leave and - The organizer is `CreatedBy` **and** an attendee row with `Role = Organizer`. Holidays, leave and
birthdays are read-only layers, read live from the existing tables (nothing is copied). birthdays are read-only layers, read live from the existing tables (nothing is copied).
- Repeats are RFC 5545 RRULEs worked out with **Ical.Net** (`HRM.DA/Service/Calendar/CalendarRecurrence.cs`). - Repeats are RFC 5545 RRULEs worked out with **Ical.Net** (`HRM.DA/Service/Calendar/CalendarRecurrence.cs`).
@ -463,18 +463,23 @@ When behavior differs between clients, look for or add a Logic key rather than b
## Branches: one product, many client deployments ## Branches: one product, many client deployments
`origin` (`103.197.204.162:3025/CelHRTeam/cel.hrm`) carries ~79 branches, and they are not short-lived **This checkout is not that repo.** It is `HRM-10` (`origin` = `103.197.204.162:3025/CelHRTeam/HRM-10`),
feature branches. The default/integration branch is **`devqc`**. The rest are long-lived **per-client** a fresh import with a single branch `main` and a single squashed commit (`838b8d4` "first commit").
branches (`BergerHR`, `SGSHR`, `IDLC_Payroll_Master`, `Square_PMS*`, `Wartsila`, `LiFungHR`, None of the older history exists here: every commit hash quoted elsewhere in this file (`c8588ce67`,
`Metlife_fund`, `PetromaxHR`, `ProclozPayroll`, `TexEbo_Payroll`, `Duncan_Payroll`, `HNM`, `PCSHRUAT`, `91369150c`, `ac179c03e`, `73f466cd0`, `bfd085e0e`) is from the original `CelHRTeam/cel.hrm` repo, and
…) and **per-developer** ones (`dev_<name>`, `dev_<name>Master`). `git show`/`git log` recovery commands only work in a clone of that repo, not here.
That original repo carries ~79 branches, and they are not short-lived feature branches. Its
default/integration branch is **`devqc`**. The rest are long-lived **per-client** branches
(`BergerHR`, `SGSHR`, `IDLC_Payroll_Master`, `Square_PMS*`, `Wartsila`, `LiFungHR`, `Metlife_fund`,
`PetromaxHR`, `ProclozPayroll`, `TexEbo_Payroll`, `Duncan_Payroll`, `HNM`, `PCSHRUAT`, …) and
**per-developer** ones (`dev_<name>`, `dev_<name>Master`).
Two consequences worth holding onto: Two consequences worth holding onto:
- Work moves between client branches by hand, as bulk "transferred from `<branch>`" commits — e.g. - Work moves between client branches by hand, as bulk "transferred from `<branch>`" commits. So a fix
`c8588ce67` "works transfered from square_pms". So a fix made here is *not* automatically in any made here is *not* automatically in any client's branch of `cel.hrm` (and vice versa), and a file
other client's branch, and a file can look freshly rewritten when it was only ported. Check can look freshly rewritten when it was only ported.
`git log --follow` before assuming a recent change was authored for this branch.
- This is *why* per-client behavior belongs in uploaded `*LogicConfiguration.xml` / `*-Menu.xml` data - This is *why* per-client behavior belongs in uploaded `*LogicConfiguration.xml` / `*-Menu.xml` data
and in the `Calendar` appsettings section rather than in `if (client == …)` code: config travels and in the `Calendar` appsettings section rather than in `if (client == …)` code: config travels
with the database, code branching has to be re-merged across ~79 branches. with the database, code branching has to be re-merged across ~79 branches.
@ -540,22 +545,19 @@ Schema/proc changes are hand-authored `.sql` scripts named `<Feature>_DB_Changes
each database **manually**. They live in two places and the distinction is the whole point: each database **manually**. They live in two places and the distinction is the whole point:
- **Repo root** — the *pending* ones. `ls *_DB_Changes.sql` shows what has not been applied yet - **Repo root** — the *pending* ones. `ls *_DB_Changes.sql` shows what has not been applied yet
(the list changes every few days — run it rather than trusting a written-down list). Write new (at the initial import there were none). Write new scripts here, in the same commit as the code
scripts here, in the same commit as the code that needs them. that needs them.
- **[`db/Script/`](db/Script)** — the archive of shipped ones. Applied scripts used to be deleted - **[`db/Script/`](db/Script)** — the archive of shipped ones (`Calendar`, `MenuIcon`,
outright; commit `c8588ce67` (2026-10-13) instead *moved* the five applied ones here `AttendanceLeaveSummaryLM`, `TaxParameterEssDeadline`, `PMS_SquareAlign_IDP`, `EmpHistoricalData`).
(`Calendar`, `MenuIcon`, `AttendanceLeaveSummaryLM`, `TaxParameterEssDeadline`, Read them for precedent — they are the best worked examples of house style — but don't re-run one
`PMS_SquareAlign_IDP`). Read them for precedent — they are the best worked examples of house style against a database that already has it.
— but don't re-run one against a database that already has it.
The convention is not enforced: `bfd085e0e` (Historical Data Upload) committed The convention was not enforced in `cel.hrm`: `EmpHistoricalData` went straight into `db/Script/`,
`EmpHistoricalData_DB_Changes.sql` straight into `db/Script/`. So the root listing is not a complete and several applied scripts were deleted instead of archived — `ScheduleEmail`, `UserEmailAddress`,
"pending" list — before deploying a branch to a database, also check `git log -- db/Script` for `HistorySalaryMonthlyAmountNull` and others. **None of those deleted scripts exist in this repo**;
scripts added since that database was last updated. It also breaks the other way: applied scripts the only copies are in `cel.hrm` history (`git log --diff-filter=D --name-only -- '*_DB_Changes.sql'`
are still sometimes deleted instead of moved (`ScheduleEmail`, `UserEmailAddress`, there). A fresh database built from this repo's scripts alone will be missing that schema, as well as
`HistorySalaryMonthlyAmountNull`, … in `ac179c03e` / `73f466cd0` / `91369150c`), so for those the only the never-scripted `MasterEmailLog` tables.
copy is git history (`git show <deleting-commit>^:<file>`) —
`git log --diff-filter=D --name-only -- '*_DB_Changes.sql'` lists them.
Every script is guarded and re-runnable (`IF COL_LENGTH(...) IS NULL`, `IF OBJECT_ID(...) IS NULL`, Every script is guarded and re-runnable (`IF COL_LENGTH(...) IS NULL`, `IF OBJECT_ID(...) IS NULL`,
`sp_rename` only when the old name is still there), documents its own run order, and states whether `sp_rename` only when the old name is still there), documents its own run order, and states whether
@ -705,8 +707,3 @@ A typical feature commit touches, in order:
6. `ClientApp/src/app/_models/<Module>/<entity>.ts` and `_services/<module>/<module>.service.ts` 6. `ClientApp/src/app/_models/<Module>/<entity>.ts` and `_services/<module>/<module>.service.ts`
7. the feature component(s) under `ClientApp/src/app/<feature>/` 7. the feature component(s) under `ClientApp/src/app/<feature>/`
8. a root `<Feature>_DB_Changes.sql` if the schema changes 8. a root `<Feature>_DB_Changes.sql` if the schema changes
## Editor rules
`.github/copilot-instructions.md` requires: for anything Azure-related, always use the Azure tools and
invoke `azmcp_bestpractices_get` first; if that tool isn't available, ask the user to enable it.

View File

@ -0,0 +1,47 @@
import { Injectable, NgZone } from '@angular/core';
import { fromEvent, merge, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class IdleService {
private isTrackingEnabled = true;
private timeout = 5 * 60 * 1000; // 5 min
constructor(private ngZone: NgZone) {}
startWatching(onTimeout: () => void) {
this.ngZone.runOutsideAngular(() => {
const events$ = merge(
fromEvent(document, 'mousemove'),
fromEvent(document, 'click'),
fromEvent(document, 'keydown'),
fromEvent(document, 'scroll')
);
events$
.pipe(
switchMap(() => timer(this.timeout))
)
.subscribe(() => {
if (this.isTrackingEnabled == false) return; //disable
this.ngZone.run(() => {
onTimeout();
});
});
});
}
stopTracking() {
this.isTrackingEnabled = false;
}
startTracking() {
this.isTrackingEnabled = true;
}
}

View File

@ -18,6 +18,7 @@ import { Subject } from 'rxjs';
import { PendingJobDTO } from 'src/app/_models/Work-Flow/pendingJobDTO'; import { PendingJobDTO } from 'src/app/_models/Work-Flow/pendingJobDTO';
import { DataPermission } from 'src/app/_models/Basic/DataPermission'; import { DataPermission } from 'src/app/_models/Basic/DataPermission';
import { BehaviorSubject } from 'rxjs'; import { BehaviorSubject } from 'rxjs';
import { IdleService } from 'src/app/_guards/idle.service';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class AuthService { export class AuthService {
@ -39,7 +40,6 @@ export class AuthService {
getIsFromSuperUser(): boolean { getIsFromSuperUser(): boolean {
return this.isFromSuperUserSubject.value; return this.isFromSuperUserSubject.value;
} }
private isFromUserSubject = new BehaviorSubject<boolean>(false); private isFromUserSubject = new BehaviorSubject<boolean>(false);
isFromUser$ = this.isFromUserSubject.asObservable(); isFromUser$ = this.isFromUserSubject.asObservable();
setIsFromUser(value: boolean) { setIsFromUser(value: boolean) {
@ -48,22 +48,29 @@ export class AuthService {
// bookmarks: Bookmark[]; // bookmarks: Bookmark[];
constructor(private http: HttpClient, constructor(private http: HttpClient,
public apiService: ApiService , public apiService: ApiService ,
public notificationService: HRMNotificationService, private router: Router) { public notificationService: HRMNotificationService, private router: Router, private idleService: IdleService) {
this.subject = new Subject<Bookmark[]>(); this.subject = new Subject<Bookmark[]>();
this.subject2 = new Subject<PendingJobDTO[]>(); this.subject2 = new Subject<PendingJobDTO[]>();
// this.loadBookmark(); // this.loadBookmark();
// console.log(this.bookmarks); // console.log(this.bookmarks);
} }
login(model: any) { login(model: any) {
return this.http.post(this.apiService.base_url + '/Authentication/login', model).pipe( return this.http.post(this.apiService.base_url + '/Authentication/login', model).pipe(
map((response: any) => { map((response: any) => {
const user = response; const user = response;
if (user) { if (user) {
// debugger; if(user.mfaRequired){
localStorage.setItem('token', user); ApiService.isMFA = true;
ApiService.AuthenticationToken = user; ApiService.AuthenticationMFASessionID = user. mfaSessionId;
// this.decodedToken = this.jwtHelper.decodeToken(ApiService.AuthenticationToken); }
else{
ApiService.isMFA = false;
ApiService.AuthenticationMFASessionID = '';
localStorage.setItem('token', user);
ApiService.AuthenticationToken = user;
//idle logout
this.idleService.stopTracking();
}
} }
}) })
); );
@ -76,43 +83,34 @@ export class AuthService {
localStorage.removeItem('pendingjobs'); localStorage.removeItem('pendingjobs');
localStorage.setItem('pendingjobs', JSON.stringify(pendingJobDTOs)); localStorage.setItem('pendingjobs', JSON.stringify(pendingJobDTOs));
} }
userPayrolltypeSwitch(param: any): any { userPayrolltypeSwitch(param: any): any {
return this.apiService.httpPost<any>('/Authentication/userPayrolltypeSwitch', param); return this.apiService.httpPost<any>('/Authentication/userPayrolltypeSwitch', param);
} }
SwtichUserMode(param: any): any { SwtichUserMode(param: any): any {
return this.apiService.httpPost<any>('/Authentication/switchuser', param); return this.apiService.httpPost<any>('/Authentication/switchuser', param);
} }
GetLogInUserType(): any { GetLogInUserType(): any {
return this.apiService.httpGet<EnumUserType>('/Authentication/GetLogInUserType'); return this.apiService.httpGet<EnumUserType>('/Authentication/GetLogInUserType');
} }
GetCurrentUser(): any { GetCurrentUser(): any {
return this.apiService.httpGet<any>('/Authentication/GetCurrentUser'); return this.apiService.httpGet<any>('/Authentication/GetCurrentUser');
} }
getUserByEmail(email: string) { getUserByEmail(email: string) {
return this.apiService.httpGet<User>('/Authentication/getUserByEmail/' + email); return this.apiService.httpGet<User>('/Authentication/getUserByEmail/' + email);
} }
GetUsers(usertype: EnumUserType, loginidid?: string, name?: string): any { GetUsers(usertype: EnumUserType, loginidid?: string, name?: string): any {
//const params = { //const params = {
// LogInID: loginid == undefined ? '' : loginid, // LogInID: loginid == undefined ? '' : loginid,
// Name: name == undefined ? '' : name, // Name: name == undefined ? '' : name,
// userType: usertype // userType: usertype
//}; //};
const nname = this.apiService.getApiDefaultData(name); const nname = this.apiService.getApiDefaultData(name);
const sloginid = this.apiService.getApiDefaultData(loginidid); const sloginid = this.apiService.getApiDefaultData(loginidid);
return this.apiService.httpGet<User[]>('/Authentication/GetUsers/' + usertype + '/' + loginidid + '/' + name); return this.apiService.httpGet<User[]>('/Authentication/GetUsers/' + usertype + '/' + loginidid + '/' + name);
} }
GetAllEmpNotYetUser() { GetAllEmpNotYetUser() {
return this.apiService.httpGet<User[]>('/Authentication/GetAllEmpNotYetUser'); return this.apiService.httpGet<User[]>('/Authentication/GetAllEmpNotYetUser');
} }
logout() { logout() {
localStorage.removeItem('forgotpass'); localStorage.removeItem('forgotpass');
localStorage.removeItem('bookmark'); localStorage.removeItem('bookmark');
@ -124,16 +122,12 @@ export class AuthService {
this.logoutSource.next(); this.logoutSource.next();
this.router.navigate(['/login']); this.router.navigate(['/login']);
} }
SaveUser(oUser: User): any { SaveUser(oUser: User): any {
return this.apiService.httpPost<User>('/Authentication/SaveUser', oUser); return this.apiService.httpPost<User>('/Authentication/SaveUser', oUser);
} }
ApproveUser(oUser: User): any { ApproveUser(oUser: User): any {
return this.apiService.httpPost<User>('/Authentication/ApproveUser', oUser); return this.apiService.httpPost<User>('/Authentication/ApproveUser', oUser);
} }
DoActiveAndIntacive(oUser: User): any { DoActiveAndIntacive(oUser: User): any {
return this.apiService.httpPost<User>('/Authentication/DoActiveAndIntacive', oUser); return this.apiService.httpPost<User>('/Authentication/DoActiveAndIntacive', oUser);
} }
@ -143,64 +137,47 @@ export class AuthService {
getBookmarks() { getBookmarks() {
return this.apiService.httpGet<Bookmark[]>('/Authentication/getBookmarks'); return this.apiService.httpGet<Bookmark[]>('/Authentication/getBookmarks');
} }
SaveBookmark(oBookmark: Bookmark): any { SaveBookmark(oBookmark: Bookmark): any {
return this.apiService.httpPost<Bookmark>('/Authentication/SaveBookmark', oBookmark); return this.apiService.httpPost<Bookmark>('/Authentication/SaveBookmark', oBookmark);
} }
deleteBookmark(param: any) { deleteBookmark(param: any) {
return this.apiService.httpPost('/Authentication/deleteBookmark', param); return this.apiService.httpPost('/Authentication/deleteBookmark', param);
} }
deleteBookmarkByMenuKey(param: any) { deleteBookmarkByMenuKey(param: any) {
return this.apiService.httpPost('/Authentication/deleteBookmarkByMenuKey', param); return this.apiService.httpPost('/Authentication/deleteBookmarkByMenuKey', param);
} }
getPendingJob(employeeId: number) { getPendingJob(employeeId: number) {
return this.apiService.httpGet<PendingJobDTO[]>('/Workflow/getPendingJob' + '/' + employeeId); return this.apiService.httpGet<PendingJobDTO[]>('/Workflow/getPendingJob' + '/' + employeeId);
} }
markNotificationsAsRead(ids: number[]) { markNotificationsAsRead(ids: number[]) {
return this.apiService.httpPost<any>('/Workflow/MarkNotificationsAsRead', ids); return this.apiService.httpPost<any>('/Workflow/MarkNotificationsAsRead', ids);
} }
loggedIn() { loggedIn() {
const token = localStorage.getItem('token'); const token = localStorage.getItem('token');
ApiService.AuthenticationToken = token; ApiService.AuthenticationToken = token;
return !this.jwtHelper.isTokenExpired(token); return !this.jwtHelper.isTokenExpired(token);
} }
register(user: User) { register(user: User) {
return this.http.post(this.baseUrl + 'register', user); return this.http.post(this.baseUrl + 'register', user);
} }
loadMenu() { loadMenu() {
return this.http.get(this.baseUrl + 'loadMenu'); return this.http.get(this.baseUrl + 'loadMenu');
} }
getAllRoles() { getAllRoles() {
return this.apiService.httpGet<RolePermission[]>('/Authentication/getAllRoles'); return this.apiService.httpGet<RolePermission[]>('/Authentication/getAllRoles');
} }
getRole(roleID: number) { getRole(roleID: number) {
return this.apiService.httpGet<RolePermission[]>('/Authentication/getRole/' + roleID); return this.apiService.httpGet<RolePermission[]>('/Authentication/getRole/' + roleID);
} }
getMenuesFromConfig() { getMenuesFromConfig() {
return this.apiService.httpGet<RolePermission[]>('/Authentication/getMenuesFromConfig'); return this.apiService.httpGet<RolePermission[]>('/Authentication/getMenuesFromConfig');
} }
saveRole(params: Role) { saveRole(params: Role) {
return this.apiService.httpPost<number>('/Authentication/saveRole', params); return this.apiService.httpPost<number>('/Authentication/saveRole', params);
} }
GetRolePermissionbyUserID() { GetRolePermissionbyUserID() {
return this.apiService.httpGet<any>('/Authentication/GetRolePermissionbyUserID'); return this.apiService.httpGet<any>('/Authentication/GetRolePermissionbyUserID');
} }
getUserRoles(roletype: EnumRoleType, userID?: number, roleid?: number) { getUserRoles(roletype: EnumRoleType, userID?: number, roleid?: number) {
const nuserid = this.apiService.getApiDefaultIntData(userID); const nuserid = this.apiService.getApiDefaultIntData(userID);
@ -209,66 +186,51 @@ export class AuthService {
return this.apiService.httpGet<UserRole[]>('/Authentication/getUserRoles/' + roletype + '/' return this.apiService.httpGet<UserRole[]>('/Authentication/getUserRoles/' + roletype + '/'
+ nuserid + '/' + nroletype); + nuserid + '/' + nroletype);
} }
GetEmpUserRole(searchemps: SearchEmployee[]) { GetEmpUserRole(searchemps: SearchEmployee[]) {
return this.apiService.httpPost<UserRole[]>('/Authentication/GetEmpUserRole', searchemps); return this.apiService.httpPost<UserRole[]>('/Authentication/GetEmpUserRole', searchemps);
} }
saveUserRole(params: any) { saveUserRole(params: any) {
return this.apiService.httpPost<number>('/Authentication/saveUserRole', params); return this.apiService.httpPost<number>('/Authentication/saveUserRole', params);
} }
GetAllPayrollTypes() { GetAllPayrollTypes() {
return this.apiService.httpGet<PayrollType[]>('/Authentication/GetAllPayrollTypes'); return this.apiService.httpGet<PayrollType[]>('/Authentication/GetAllPayrollTypes');
} }
GetPayrollTypesByLoginID(loginID: string) { GetPayrollTypesByLoginID(loginID: string) {
return this.apiService.httpGet<PayrollType[]>('/Authentication/GetPayrollTypesByLoginID/' + loginID); return this.apiService.httpGet<PayrollType[]>('/Authentication/GetPayrollTypesByLoginID/' + loginID);
} }
GetBenifitsProcessStatus() { GetBenifitsProcessStatus() {
return this.apiService.httpGet<PayrollType[]>('/Authentication/GetBenifitsProcessStatus' ); return this.apiService.httpGet<PayrollType[]>('/Authentication/GetBenifitsProcessStatus' );
} }
getSwitchUserId(usertype: EnumUserType) { getSwitchUserId(usertype: EnumUserType) {
return this.apiService.httpGet<any>('/Authentication/getSwitchUserId/'+ usertype); return this.apiService.httpGet<any>('/Authentication/getSwitchUserId/'+ usertype);
} }
GetPayrollTypeByLoginID() { GetPayrollTypeByLoginID() {
return this.apiService.httpGet<PayrollType>('/Authentication/GetPayrollTypeByLoginID'); return this.apiService.httpGet<PayrollType>('/Authentication/GetPayrollTypeByLoginID');
} }
getAdminPayrollTypes() { getAdminPayrollTypes() {
return this.apiService.httpGet<PayrollType[]>('/Authentication/getAdminPayrollTypes'); return this.apiService.httpGet<PayrollType[]>('/Authentication/getAdminPayrollTypes');
} }
GetUserAccessType(userid: number) { GetUserAccessType(userid: number) {
return this.apiService.httpGet<UserAccessType[]>('/Authentication/GetUserAccessType/' + userid); return this.apiService.httpGet<UserAccessType[]>('/Authentication/GetUserAccessType/' + userid);
} }
SaveUserAccessType(acesssTypes: UserAccessType[]) { SaveUserAccessType(acesssTypes: UserAccessType[]) {
return this.apiService.httpPost<boolean>('/Authentication/SaveUserAccessType', acesssTypes); return this.apiService.httpPost<boolean>('/Authentication/SaveUserAccessType', acesssTypes);
} }
changePassword(userData: any) { changePassword(userData: any) {
return this.apiService.httpPost<any>('/Authentication/changePassword', userData); return this.apiService.httpPost<any>('/Authentication/changePassword', userData);
} }
changePasswordbyAdmin(userData: any) { changePasswordbyAdmin(userData: any) {
return this.apiService.httpPost<any>('/Authentication/changePasswordbyAdmin', userData); return this.apiService.httpPost<any>('/Authentication/changePasswordbyAdmin', userData);
} }
forgotPassword(data: any) { forgotPassword(data: any) {
return this.apiService.httpPost<any>('/Authentication/forgotPassword', data); return this.apiService.httpPost<any>('/Authentication/forgotPassword', data);
} }
getVersionNumber() { getVersionNumber() {
return this.apiService.httpGet<string>('/Authentication/getVersionNumber'); return this.apiService.httpGet<string>('/Authentication/getVersionNumber');
} }
GetUserByLoingID(loginid: string, systemType: EnumSystemType) { GetUserByLoingID(loginid: string, systemType: EnumSystemType) {
return this.apiService.httpGet<User>('/Authentication/GetUserByLoingID/' + loginid + '/' + systemType); return this.apiService.httpGet<User>('/Authentication/GetUserByLoingID/' + loginid + '/' + systemType);
} }
@ -279,19 +241,15 @@ export class AuthService {
getUserByUserType(param: any): any { getUserByUserType(param: any): any {
return this.apiService.httpPost<any>('/Authentication/getUserByUserType', param); return this.apiService.httpPost<any>('/Authentication/getUserByUserType', param);
} }
addPermission(param: any) { addPermission(param: any) {
return this.apiService.httpPost<any>('/Authentication/addPermission', param); return this.apiService.httpPost<any>('/Authentication/addPermission', param);
} }
loadDataPermission(userid: number, payrolltypeid:number) { loadDataPermission(userid: number, payrolltypeid:number) {
return this.apiService.httpGet<DataPermission[]>('/Authentication/loadDataPermission/' + userid + "/" + payrolltypeid); return this.apiService.httpGet<DataPermission[]>('/Authentication/loadDataPermission/' + userid + "/" + payrolltypeid);
} }
DeletedataPermission(item:any) { DeletedataPermission(item:any) {
return this.apiService.httpPost<any> ('/Authentication/deletePermission' ,item); return this.apiService.httpPost<any> ('/Authentication/deletePermission' ,item);
} }
getSSOStatus() { getSSOStatus() {
return this.apiService.httpGet<any>('/Authentication/getSSOStatus'); return this.apiService.httpGet<any>('/Authentication/getSSOStatus');
} }
@ -302,4 +260,26 @@ export class AuthService {
const fmt = (d: Date) => d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2); const fmt = (d: Date) => d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
return this.apiService.httpGet<PayrollType[]>('/Authentication/SetExpectedSalaryandApprovalDate'+ '/' + fmt(expectedDate) + '/' + fmt(expectedApprovalDate)); return this.apiService.httpGet<PayrollType[]>('/Authentication/SetExpectedSalaryandApprovalDate'+ '/' + fmt(expectedDate) + '/' + fmt(expectedApprovalDate));
} }
VerifyMfa(model: any) {
return this.http.post(this.apiService.base_url + '/Authentication/verify-mfa', model).pipe(
map((response: any) => {
const user = response;
localStorage.setItem('token', user.userToken);
ApiService.AuthenticationToken = user.userToken;
})
);
}
ResendOTP(model: any): any {
return this.http.post(this.apiService.base_url + '/Authentication/resend-otp', model).pipe(
map((response: any) => {
const user = response;
if (user) {
if(user.mfaRequired){
ApiService.isMFA = true;
ApiService.AuthenticationMFASessionID = user. mfaSessionId;
}
}
})
);
}
} }

View File

@ -14,6 +14,8 @@ import { environment } from '../environments/environment';
export class ApiService { export class ApiService {
public isSSO = false; public isSSO = false;
public static isMFA : boolean = false;
public isADLogin = false;
public versionDeployement = false; public versionDeployement = false;
public versionNumber = "20261012-01"; public versionNumber = "20261012-01";
public static BASE_URL = ''; public static BASE_URL = '';
@ -24,6 +26,7 @@ export class ApiService {
public static PAYROLLTYPEID: number = 0; public static PAYROLLTYPEID: number = 0;
public static USERTYPE: number = 0; public static USERTYPE: number = 0;
public isSelService : boolean = true; public isSelService : boolean = true;
public static MFACode: string = undefined;
public isSelServiceFullScreen : boolean = false; public isSelServiceFullScreen : boolean = false;
public isNewDaswhboard : boolean = true; public isNewDaswhboard : boolean = true;
public menuItems: any[] = []; public menuItems: any[] = [];
@ -36,6 +39,7 @@ export class ApiService {
public static AuthenticationToken = ''; public static AuthenticationToken = '';
public static readonly DEFAULT_PHOTO = './assets/photos/profile-default.jpg'; public static readonly DEFAULT_PHOTO = './assets/photos/profile-default.jpg';
public selectedMenuName: string = ''; public selectedMenuName: string = '';
public static AuthenticationMFASessionID = '';
constructor(public httpClient: HttpClient, public datepipe: DatePipe) { constructor(public httpClient: HttpClient, public datepipe: DatePipe) {
if (!ApiService.AuthenticationToken) { if (!ApiService.AuthenticationToken) {

View File

@ -15,8 +15,6 @@
@if (!apiService.isSSO) { @if (!apiService.isSSO) {
<div class="login-content" style="margin-top: 100px;"> <div class="login-content" style="margin-top: 100px;">
<img src="assets/layout/images/banner.png" alt="Banner" [style.width]="bannerWidth" [style.height]="bannerHeight"/> <img src="assets/layout/images/banner.png" alt="Banner" [style.width]="bannerWidth" [style.height]="bannerHeight"/>
<!-- <img src="assets/layout/images/banner.png" width="350" height="230" alt="Banner"/> -->
<!-- <h1><span>SIGN IN</span> HRM</h1> -->
<p style="color: rgb(177, 177, 177); font-weight: bolder;">Welcome, please use the form to sign-in.</p> <p style="color: rgb(177, 177, 177); font-weight: bolder;">Welcome, please use the form to sign-in.</p>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()"> <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div class="login-input-wrapper"> <div class="login-input-wrapper">
@ -70,6 +68,4 @@
</kendo-dialog> </kendo-dialog>
} }
</body> </body>
</html> </html>

View File

@ -1,4 +1,4 @@
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; import { Component, ElementRef, OnInit, ChangeDetectionStrategy, QueryList, ViewChildren } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthGuard } from './_guards/auth.guard'; import { AuthGuard } from './_guards/auth.guard';
@ -46,7 +46,6 @@ export class LoginComponent implements OnInit {
versionNumber: string; versionNumber: string;
showModal = false; showModal = false;
bookmarks: Bookmark[] = []; bookmarks: Bookmark[] = [];
/* _wfmovementTrans: PendingJobDTO[] = [];*/
currentUser: User; currentUser: User;
emailAddress = ''; emailAddress = '';
bannerHeight = '200px'; bannerHeight = '200px';
@ -66,12 +65,6 @@ export class LoginComponent implements OnInit {
private authService: MsalService, public appMain : AppMainComponent, private authService: MsalService, public appMain : AppMainComponent,
private versionCheck: VersionCheckService private versionCheck: VersionCheckService
) { ) {
// Redirect to home if already logged in -- but only when the app actually started on
// the login page. This component sits in app-main's template behind [hidden], not
// *ngIf, so its constructor runs once at bootstrap on EVERY route. Redirecting
// unconditionally fires before the router's initial navigation and throws away
// whatever URL the user opened, landing them on '/' (and from there on
// /ess/landing-page or /ess/self-dashboard via DashboardDemoComponent).
if (ApiService.AuthenticationToken && window.location.hash.indexOf('/login') > -1) { if (ApiService.AuthenticationToken && window.location.hash.indexOf('/login') > -1) {
this.router.navigate(['/']); this.router.navigate(['/']);
} }
@ -85,47 +78,50 @@ export class LoginComponent implements OnInit {
nmgtLink : any; nmgtLink : any;
currentLink : any; currentLink : any;
loadFirst : boolean; loadFirst : boolean;
showMfaModal = false;
mfaCode : string = undefined;
otpIndexes = [0, 1, 2, 3, 4, 5];
@ViewChildren('otpBox') otpBoxes: QueryList<ElementRef<HTMLInputElement>>;
timerValue: string = undefined;
private secondsLeft = undefined;
intervalId: any;
isResend:boolean = false;
isResendCode:boolean = false;
mFATimer : number = 0;
ngOnInit() { ngOnInit() {
// const x = window.location.href; // const x = window.location.href;
// this.currentLink = window.location.href.split('/').pop(); // this.currentLink = window.location.href.split('/').pop();
this.apiService.isADLogin = false;
ApiService.isMFA = false;
this.mFATimer = 2;
this.nmgtLink = null;
this.loadingPanel.ShowLoadingPanel = true; this.loadingPanel.ShowLoadingPanel = true;
this.userService.getSSOStatus().subscribe( this.userService.getSSOStatus().subscribe(
(resp) => { (resp) => {
// debugger;
this.ssoDT = resp; this.ssoDT = resp;
this.apiService.isSSO = this.ssoDT[0].isSSO; this.apiService.isSSO = this.ssoDT[0].isSSO;
this.apiService.isNewDaswhboard = this.ssoDT[0].isNewDashboard; this.apiService.isNewDaswhboard = this.ssoDT[0].isNewDashboard;
this.nmgtLink = this.ssoDT[0].nmgtLink; this.nmgtLink = this.ssoDT[0].nmgtLink;
ApiService.isMFA = this.ssoDT[0].isMFA;
this.mFATimer = this.ssoDT[0].mfaTimer;
}, },
(x) => { (x) => {
this.loadingPanel.ShowLoadingPanel = false; this.loadingPanel.ShowLoadingPanel = false;
}, },
() => { () => {
this.loadingPanel.ShowLoadingPanel = false; this.loadingPanel.ShowLoadingPanel = false;
// if(this.apiService.currentLink === this.nmgtLink){
// this.apiService.isSSO = false;
// }
// debugger;
if (this.apiService.isSSO === true) { if (this.apiService.isSSO === true) {
this.msalBroadcastService.msalSubject$ this.msalBroadcastService.msalSubject$
.pipe( .pipe(filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),)
filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS), .subscribe((result: EventMessage) => {});
)
.subscribe((result: EventMessage) => {
console.log('My Credential is following');
console.log(result);
});
this.msalBroadcastService.inProgress$ this.msalBroadcastService.inProgress$
.pipe( .pipe(filter((status: InteractionStatus) => status === InteractionStatus.None))
filter((status: InteractionStatus) => status === InteractionStatus.None) .subscribe(() => {this.setLoginDisplay();});
)
.subscribe(() => {
this.setLoginDisplay();
});
} }
}); });
this.showModal = false; this.showModal = false;
this.loginForm = this.formBuilder.group({ this.loginForm = this.formBuilder.group({
username: ['', Validators.required], username: ['', Validators.required],
@ -133,9 +129,7 @@ export class LoginComponent implements OnInit {
payrolltypeid: [''], payrolltypeid: [''],
}); });
this.payrollTypes = []; this.payrollTypes = [];
// this.versionNumber = 'v-20240109-01';
this.versionNumber = 'v-' + GlobalfunctionExtension.generateVersionNumber(new Date(2024, 4, 28)) + '-01'; this.versionNumber = 'v-' + GlobalfunctionExtension.generateVersionNumber(new Date(2024, 4, 28)) + '-01';
//// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
} }
public payrollTypesImg = [ public payrollTypesImg = [
@ -162,18 +156,11 @@ export class LoginComponent implements OnInit {
this.authService.loginRedirect(); this.authService.loginRedirect();
} }
} }
// convenience getter for easy access to form fields
get f() { get f() {
return this.loginForm.controls; return this.loginForm.controls;
} }
onFocusOutEvent(event: any) { onFocusOutEvent(event: any) {
} }
GetPayrollTypeByLoginID() { GetPayrollTypeByLoginID() {
this.selectedPayrollTypeID = null; this.selectedPayrollTypeID = null;
this.payrollTypes = []; this.payrollTypes = [];
@ -181,7 +168,6 @@ export class LoginComponent implements OnInit {
return; return;
} }
this.loadingPanel.ShowLoadingPanel = true; this.loadingPanel.ShowLoadingPanel = true;
// Assuming GetPayrollTypesByLoginID is an observable returning payroll types based on the username
this.userService.GetPayrollTypesByLoginID(this.f['username'].value).subscribe( this.userService.GetPayrollTypesByLoginID(this.f['username'].value).subscribe(
(resp: any) => { (resp: any) => {
this.payrollTypes = resp; this.payrollTypes = resp;
@ -195,8 +181,6 @@ export class LoginComponent implements OnInit {
if (this.payrollTypes !== undefined && this.payrollTypes.length > 1) { if (this.payrollTypes !== undefined && this.payrollTypes.length > 1) {
const validItem = []; const validItem = [];
validItem.push(Validators.required); validItem.push(Validators.required);
// this.loginForm.controls['payrolltypeid'].setValidators(validItem);
// this.loginForm.controls['payrolltypeid'].updateValueAndValidity();
} }
if (this.payrollTypes !== undefined && this.payrollTypes.length === 1) { if (this.payrollTypes !== undefined && this.payrollTypes.length === 1) {
this.selectedPayrollTypeID = this.payrollTypes[0].id; this.selectedPayrollTypeID = this.payrollTypes[0].id;
@ -208,61 +192,22 @@ export class LoginComponent implements OnInit {
} }
} }
); );
// this.userService.GetPayrollTypesByLoginID(this.f['username'].subscribe(
// (resp: any) => {
// this.payrollTypes = resp;
// },
// (err: any) => {
// this.loadingPanel.ShowLoadingPanel = false;
// this.notificationService.showError(err.error);
// },
// () => {
// this.loadingPanel.ShowLoadingPanel = false;
// if (this.payrollTypes !== undefined && this.payrollTypes.length > 1) {
// const validItem = [];
// validItem.push(Validators.required);
// // this.loginForm.controls['payrolltypeid'].setValidators(validItem);
// // this.loginForm.controls['payrolltypeid'].updateValueAndValidity();
// }
// if (this.payrollTypes !== undefined && this.payrollTypes.length === 1) {
// this.selectedPayrollTypeID = this.payrollTypes[0].id;
// this.Login();
// } else if (this.payrollTypes !== undefined && this.payrollTypes.length > 1) {
// this.showModal = true;
// } else {
// this.Login();
// }
// }
// );
} }
onPopUpClose() { onPopUpClose() {
this.showModal = false; this.showModal = false;
} }
forgetPassword() { forgetPassword() {
localStorage.setItem('forgotpass', JSON.stringify(true)); localStorage.setItem('forgotpass', JSON.stringify(true));
localStorage.removeItem('token'); localStorage.removeItem('token');
localStorage.removeItem('menuList'); localStorage.removeItem('menuList');
// this.router.navigate(['/forgot-password']);
// this.router.navigateByUrl('/forgot-password');
// this.router.navigate(['/forgot-password']);
} }
onSubmit() { onSubmit() {
debugger;
if (this.apiService.isSSO) { if (this.apiService.isSSO) {
this.authService.loginRedirect(); this.authService.loginRedirect();
console.log('redirect');
} else { } else {
this.GetPayrollTypeByLoginID(); this.GetPayrollTypeByLoginID();
} }
} }
private Login() { private Login() {
let params: any; let params: any;
if (this.apiService.isSSO === true) { if (this.apiService.isSSO === true) {
@ -274,7 +219,6 @@ export class LoginComponent implements OnInit {
email: this.emailAddress, email: this.emailAddress,
isSSO: true isSSO: true
}; };
console.log(params);
} else { } else {
let nextPayrollProcessDate; let nextPayrollProcessDate;
this.submitted = true; this.submitted = true;
@ -285,7 +229,6 @@ export class LoginComponent implements OnInit {
this.notificationService.showError('Please select a Access-Type'); this.notificationService.showError('Please select a Access-Type');
return; return;
} }
if (this.selectedPayrollTypeID != undefined && this.selectedPayrollTypeID != null) { if (this.selectedPayrollTypeID != undefined && this.selectedPayrollTypeID != null) {
nextPayrollProcessDate = this.payrollTypes.find(x => x.id == this.selectedPayrollTypeID).nextPayProcessDate; nextPayrollProcessDate = this.payrollTypes.find(x => x.id == this.selectedPayrollTypeID).nextPayProcessDate;
} }
@ -305,54 +248,75 @@ export class LoginComponent implements OnInit {
this.loading = false; this.loading = false;
}, },
(err: any) => { (err: any) => {
console.log(err);
if(this.apiService.isSSO === true){ if(this.apiService.isSSO === true){
this.notificationService.showError('User not found'); this.notificationService.showError('User not found');
} }
else{ else{
this.notificationService.showError('Invalid Login-ID or Password'); if(err.status === 429){
this.notificationService.showError(err.error.message);
}
else if(this.apiService.isADLogin === true){
this.notificationService.showError(err.error);
}
else{
this.notificationService.showError('Invalid Login-ID or Password');
}
} }
this.loadingPanel.ShowLoadingPanel = false; this.loadingPanel.ShowLoadingPanel = false;
}, },
() => { () => {
const jwtHelper = new JwtHelperService(); const jwtHelper = new JwtHelperService();
//Remove Pending Job if(ApiService.isMFA == true){
// this.userService.subject2.next(this._wfmovementTrans);
const user = jwtHelper.decodeToken(localStorage.getItem('token'));
ApiService.PAYROLLTYPEID = parseInt(user.PayrollTypeID,10);
ApiService.USERTYPE = parseInt(user.UserType,10);
if (user.ChangePasswordAtNextLogon === 'True') {
localStorage.removeItem('menuList');
this.auth.menuEvent.emit(false);
this.loadingPanel.ShowLoadingPanel = false; this.loadingPanel.ShowLoadingPanel = false;
this.router.navigate(['/authentication/change-password']); this.loading = false;
} else { this.showModal = false;
this.userService.GetRolePermissionbyUserID().subscribe( this.showMfaModal = true;
(menu: any) => { this.mfaCode = '';
localStorage.setItem('menuList', JSON.stringify(menu)); localStorage.removeItem('token');
this.router.navigate(['/']); localStorage.removeItem('menuList');
}, this.startTimer();
(errmenu: any) => { }else{
this.notificationService.showError(errmenu.error); const user = jwtHelper.decodeToken(localStorage.getItem('token'));
ApiService.PAYROLLTYPEID = parseInt(user.PayrollTypeID,10);
ApiService.USERTYPE = parseInt(user.UserType,10);
if(!this.apiService.isSSO){
if (user.ChangePasswordAtNextLogon === 'True') {
localStorage.removeItem('menuList');
this.auth.menuEvent.emit(false);
this.loadingPanel.ShowLoadingPanel = false; this.loadingPanel.ShowLoadingPanel = false;
}, this.router.navigate(['/authentication/change-password']);
() => {
this.loadingPanel.ShowLoadingPanel = false;
this.appMain.IsSelfService();
this.loadBookmark();
this.auth.menuEvent.emit(true);
} }
); else{
this.getMenu();
}
}
else{
this.getMenu();
}
} }
this.showModal = false; this.showModal = false;
} }
); );
} }
getMenu(){
this.loadingPanel.ShowLoadingPanel = true;
this.userService.GetRolePermissionbyUserID().subscribe(
(menu: any) => {
localStorage.setItem('menuList', JSON.stringify(menu));
this.router.navigate(['/']);
},
(errmenu: any) => {
this.notificationService.showError(errmenu.error);
this.loadingPanel.ShowLoadingPanel = false;
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
this.appMain.IsSelfService();
this.loadBookmark();
this.auth.menuEvent.emit(true);
}
);
}
loadBookmark() { loadBookmark() {
this.userService.getBookmarks() this.userService.getBookmarks()
.subscribe( .subscribe(
@ -379,23 +343,143 @@ export class LoginComponent implements OnInit {
menu = [...menu, ...flatMenu];*/ menu = [...menu, ...flatMenu];*/
}); });
} }
//loadPendingJobs() {
// this.wfService.getPendingJob(0).subscribe(
// (resp) => {
// this._wfmovementTrans = resp;
// },
// () => {
// },
// () => {
// localStorage.setItem('pendingjobs', JSON.stringify(this._wfmovementTrans));
// this.authService.subject2.next(this._wfmovementTrans);
// },
// );
//}
onForgotPassword() { onForgotPassword() {
localStorage.removeItem('token'); localStorage.removeItem('token');
this.router.navigate(['/forgot-password']); this.router.navigate(['/forgot-password']);
} }
onPopUpOTPClose(){
this.showMfaModal = false;
this.ngOnInit();
}
private syncMfaCode(): void {
if (!this.otpBoxes) { return; }
this.mfaCode = this.otpBoxes.map(b => b.nativeElement.value || '').join('');
}
onOtpInput(event: Event, index: number): void {
const input = event.target as HTMLInputElement;
const digit = (input.value || '').replace(/\D/g, '').slice(-1);
input.value = digit;
this.syncMfaCode();
if (digit && index < 5) {
this.otpBoxes.get(index + 1)?.nativeElement.focus();
}
}
onOtpKeydown(event: KeyboardEvent, index: number): void {
const input = event.target as HTMLInputElement;
if (event.key === 'Backspace') {
if (!input.value && index > 0) {
const prev = this.otpBoxes.get(index - 1)?.nativeElement;
if (prev) {
prev.value = '';
prev.focus();
}
event.preventDefault();
}
setTimeout(() => this.syncMfaCode());
} else if (event.key === 'ArrowLeft' && index > 0) {
this.otpBoxes.get(index - 1)?.nativeElement.focus();
event.preventDefault();
} else if (event.key === 'ArrowRight' && index < 5) {
this.otpBoxes.get(index + 1)?.nativeElement.focus();
event.preventDefault();
}
}
onOtpPaste(event: ClipboardEvent): void {
event.preventDefault();
const text = (event.clipboardData?.getData('text') || '').replace(/\D/g, '').slice(0, 6);
if (!text) { return; }
const boxes = this.otpBoxes.toArray();
boxes.forEach((b, i) => b.nativeElement.value = text[i] || '');
this.syncMfaCode();
boxes[Math.min(text.length, 5)]?.nativeElement.focus();
}
validateOTP(){
if(this.secondsLeft > 0 && this.secondsLeft < 120){
this.loadingPanel.ShowLoadingPanel = true;
if(this.mfaCode === undefined || this.mfaCode === null || this.mfaCode.trim() === ''){
this.notificationService.showError('Please enter the MFA Code');
return;
}
let params = {
mfaSessionId : ApiService.AuthenticationMFASessionID,
mfaCode : this.mfaCode
};
this.userService.VerifyMfa(params).subscribe(
(resp: any) => {
this.loading = false;
this.showMfaModal = false;
},
(err: any) => {
this.notificationService.showError(err.error);
this.showMfaModal = false;
this.loadingPanel.ShowLoadingPanel = false;
},
() => {
this.showModal = false;
this.loading = false;
this.showMfaModal = false;
this.getMenu();
}
);
}
else{
this.isResend = true;
this.notificationService.showError('Time is Expired. Please Resend Code')
}
}
reSendOTP(){
var code = undefined;
let params = {
mfaSessionId : ApiService.AuthenticationMFASessionID,
mfaCode : null
};
this.loadingPanel.ShowLoadingPanel = true;
this.userService.ResendOTP(params).subscribe(
(resp: any) => {
code = resp;
},
(err: any) => {
this.loadingPanel.ShowLoadingPanel = false;
},
() => {
this.isResend = false;
this.loadingPanel.ShowLoadingPanel = false;
//if(code != undefined) ApiService.MFACode = code;
this.startTimer();
}
);
}
startTimer() {
this.timerValue = '02:00';
this.secondsLeft = 120;
if(this.mFATimer && this.mFATimer > 0){
this.secondsLeft = Math.floor(this.mFATimer * 60);
const minutes = Math.floor(this.mFATimer);
const seconds = Math.round((this.mFATimer - minutes) * 60);
const minuteStr = minutes.toString().padStart(2, '0');
const secondStr = seconds.toString().padStart(2, '0');
this.timerValue = `${minuteStr}:${secondStr}`;
}
// clear
if (this.intervalId) {
clearInterval(this.intervalId);
}
// start
this.intervalId = setInterval(() => {
if (this.secondsLeft > 0) {
this.secondsLeft--;
this.isResend = false;
const minute = Math.floor(this.secondsLeft / 60).toString().padStart(2, '0');
const second = (this.secondsLeft % 60).toString().padStart(2, '0');
this.timerValue = `${minute}:${second}`;
if(this.secondsLeft === 0){
this.isResend = true;
ApiService.MFACode = undefined;
clearInterval(this.intervalId);
}
} else {
clearInterval(this.intervalId); // stop when 0
}
}, 1000);
}
} }

View File

@ -389,9 +389,9 @@ namespace HRM.UI.Controllers
return BadRequest("Login ID/Password is invalid"); return BadRequest("Login ID/Password is invalid");
} }
} }
//string userToken = this.CreateToten(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate);
string userToken = this.CreateToten(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate); string userToken = this.CreateTokenNew(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate, mfaCode);
return Ok(userToken); return Ok(userToken);
} }
public string CreateToten(User userFromRepo, int? payrolltypeid, DateTime? nextPayProcessDate) public string CreateToten(User userFromRepo, int? payrolltypeid, DateTime? nextPayProcessDate)
@ -464,20 +464,14 @@ namespace HRM.UI.Controllers
new Claim("nextPayProcessDate", (payrolltypeid == null) ? "null" : payrollType.NextPayProcessDate.ToString()), new Claim("nextPayProcessDate", (payrolltypeid == null) ? "null" : payrollType.NextPayProcessDate.ToString()),
}; };
// Add role claims claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
claims.AddRange(
roles.Select(role => new Claim(ClaimTypes.Role, role))
);
var key = Encoding.ASCII.GetBytes(_jwt.Secret); var key = Encoding.ASCII.GetBytes(_jwt.Secret);
var token = new JwtSecurityToken( var token = new JwtSecurityToken(
issuer: _jwt.Issuer, issuer: _jwt.Issuer,
audience: _jwt.Audience, audience: _jwt.Audience,
claims: claims, claims: claims,
expires: DateTime.UtcNow.AddMinutes(_jwt.TokenLifetimeMinutes), expires: DateTime.UtcNow.AddMinutes(_jwt.TokenLifetimeMinutes),
signingCredentials: new SigningCredentials( signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256
)
); );
string userToken = new JwtSecurityTokenHandler().WriteToken(token); string userToken = new JwtSecurityTokenHandler().WriteToken(token);
if (!string.IsNullOrEmpty(userToken)) if (!string.IsNullOrEmpty(userToken))
@ -549,7 +543,6 @@ namespace HRM.UI.Controllers
} }
break; break;
} }
return roles.Distinct().ToList(); return roles.Distinct().ToList();
} }
public string processMFA() public string processMFA()
@ -670,6 +663,100 @@ namespace HRM.UI.Controllers
} }
} }
[HttpPost("verify-mfa")]
[EnableRateLimiting("MfaPolicy")]
[AllowAnonymous]
public IActionResult VerifyMfa([FromBody] VerifyMfaDto dto)
{
var key = $"MFA_{dto.MfaSessionId}";
var challenge = _cache.Get<MfaChallenge>(key);
if (challenge == null)
return Unauthorized("OTP expired or invalid");
if (challenge.ExpiredAt < DateTime.Now)
{
_cache.Remove(key);
return Unauthorized("OTP expired");
}
if (dto.mfaCode != challenge.OTP)
{
challenge.AttemptCount++;
_cache.Set(key, challenge, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = challenge.ExpiredAt - DateTime.UtcNow
});
return Unauthorized("Invalid OTP");
}
_cache.Remove(key);
User userFromRepo = _userService.Get(challenge.UserId);
int payrolltypeID = 0;
DateTime nextProcessDate = DateTime.Now;
if (userFromRepo != null)
{
List<PayrollType> payrollTypes = new List<PayrollType>();
payrollTypes = this._payrollTypeService.GetPayrollTypes(userFromRepo.LoginID);
if (payrollTypes != null && payrollTypes.Count > 0)
{
nextProcessDate = payrollTypes[0].NextPayProcessDate;
payrolltypeID = payrollTypes[0].ID;
}
}
string userToken = this.CreateTokenNew(userFromRepo, payrolltypeID, nextProcessDate, "");
return Ok(new { userToken });
}
[HttpPost("resend-otp")]
[EnableRateLimiting("ResendOtpPolicy")]
[AllowAnonymous]
public ActionResult GetOTP([FromBody] VerifyMfaDto dto)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
IConfiguration Configuration = builder.Build();
decimal mFATimer = Convert.ToDecimal(Configuration.GetSection("LDAPSettings")["MFATimer"]);
string time = DateTime.Now.AddMinutes((double)mFATimer).ToString("hh:mm tt");
string mfaCode = null;
try
{
var key = $"MFA_{dto.MfaSessionId}";
var challenge = _cache.Get<MfaChallenge>(key);
if (challenge == null)
return Unauthorized("OTP expired or invalid");
_cache.Remove(key);
User userFromRepo = _userService.Get(challenge.UserId);
int ID = userFromRepo.ID;
mfaCode = this.processMFA();
var mfaSessionId = Guid.NewGuid().ToString();
decimal minutes = mFATimer > 0 ? mFATimer : 2.0m;
TimeSpan otpValidity = TimeSpan.FromSeconds((double)(minutes * 60));
_cache.Remove($"MFA_{mfaSessionId}");
var newChallenge = new MfaChallenge
{
UserId = ID,
OTP = mfaCode,
CreatedAt = DateTime.Now,
ExpiredAt = DateTime.Now.Add(otpValidity),
AttemptCount = 0
};
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = otpValidity,
Priority = CacheItemPriority.High
};
_cache.Set($"MFA_{mfaSessionId}", newChallenge, cacheOptions);
SendMfaCode(mfaCode, time, userFromRepo);
return Ok(new
{
mfaRequired = true,
mfaSessionId = mfaSessionId,
});
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
[HttpPost("userPayrolltypeSwitch")] [HttpPost("userPayrolltypeSwitch")]
public ActionResult userPayrolltypeSwitch(dynamic data) public ActionResult userPayrolltypeSwitch(dynamic data)
{ {
@ -1621,21 +1708,27 @@ namespace HRM.UI.Controllers
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json"); var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
EmailSettings emailSettings = new EmailSettings(); EmailSettings emailSettings = new EmailSettings();
IConfiguration Configuration = builder.Build(); IConfiguration Configuration = builder.Build();
Configuration.GetSection("EmailSettings").Bind(emailSettings); //Configuration.GetSection("EmailSettings").Bind(emailSettings);
string isSSO = Configuration.GetSection("EmailSettings")["isSSO"]; string isSSO = Configuration.GetSection("EmailSettings")["isSSO"];
string isNewDashboard = Configuration.GetSection("EmailSettings")["isNewDashboard"]; string isNewDashboard = Configuration.GetSection("EmailSettings")["isNewDashboard"];
string nmgtLink = Configuration.GetSection("EmailSettings")["nmgtLink"]; string nmgtLink = Configuration.GetSection("EmailSettings")["nmgtLink"];
string isMFA = Configuration.GetSection("LDAPSettings")["isMFA"];
string mfaTimer = Configuration.GetSection("LDAPSettings")["MFATimer"];
DataTable dt = new DataTable(); DataTable dt = new DataTable();
dt.Columns.Add("isSSO", typeof(bool)); dt.Columns.Add("isSSO", typeof(bool));
dt.Columns.Add("nmgtLink", typeof(string)); dt.Columns.Add("nmgtLink", typeof(string));
dt.Columns.Add("isNewDashboard", typeof(bool)); dt.Columns.Add("isNewDashboard", typeof(bool));
dt.Columns.Add("isMFA", typeof(bool));
dt.Columns.Add("mfaTimer", typeof(int));
dt.TableName = "SSO"; dt.TableName = "SSO";
DataRow row = dt.NewRow(); DataRow row = dt.NewRow();
row["isSSO"] = isSSO == "true" ? true : false; row["isSSO"] = isSSO == "true" ? true : false;
row["isNewDashboard"] = isNewDashboard == "false" ? false : true; row["isNewDashboard"] = isNewDashboard == "false" ? false : true;
row["nmgtLink"] = nmgtLink; row["nmgtLink"] = nmgtLink;
row["isMFA"] = isMFA == "true" ? true : false;
row["mfaTimer"] = int.Parse(mfaTimer);
dt.Rows.Add(row); dt.Rows.Add(row);
return Ok(dt); return Ok(dt);

View File

@ -33,7 +33,8 @@ namespace HRM.UI.Api
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly AppSettings _appSettings; private readonly AppSettings _appSettings;
public IConfiguration Configuration { get; } private readonly JwtSettings _jwt;
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment env, ILogger<Startup> logger) public Startup(IConfiguration configuration, IWebHostEnvironment env, ILogger<Startup> logger)
{ {
@ -42,7 +43,8 @@ namespace HRM.UI.Api
Configuration = configuration; Configuration = configuration;
_appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>(); _appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
} _jwt = Configuration.GetSection("Jwt").Get<JwtSettings>();
}
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
@ -78,11 +80,15 @@ namespace HRM.UI.Api
services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
#endregion #endregion
#region Controllers #region jwt
services.Configure<JwtSettings>(Configuration.GetSection("Jwt"));
#endregion
services.AddHttpClient<ApiIntegrationService>(); #region Controllers
services.AddHttpClient<ApiIntegrationService>();
services.AddControllers( services.AddControllers(
options => { options.Filters.Add(new ProducesAttribute("application/json")); }) options => { options.Filters.Add(new ProducesAttribute("application/json")); })