MFA
This commit is contained in:
parent
838b8d4480
commit
125d79ed75
63
CLAUDE.md
63
CLAUDE.md
|
|
@ -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
|
||||
`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
|
||||
`HistorySalaryMonthlyAmountNull_DB_Changes.sql` run first. That script was deleted from the root in
|
||||
`91369150c` (not archived): recover it with
|
||||
`HistorySalaryMonthlyAmountNull_DB_Changes.sql` run first. That script is not in this repo — it was
|
||||
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;
|
||||
the save is `HistorySalaryMonthlyService`'s one all-or-nothing transaction.
|
||||
- **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
|
||||
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`.
|
||||
Schema: `ScheduleEmail_DB_Changes.sql` was deleted from the root once applied (commit `ac179c03e`)
|
||||
and **not** archived in `db/Script/` — recover it with `git show 73f466cd0:ScheduleEmail_DB_Changes.sql`.
|
||||
Schema: `ScheduleEmail_DB_Changes.sql` is **not** in this repo — it was deleted unarchived in `cel.hrm`;
|
||||
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
|
||||
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`).
|
||||
|
|
@ -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
|
||||
|
||||
`origin` (`103.197.204.162:3025/CelHRTeam/cel.hrm`) carries ~79 branches, and they are not short-lived
|
||||
feature branches. The 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`).
|
||||
**This checkout is not that repo.** It is `HRM-10` (`origin` = `103.197.204.162:3025/CelHRTeam/HRM-10`),
|
||||
a fresh import with a single branch `main` and a single squashed commit (`838b8d4` "first commit").
|
||||
None of the older history exists here: every commit hash quoted elsewhere in this file (`c8588ce67`,
|
||||
`91369150c`, `ac179c03e`, `73f466cd0`, `bfd085e0e`) is from the original `CelHRTeam/cel.hrm` repo, and
|
||||
`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:
|
||||
|
||||
- Work moves between client branches by hand, as bulk "transferred from `<branch>`" commits — e.g.
|
||||
`c8588ce67` "works transfered from square_pms". So a fix made here is *not* automatically in any
|
||||
other client's branch, and a file can look freshly rewritten when it was only ported. Check
|
||||
`git log --follow` before assuming a recent change was authored for this branch.
|
||||
- Work moves between client branches by hand, as bulk "transferred from `<branch>`" commits. So a fix
|
||||
made here is *not* automatically in any client's branch of `cel.hrm` (and vice versa), and a file
|
||||
can look freshly rewritten when it was only ported.
|
||||
- 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
|
||||
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:
|
||||
|
||||
- **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
|
||||
scripts here, in the same commit as the code that needs them.
|
||||
- **[`db/Script/`](db/Script)** — the archive of shipped ones. Applied scripts used to be deleted
|
||||
outright; commit `c8588ce67` (2026-10-13) instead *moved* the five applied ones here
|
||||
(`Calendar`, `MenuIcon`, `AttendanceLeaveSummaryLM`, `TaxParameterEssDeadline`,
|
||||
`PMS_SquareAlign_IDP`). Read them for precedent — they are the best worked examples of house style
|
||||
— but don't re-run one against a database that already has it.
|
||||
(at the initial import there were none). Write new scripts here, in the same commit as the code
|
||||
that needs them.
|
||||
- **[`db/Script/`](db/Script)** — the archive of shipped ones (`Calendar`, `MenuIcon`,
|
||||
`AttendanceLeaveSummaryLM`, `TaxParameterEssDeadline`, `PMS_SquareAlign_IDP`, `EmpHistoricalData`).
|
||||
Read them for precedent — they are the best worked examples of house style — but don't re-run one
|
||||
against a database that already has it.
|
||||
|
||||
The convention is not enforced: `bfd085e0e` (Historical Data Upload) committed
|
||||
`EmpHistoricalData_DB_Changes.sql` straight into `db/Script/`. So the root listing is not a complete
|
||||
"pending" list — before deploying a branch to a database, also check `git log -- db/Script` for
|
||||
scripts added since that database was last updated. It also breaks the other way: applied scripts
|
||||
are still sometimes deleted instead of moved (`ScheduleEmail`, `UserEmailAddress`,
|
||||
`HistorySalaryMonthlyAmountNull`, … in `ac179c03e` / `73f466cd0` / `91369150c`), so for those the only
|
||||
copy is git history (`git show <deleting-commit>^:<file>`) —
|
||||
`git log --diff-filter=D --name-only -- '*_DB_Changes.sql'` lists them.
|
||||
The convention was not enforced in `cel.hrm`: `EmpHistoricalData` went straight into `db/Script/`,
|
||||
and several applied scripts were deleted instead of archived — `ScheduleEmail`, `UserEmailAddress`,
|
||||
`HistorySalaryMonthlyAmountNull` and others. **None of those deleted scripts exist in this repo**;
|
||||
the only copies are in `cel.hrm` history (`git log --diff-filter=D --name-only -- '*_DB_Changes.sql'`
|
||||
there). A fresh database built from this repo's scripts alone will be missing that schema, as well as
|
||||
the never-scripted `MasterEmailLog` tables.
|
||||
|
||||
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
|
||||
|
|
@ -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`
|
||||
7. the feature component(s) under `ClientApp/src/app/<feature>/`
|
||||
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.
|
||||
|
|
|
|||
47
HRM.UI/ClientApp/src/app/_guards/idle.service.ts
Normal file
47
HRM.UI/ClientApp/src/app/_guards/idle.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -18,6 +18,7 @@ import { Subject } from 'rxjs';
|
|||
import { PendingJobDTO } from 'src/app/_models/Work-Flow/pendingJobDTO';
|
||||
import { DataPermission } from 'src/app/_models/Basic/DataPermission';
|
||||
import { BehaviorSubject } from 'rxjs';
|
||||
import { IdleService } from 'src/app/_guards/idle.service';
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthService {
|
||||
|
||||
|
|
@ -39,7 +40,6 @@ export class AuthService {
|
|||
getIsFromSuperUser(): boolean {
|
||||
return this.isFromSuperUserSubject.value;
|
||||
}
|
||||
|
||||
private isFromUserSubject = new BehaviorSubject<boolean>(false);
|
||||
isFromUser$ = this.isFromUserSubject.asObservable();
|
||||
setIsFromUser(value: boolean) {
|
||||
|
|
@ -48,22 +48,29 @@ export class AuthService {
|
|||
// bookmarks: Bookmark[];
|
||||
constructor(private http: HttpClient,
|
||||
public apiService: ApiService ,
|
||||
public notificationService: HRMNotificationService, private router: Router) {
|
||||
public notificationService: HRMNotificationService, private router: Router, private idleService: IdleService) {
|
||||
this.subject = new Subject<Bookmark[]>();
|
||||
this.subject2 = new Subject<PendingJobDTO[]>();
|
||||
// this.loadBookmark();
|
||||
// console.log(this.bookmarks);
|
||||
}
|
||||
|
||||
login(model: any) {
|
||||
return this.http.post(this.apiService.base_url + '/Authentication/login', model).pipe(
|
||||
map((response: any) => {
|
||||
const user = response;
|
||||
if (user) {
|
||||
// debugger;
|
||||
localStorage.setItem('token', user);
|
||||
ApiService.AuthenticationToken = user;
|
||||
// this.decodedToken = this.jwtHelper.decodeToken(ApiService.AuthenticationToken);
|
||||
if(user.mfaRequired){
|
||||
ApiService.isMFA = true;
|
||||
ApiService.AuthenticationMFASessionID = user. mfaSessionId;
|
||||
}
|
||||
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.setItem('pendingjobs', JSON.stringify(pendingJobDTOs));
|
||||
}
|
||||
|
||||
userPayrolltypeSwitch(param: any): any {
|
||||
return this.apiService.httpPost<any>('/Authentication/userPayrolltypeSwitch', param);
|
||||
}
|
||||
SwtichUserMode(param: any): any {
|
||||
return this.apiService.httpPost<any>('/Authentication/switchuser', param);
|
||||
}
|
||||
|
||||
GetLogInUserType(): any {
|
||||
return this.apiService.httpGet<EnumUserType>('/Authentication/GetLogInUserType');
|
||||
}
|
||||
|
||||
GetCurrentUser(): any {
|
||||
return this.apiService.httpGet<any>('/Authentication/GetCurrentUser');
|
||||
}
|
||||
getUserByEmail(email: string) {
|
||||
return this.apiService.httpGet<User>('/Authentication/getUserByEmail/' + email);
|
||||
}
|
||||
|
||||
GetUsers(usertype: EnumUserType, loginidid?: string, name?: string): any {
|
||||
//const params = {
|
||||
// LogInID: loginid == undefined ? '' : loginid,
|
||||
// Name: name == undefined ? '' : name,
|
||||
// userType: usertype
|
||||
//};
|
||||
|
||||
const nname = this.apiService.getApiDefaultData(name);
|
||||
const sloginid = this.apiService.getApiDefaultData(loginidid);
|
||||
|
||||
return this.apiService.httpGet<User[]>('/Authentication/GetUsers/' + usertype + '/' + loginidid + '/' + name);
|
||||
}
|
||||
|
||||
GetAllEmpNotYetUser() {
|
||||
return this.apiService.httpGet<User[]>('/Authentication/GetAllEmpNotYetUser');
|
||||
|
||||
}
|
||||
|
||||
logout() {
|
||||
localStorage.removeItem('forgotpass');
|
||||
localStorage.removeItem('bookmark');
|
||||
|
|
@ -124,16 +122,12 @@ export class AuthService {
|
|||
this.logoutSource.next();
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
|
||||
|
||||
SaveUser(oUser: User): any {
|
||||
return this.apiService.httpPost<User>('/Authentication/SaveUser', oUser);
|
||||
}
|
||||
|
||||
ApproveUser(oUser: User): any {
|
||||
return this.apiService.httpPost<User>('/Authentication/ApproveUser', oUser);
|
||||
}
|
||||
|
||||
DoActiveAndIntacive(oUser: User): any {
|
||||
return this.apiService.httpPost<User>('/Authentication/DoActiveAndIntacive', oUser);
|
||||
}
|
||||
|
|
@ -143,64 +137,47 @@ export class AuthService {
|
|||
getBookmarks() {
|
||||
return this.apiService.httpGet<Bookmark[]>('/Authentication/getBookmarks');
|
||||
}
|
||||
|
||||
SaveBookmark(oBookmark: Bookmark): any {
|
||||
return this.apiService.httpPost<Bookmark>('/Authentication/SaveBookmark', oBookmark);
|
||||
}
|
||||
|
||||
deleteBookmark(param: any) {
|
||||
return this.apiService.httpPost('/Authentication/deleteBookmark', param);
|
||||
}
|
||||
|
||||
deleteBookmarkByMenuKey(param: any) {
|
||||
return this.apiService.httpPost('/Authentication/deleteBookmarkByMenuKey', param);
|
||||
}
|
||||
|
||||
getPendingJob(employeeId: number) {
|
||||
return this.apiService.httpGet<PendingJobDTO[]>('/Workflow/getPendingJob' + '/' + employeeId);
|
||||
}
|
||||
markNotificationsAsRead(ids: number[]) {
|
||||
return this.apiService.httpPost<any>('/Workflow/MarkNotificationsAsRead', ids);
|
||||
}
|
||||
|
||||
loggedIn() {
|
||||
const token = localStorage.getItem('token');
|
||||
ApiService.AuthenticationToken = token;
|
||||
return !this.jwtHelper.isTokenExpired(token);
|
||||
}
|
||||
|
||||
register(user: User) {
|
||||
return this.http.post(this.baseUrl + 'register', user);
|
||||
}
|
||||
|
||||
loadMenu() {
|
||||
return this.http.get(this.baseUrl + 'loadMenu');
|
||||
}
|
||||
|
||||
getAllRoles() {
|
||||
return this.apiService.httpGet<RolePermission[]>('/Authentication/getAllRoles');
|
||||
}
|
||||
|
||||
|
||||
|
||||
getRole(roleID: number) {
|
||||
return this.apiService.httpGet<RolePermission[]>('/Authentication/getRole/' + roleID);
|
||||
}
|
||||
|
||||
|
||||
getMenuesFromConfig() {
|
||||
return this.apiService.httpGet<RolePermission[]>('/Authentication/getMenuesFromConfig');
|
||||
}
|
||||
|
||||
saveRole(params: Role) {
|
||||
return this.apiService.httpPost<number>('/Authentication/saveRole', params);
|
||||
}
|
||||
|
||||
GetRolePermissionbyUserID() {
|
||||
return this.apiService.httpGet<any>('/Authentication/GetRolePermissionbyUserID');
|
||||
}
|
||||
|
||||
|
||||
getUserRoles(roletype: EnumRoleType, userID?: number, roleid?: number) {
|
||||
|
||||
const nuserid = this.apiService.getApiDefaultIntData(userID);
|
||||
|
|
@ -209,66 +186,51 @@ export class AuthService {
|
|||
return this.apiService.httpGet<UserRole[]>('/Authentication/getUserRoles/' + roletype + '/'
|
||||
+ nuserid + '/' + nroletype);
|
||||
}
|
||||
|
||||
|
||||
GetEmpUserRole(searchemps: SearchEmployee[]) {
|
||||
|
||||
return this.apiService.httpPost<UserRole[]>('/Authentication/GetEmpUserRole', searchemps);
|
||||
}
|
||||
|
||||
saveUserRole(params: any) {
|
||||
return this.apiService.httpPost<number>('/Authentication/saveUserRole', params);
|
||||
}
|
||||
|
||||
|
||||
GetAllPayrollTypes() {
|
||||
return this.apiService.httpGet<PayrollType[]>('/Authentication/GetAllPayrollTypes');
|
||||
}
|
||||
|
||||
GetPayrollTypesByLoginID(loginID: string) {
|
||||
return this.apiService.httpGet<PayrollType[]>('/Authentication/GetPayrollTypesByLoginID/' + loginID);
|
||||
}
|
||||
GetBenifitsProcessStatus() {
|
||||
return this.apiService.httpGet<PayrollType[]>('/Authentication/GetBenifitsProcessStatus' );
|
||||
}
|
||||
|
||||
getSwitchUserId(usertype: EnumUserType) {
|
||||
return this.apiService.httpGet<any>('/Authentication/getSwitchUserId/'+ usertype);
|
||||
}
|
||||
|
||||
GetPayrollTypeByLoginID() {
|
||||
return this.apiService.httpGet<PayrollType>('/Authentication/GetPayrollTypeByLoginID');
|
||||
}
|
||||
getAdminPayrollTypes() {
|
||||
return this.apiService.httpGet<PayrollType[]>('/Authentication/getAdminPayrollTypes');
|
||||
}
|
||||
|
||||
GetUserAccessType(userid: number) {
|
||||
return this.apiService.httpGet<UserAccessType[]>('/Authentication/GetUserAccessType/' + userid);
|
||||
|
||||
}
|
||||
|
||||
SaveUserAccessType(acesssTypes: UserAccessType[]) {
|
||||
return this.apiService.httpPost<boolean>('/Authentication/SaveUserAccessType', acesssTypes);
|
||||
|
||||
}
|
||||
|
||||
changePassword(userData: any) {
|
||||
return this.apiService.httpPost<any>('/Authentication/changePassword', userData);
|
||||
}
|
||||
|
||||
changePasswordbyAdmin(userData: any) {
|
||||
return this.apiService.httpPost<any>('/Authentication/changePasswordbyAdmin', userData);
|
||||
}
|
||||
|
||||
forgotPassword(data: any) {
|
||||
return this.apiService.httpPost<any>('/Authentication/forgotPassword', data);
|
||||
}
|
||||
|
||||
getVersionNumber() {
|
||||
return this.apiService.httpGet<string>('/Authentication/getVersionNumber');
|
||||
}
|
||||
|
||||
GetUserByLoingID(loginid: string, systemType: EnumSystemType) {
|
||||
return this.apiService.httpGet<User>('/Authentication/GetUserByLoingID/' + loginid + '/' + systemType);
|
||||
}
|
||||
|
|
@ -279,19 +241,15 @@ export class AuthService {
|
|||
getUserByUserType(param: any): any {
|
||||
return this.apiService.httpPost<any>('/Authentication/getUserByUserType', param);
|
||||
}
|
||||
|
||||
|
||||
addPermission(param: any) {
|
||||
return this.apiService.httpPost<any>('/Authentication/addPermission', param);
|
||||
}
|
||||
|
||||
loadDataPermission(userid: number, payrolltypeid:number) {
|
||||
return this.apiService.httpGet<DataPermission[]>('/Authentication/loadDataPermission/' + userid + "/" + payrolltypeid);
|
||||
}
|
||||
DeletedataPermission(item:any) {
|
||||
return this.apiService.httpPost<any> ('/Authentication/deletePermission' ,item);
|
||||
}
|
||||
|
||||
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);
|
||||
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;
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ import { environment } from '../environments/environment';
|
|||
export class ApiService {
|
||||
|
||||
public isSSO = false;
|
||||
public static isMFA : boolean = false;
|
||||
public isADLogin = false;
|
||||
public versionDeployement = false;
|
||||
public versionNumber = "20261012-01";
|
||||
public static BASE_URL = '';
|
||||
|
|
@ -24,6 +26,7 @@ export class ApiService {
|
|||
public static PAYROLLTYPEID: number = 0;
|
||||
public static USERTYPE: number = 0;
|
||||
public isSelService : boolean = true;
|
||||
public static MFACode: string = undefined;
|
||||
public isSelServiceFullScreen : boolean = false;
|
||||
public isNewDaswhboard : boolean = true;
|
||||
public menuItems: any[] = [];
|
||||
|
|
@ -36,6 +39,7 @@ export class ApiService {
|
|||
public static AuthenticationToken = '';
|
||||
public static readonly DEFAULT_PHOTO = './assets/photos/profile-default.jpg';
|
||||
public selectedMenuName: string = '';
|
||||
public static AuthenticationMFASessionID = '';
|
||||
|
||||
constructor(public httpClient: HttpClient, public datepipe: DatePipe) {
|
||||
if (!ApiService.AuthenticationToken) {
|
||||
|
|
|
|||
|
|
@ -15,8 +15,6 @@
|
|||
@if (!apiService.isSSO) {
|
||||
<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" 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>
|
||||
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
|
||||
<div class="login-input-wrapper">
|
||||
|
|
@ -70,6 +68,4 @@
|
|||
</kendo-dialog>
|
||||
}
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
||||
</html>
|
||||
|
|
@ -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 { FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { AuthGuard } from './_guards/auth.guard';
|
||||
|
|
@ -46,7 +46,6 @@ export class LoginComponent implements OnInit {
|
|||
versionNumber: string;
|
||||
showModal = false;
|
||||
bookmarks: Bookmark[] = [];
|
||||
/* _wfmovementTrans: PendingJobDTO[] = [];*/
|
||||
currentUser: User;
|
||||
emailAddress = '';
|
||||
bannerHeight = '200px';
|
||||
|
|
@ -66,12 +65,6 @@ export class LoginComponent implements OnInit {
|
|||
private authService: MsalService, public appMain : AppMainComponent,
|
||||
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) {
|
||||
this.router.navigate(['/']);
|
||||
}
|
||||
|
|
@ -85,47 +78,50 @@ export class LoginComponent implements OnInit {
|
|||
nmgtLink : any;
|
||||
currentLink : any;
|
||||
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() {
|
||||
// const x = window.location.href;
|
||||
// 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.userService.getSSOStatus().subscribe(
|
||||
(resp) => {
|
||||
// debugger;
|
||||
this.ssoDT = resp;
|
||||
this.apiService.isSSO = this.ssoDT[0].isSSO;
|
||||
this.apiService.isNewDaswhboard = this.ssoDT[0].isNewDashboard;
|
||||
this.nmgtLink = this.ssoDT[0].nmgtLink;
|
||||
ApiService.isMFA = this.ssoDT[0].isMFA;
|
||||
this.mFATimer = this.ssoDT[0].mfaTimer;
|
||||
},
|
||||
(x) => {
|
||||
this.loadingPanel.ShowLoadingPanel = false;
|
||||
},
|
||||
() => {
|
||||
this.loadingPanel.ShowLoadingPanel = false;
|
||||
// if(this.apiService.currentLink === this.nmgtLink){
|
||||
// this.apiService.isSSO = false;
|
||||
// }
|
||||
// debugger;
|
||||
|
||||
if (this.apiService.isSSO === true) {
|
||||
this.msalBroadcastService.msalSubject$
|
||||
.pipe(
|
||||
filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
|
||||
)
|
||||
.subscribe((result: EventMessage) => {
|
||||
console.log('My Credential is following');
|
||||
console.log(result);
|
||||
});
|
||||
.pipe(filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),)
|
||||
.subscribe((result: EventMessage) => {});
|
||||
this.msalBroadcastService.inProgress$
|
||||
.pipe(
|
||||
filter((status: InteractionStatus) => status === InteractionStatus.None)
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.setLoginDisplay();
|
||||
});
|
||||
.pipe(filter((status: InteractionStatus) => status === InteractionStatus.None))
|
||||
.subscribe(() => {this.setLoginDisplay();});
|
||||
}
|
||||
});
|
||||
|
||||
this.showModal = false;
|
||||
this.loginForm = this.formBuilder.group({
|
||||
username: ['', Validators.required],
|
||||
|
|
@ -133,9 +129,7 @@ export class LoginComponent implements OnInit {
|
|||
payrolltypeid: [''],
|
||||
});
|
||||
this.payrollTypes = [];
|
||||
// this.versionNumber = 'v-20240109-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'] || '/';
|
||||
}
|
||||
public payrollTypesImg = [
|
||||
|
|
@ -162,18 +156,11 @@ export class LoginComponent implements OnInit {
|
|||
this.authService.loginRedirect();
|
||||
}
|
||||
}
|
||||
|
||||
// convenience getter for easy access to form fields
|
||||
get f() {
|
||||
return this.loginForm.controls;
|
||||
}
|
||||
|
||||
|
||||
onFocusOutEvent(event: any) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
GetPayrollTypeByLoginID() {
|
||||
this.selectedPayrollTypeID = null;
|
||||
this.payrollTypes = [];
|
||||
|
|
@ -181,7 +168,6 @@ export class LoginComponent implements OnInit {
|
|||
return;
|
||||
}
|
||||
this.loadingPanel.ShowLoadingPanel = true;
|
||||
// Assuming GetPayrollTypesByLoginID is an observable returning payroll types based on the username
|
||||
this.userService.GetPayrollTypesByLoginID(this.f['username'].value).subscribe(
|
||||
(resp: any) => {
|
||||
this.payrollTypes = resp;
|
||||
|
|
@ -195,8 +181,6 @@ export class LoginComponent implements OnInit {
|
|||
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;
|
||||
|
|
@ -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() {
|
||||
this.showModal = false;
|
||||
}
|
||||
|
||||
forgetPassword() {
|
||||
localStorage.setItem('forgotpass', JSON.stringify(true));
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('menuList');
|
||||
|
||||
// this.router.navigate(['/forgot-password']);
|
||||
|
||||
// this.router.navigateByUrl('/forgot-password');
|
||||
|
||||
// this.router.navigate(['/forgot-password']);
|
||||
}
|
||||
|
||||
onSubmit() {
|
||||
debugger;
|
||||
if (this.apiService.isSSO) {
|
||||
this.authService.loginRedirect();
|
||||
console.log('redirect');
|
||||
} else {
|
||||
this.GetPayrollTypeByLoginID();
|
||||
}
|
||||
}
|
||||
|
||||
private Login() {
|
||||
let params: any;
|
||||
if (this.apiService.isSSO === true) {
|
||||
|
|
@ -274,7 +219,6 @@ export class LoginComponent implements OnInit {
|
|||
email: this.emailAddress,
|
||||
isSSO: true
|
||||
};
|
||||
console.log(params);
|
||||
} else {
|
||||
let nextPayrollProcessDate;
|
||||
this.submitted = true;
|
||||
|
|
@ -285,7 +229,6 @@ export class LoginComponent implements OnInit {
|
|||
this.notificationService.showError('Please select a Access-Type');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.selectedPayrollTypeID != undefined && this.selectedPayrollTypeID != null) {
|
||||
nextPayrollProcessDate = this.payrollTypes.find(x => x.id == this.selectedPayrollTypeID).nextPayProcessDate;
|
||||
}
|
||||
|
|
@ -305,54 +248,75 @@ export class LoginComponent implements OnInit {
|
|||
this.loading = false;
|
||||
},
|
||||
(err: any) => {
|
||||
console.log(err);
|
||||
if(this.apiService.isSSO === true){
|
||||
this.notificationService.showError('User not found');
|
||||
}
|
||||
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;
|
||||
},
|
||||
() => {
|
||||
const jwtHelper = new JwtHelperService();
|
||||
//Remove Pending Job
|
||||
|
||||
// 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);
|
||||
if(ApiService.isMFA == true){
|
||||
this.loadingPanel.ShowLoadingPanel = false;
|
||||
this.router.navigate(['/authentication/change-password']);
|
||||
} else {
|
||||
this.userService.GetRolePermissionbyUserID().subscribe(
|
||||
(menu: any) => {
|
||||
localStorage.setItem('menuList', JSON.stringify(menu));
|
||||
this.router.navigate(['/']);
|
||||
},
|
||||
(errmenu: any) => {
|
||||
this.notificationService.showError(errmenu.error);
|
||||
this.loading = false;
|
||||
this.showModal = false;
|
||||
this.showMfaModal = true;
|
||||
this.mfaCode = '';
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('menuList');
|
||||
this.startTimer();
|
||||
}else{
|
||||
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.appMain.IsSelfService();
|
||||
this.loadBookmark();
|
||||
this.auth.menuEvent.emit(true);
|
||||
this.router.navigate(['/authentication/change-password']);
|
||||
}
|
||||
);
|
||||
else{
|
||||
this.getMenu();
|
||||
}
|
||||
}
|
||||
else{
|
||||
this.getMenu();
|
||||
}
|
||||
}
|
||||
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() {
|
||||
this.userService.getBookmarks()
|
||||
.subscribe(
|
||||
|
|
@ -379,23 +343,143 @@ export class LoginComponent implements OnInit {
|
|||
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() {
|
||||
localStorage.removeItem('token');
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -389,9 +389,9 @@ namespace HRM.UI.Controllers
|
|||
return BadRequest("Login ID/Password is invalid");
|
||||
}
|
||||
}
|
||||
|
||||
string userToken = this.CreateToten(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate);
|
||||
return Ok(userToken);
|
||||
//string userToken = this.CreateToten(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate);
|
||||
string userToken = this.CreateTokenNew(userFromRepo, userForLoginDto.payrollTypeid, userForLoginDto.nextPayProcessDate, mfaCode);
|
||||
return Ok(userToken);
|
||||
}
|
||||
|
||||
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()),
|
||||
};
|
||||
|
||||
// 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 token = new JwtSecurityToken(
|
||||
issuer: _jwt.Issuer,
|
||||
audience: _jwt.Audience,
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(_jwt.TokenLifetimeMinutes),
|
||||
signingCredentials: new SigningCredentials(
|
||||
new SymmetricSecurityKey(key),
|
||||
SecurityAlgorithms.HmacSha256
|
||||
)
|
||||
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
|
||||
);
|
||||
string userToken = new JwtSecurityTokenHandler().WriteToken(token);
|
||||
if (!string.IsNullOrEmpty(userToken))
|
||||
|
|
@ -549,7 +543,6 @@ namespace HRM.UI.Controllers
|
|||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return roles.Distinct().ToList();
|
||||
}
|
||||
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")]
|
||||
public ActionResult userPayrolltypeSwitch(dynamic data)
|
||||
{
|
||||
|
|
@ -1621,21 +1708,27 @@ namespace HRM.UI.Controllers
|
|||
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
|
||||
EmailSettings emailSettings = new EmailSettings();
|
||||
IConfiguration Configuration = builder.Build();
|
||||
Configuration.GetSection("EmailSettings").Bind(emailSettings);
|
||||
//Configuration.GetSection("EmailSettings").Bind(emailSettings);
|
||||
string isSSO = Configuration.GetSection("EmailSettings")["isSSO"];
|
||||
string isNewDashboard = Configuration.GetSection("EmailSettings")["isNewDashboard"];
|
||||
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("nmgtLink", typeof(string));
|
||||
dt.Columns.Add("isNewDashboard", typeof(bool));
|
||||
dt.Columns.Add("isMFA", typeof(bool));
|
||||
dt.Columns.Add("mfaTimer", typeof(int));
|
||||
dt.TableName = "SSO";
|
||||
|
||||
DataRow row = dt.NewRow();
|
||||
row["isSSO"] = isSSO == "true" ? true : false;
|
||||
row["isNewDashboard"] = isNewDashboard == "false" ? false : true;
|
||||
row["nmgtLink"] = nmgtLink;
|
||||
row["isMFA"] = isMFA == "true" ? true : false;
|
||||
row["mfaTimer"] = int.Parse(mfaTimer);
|
||||
dt.Rows.Add(row);
|
||||
|
||||
return Ok(dt);
|
||||
|
|
|
|||
|
|
@ -33,7 +33,8 @@ namespace HRM.UI.Api
|
|||
|
||||
private readonly ILogger _logger;
|
||||
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)
|
||||
{
|
||||
|
|
@ -42,7 +43,8 @@ namespace HRM.UI.Api
|
|||
Configuration = configuration;
|
||||
|
||||
_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.
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
|
|
@ -78,11 +80,15 @@ namespace HRM.UI.Api
|
|||
|
||||
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(
|
||||
options => { options.Filters.Add(new ProducesAttribute("application/json")); })
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user