HRM-10/HRM.UI/ClientApp/src/app/login.component.ts

486 lines
19 KiB
TypeScript
Raw Normal View History

2026-11-03 15:54:54 +06:00
import { Component, ElementRef, OnInit, ChangeDetectionStrategy, QueryList, ViewChildren } from '@angular/core';
2026-11-03 13:06:00 +06:00
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthGuard } from './_guards/auth.guard';
import { ApiService } from './app.api.service';
import { AuthService } from './_services/auth/auth.service';
import { PayrollType } from './_models/Authentication/payrollType';
import { HRMNotificationService } from './app.notification.service';
import { JwtHelperService } from '@auth0/angular-jwt';
import { loadingPanelService } from './hrm-loding panel/loding.panel.service';
import { Bookmark } from './_models/Basic/bookmark';
import { MenuService } from './app.menu.service';
import { WorkflowService } from './_services/workflow/workflow.service';
import { PendingJobDTO } from './_models/Work-Flow/pendingJobDTO';
import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
import { filter } from 'rxjs/operators';
import { EventMessage, EventType, InteractionStatus } from '@azure/msal-browser';
import { User } from './_models/Authentication/user';
import { GlobalfunctionExtension } from './_models/globalFunctions';
import { AppMainComponent } from './app.main.component';
import { LoadingPanelComponent } from './hrm-loding panel/loading-panel.component';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from '@progress/kendo-angular-buttons';
import { DropDownListModule } from '@progress/kendo-angular-dropdowns';
import { DialogModule } from '@progress/kendo-angular-dialog';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { LabelModule } from '@progress/kendo-angular-label';
import { VersionCheckService } from './version-check.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
payrollTypes: PayrollType[];
selectedPayrollTypeID: number;
versionNumber: string;
showModal = false;
bookmarks: Bookmark[] = [];
currentUser: User;
emailAddress = '';
bannerHeight = '200px';
bannerWidth = '360px';
imgSrc: string= 'assets/layout/images/Logo.png';
appVersion: string = '...';
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
public userService: AuthService,
public apiService: ApiService,
private auth: AuthGuard,
public notificationService: HRMNotificationService, public loadingPanel: loadingPanelService,
public wfService: WorkflowService, public menuService: MenuService,
private msalBroadcastService: MsalBroadcastService,
private authService: MsalService, public appMain : AppMainComponent,
private versionCheck: VersionCheckService
) {
if (ApiService.AuthenticationToken && window.location.hash.indexOf('/login') > -1) {
this.router.navigate(['/']);
}
this.versionCheck.currentVersion$.subscribe(v => {
this.appVersion = v;
});
this.showModal = false;
}
ssoDT : any;
nmgtLink : any;
currentLink : any;
loadFirst : boolean;
2026-11-03 15:54:54 +06:00
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;
2026-11-03 13:06:00 +06:00
ngOnInit() {
// const x = window.location.href;
// this.currentLink = window.location.href.split('/').pop();
2026-11-03 15:54:54 +06:00
this.apiService.isADLogin = false;
ApiService.isMFA = false;
this.mFATimer = 2;
this.nmgtLink = null;
2026-11-03 13:06:00 +06:00
this.loadingPanel.ShowLoadingPanel = true;
this.userService.getSSOStatus().subscribe(
(resp) => {
this.ssoDT = resp;
this.apiService.isSSO = this.ssoDT[0].isSSO;
this.apiService.isNewDaswhboard = this.ssoDT[0].isNewDashboard;
this.nmgtLink = this.ssoDT[0].nmgtLink;
2026-11-03 15:54:54 +06:00
ApiService.isMFA = this.ssoDT[0].isMFA;
this.mFATimer = this.ssoDT[0].mfaTimer;
2026-11-03 13:06:00 +06:00
},
(x) => {
this.loadingPanel.ShowLoadingPanel = false;
},
() => {
this.loadingPanel.ShowLoadingPanel = false;
if (this.apiService.isSSO === true) {
this.msalBroadcastService.msalSubject$
2026-11-03 15:54:54 +06:00
.pipe(filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),)
.subscribe((result: EventMessage) => {});
2026-11-03 13:06:00 +06:00
this.msalBroadcastService.inProgress$
2026-11-03 15:54:54 +06:00
.pipe(filter((status: InteractionStatus) => status === InteractionStatus.None))
.subscribe(() => {this.setLoginDisplay();});
2026-11-03 13:06:00 +06:00
}
});
this.showModal = false;
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required],
payrolltypeid: [''],
});
this.payrollTypes = [];
this.versionNumber = 'v-' + GlobalfunctionExtension.generateVersionNumber(new Date(2024, 4, 28)) + '-01';
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
public payrollTypesImg = [
{ id: 1, imagePath: 'assets/payrolltype-img/payrolltype1.png' },
{ id: 2, imagePath: 'assets/payrolltype-img/payrolltype2.png' },
{ id: 3, imagePath: 'assets/payrolltype-img/payrolltype3.png' },
{ id: 4, imagePath: 'assets/payrolltype-img/payrolltype4.png' },
{ id: 5, imagePath: 'assets/payrolltype-img/payrolltype5.png' }
];
public getImagePath(typeId: number): string {
const typeImage = this.payrollTypesImg.find(img => img.id === typeId);
return typeImage ? typeImage.imagePath : 'assets/layout/images/Logo.png';
}
public selectPayrollType(typeId: number): void {
this.selectedPayrollTypeID = typeId;
this.Login();
}
setLoginDisplay() {
if (this.authService.instance.getAllAccounts().length > 0) {
const user = this.authService.instance.getAllAccounts()[0];
this.emailAddress = user.username;
this.Login();
} else {
this.authService.loginRedirect();
}
}
get f() {
return this.loginForm.controls;
}
onFocusOutEvent(event: any) {
}
GetPayrollTypeByLoginID() {
this.selectedPayrollTypeID = null;
this.payrollTypes = [];
if (this.f['username'].value.length < 3) {
return;
}
this.loadingPanel.ShowLoadingPanel = true;
this.userService.GetPayrollTypesByLoginID(this.f['username'].value).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);
}
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');
}
onSubmit() {
if (this.apiService.isSSO) {
this.authService.loginRedirect();
} else {
this.GetPayrollTypeByLoginID();
}
}
private Login() {
let params: any;
if (this.apiService.isSSO === true) {
params = {
Username: '',
Password: '',
payrollTypeid: null,
nextPayProcessDate: null,
email: this.emailAddress,
isSSO: true
};
} else {
let nextPayrollProcessDate;
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
if (this.payrollTypes.length > 1 && this.selectedPayrollTypeID === undefined) {
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;
}
this.loading = true;
params = {
Username: this.f['username'].value,
Password: this.f['password'].value,
payrollTypeid: this.selectedPayrollTypeID,
nextPayProcessDate: nextPayrollProcessDate,
email: '',
isSSO: false
};
}
this.loadingPanel.ShowLoadingPanel = true;
this.userService.login(params).subscribe(
(resp: any) => {
this.loading = false;
},
(err: any) => {
if(this.apiService.isSSO === true){
this.notificationService.showError('User not found');
}
else{
2026-11-03 15:54:54 +06:00
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');
}
2026-11-03 13:06:00 +06:00
}
this.loadingPanel.ShowLoadingPanel = false;
},
() => {
const jwtHelper = new JwtHelperService();
2026-11-03 15:54:54 +06:00
if(ApiService.isMFA == true){
2026-11-03 13:06:00 +06:00
this.loadingPanel.ShowLoadingPanel = false;
2026-11-03 15:54:54 +06:00
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);
2026-11-03 13:06:00 +06:00
this.loadingPanel.ShowLoadingPanel = false;
2026-11-03 15:54:54 +06:00
this.router.navigate(['/authentication/change-password']);
}
else{
this.getMenu();
2026-11-03 13:06:00 +06:00
}
2026-11-03 15:54:54 +06:00
}
else{
this.getMenu();
}
2026-11-03 13:06:00 +06:00
}
this.showModal = false;
}
);
}
2026-11-03 15:54:54 +06:00
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);
}
);
}
2026-11-03 13:06:00 +06:00
loadBookmark() {
this.userService.getBookmarks()
.subscribe(
(resp: any) => {
if (resp != undefined) {
this.menuService.bookMarkpages = resp;
}
},
(x) => {
},
() => {
localStorage.removeItem('bookmark');
localStorage.setItem('bookmark', JSON.stringify(this.menuService.bookMarkpages));
// console.log(this.bookmarks);
//localStorage.setItem('bookmark', JSON.stringify(this.bookmarks));
//this.authService.subject.next(this.bookmarks);
/*let menu = JSON.parse(localStorage.getItem('menuList'))
.map(x => x.items)
.flat();
const flatMenu = menu.filter(x => x.routerLink === '' && x.items !== null).flatMap(x => x.items);
const menuToRemove = menu.filter(x => x.routerLink === '' && x.items !== null);
menu = menu.filter(x => !menuToRemove.includes(x));
menu = [...menu, ...flatMenu];*/
});
}
onForgotPassword() {
localStorage.removeItem('token');
this.router.navigate(['/forgot-password']);
}
2026-11-03 15:54:54 +06:00
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);
}
2026-11-03 13:06:00 +06:00
}