/** * @Component Name: AppComponent * @Module: App * @Module Functionality : To display the all products/cart functionality * @Creation Date: August 12,2017 * @Author: sbaireddy * @Version: 1.0 */ import { Component, ElementRef, OnInit } from '@angular/core'; import { Router, NavigationExtras } from '@angular/router'; import { OktaAuthService } from '@okta/okta-angular'; import { OktaConfig } from '@okta/okta-angular/dist/okta/models/okta.config'; import { environment } from './../environments/environment'; import { SharedService } from './shared/shared.service'; import { UserService } from './services/user.service'; import { ERROR_LIST } from './shared/error.constants'; import UserUtils from './shared/user.utils'; import { IWCToken, IChannel } from './shared/modal/common'; import { User } from './shared/modal/user'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { private COMPONENT_NAME: string = 'AppComponent'; storeId: number = 10553; karmaTestResult: any = {}; showTimeout: boolean = false; showSpinner: boolean = false; showInvalidCookie: boolean = false; isAuthenticated: boolean; wcsLoginFailed: boolean = false; inputData: any; /** constructor */ constructor(public router: Router, public oktaAuth: OktaAuthService, public sharedService: SharedService, public userService: UserService) { } /** * This function is used to initialize the directive/component after Angular * first displays the data-bound properties.It is invoked only once when the * directive is instantiated * @return void */ ngOnInit(): void { const METHOD_NAME: string = 'ngOnInit()'; console.log('AppComponent.ngOnInit()>>Start'); this.sharedService.storeId.subscribe((val: number) => { this.storeId = val; }); this.sharedService.spinnerStatus.subscribe((val: boolean) => { this.showSpinner = val; }); //Capture the query params let urlParams = new URLSearchParams(window.location.search); if (urlParams.has('storeId') && urlParams.get('storeId')) { let qStoreId: string = urlParams.get('storeId'); if (UserUtils.canSuportStore(qStoreId)) { this.sharedService.updateStoreId(Number(qStoreId)); } } if (urlParams.has('logonId') && urlParams.get('logonId')) { sessionStorage.setItem('logonId', urlParams.get('logonId')); } if (urlParams.has('passcode') && urlParams.get('passcode')) { sessionStorage.setItem('passcode', urlParams.get('passcode')); } if (urlParams.has('token') && urlParams.get('token')) { sessionStorage.setItem('toggleKey', urlParams.get('token')); } if (urlParams.has('orderId') && urlParams.get('orderId')) { const fullOrderId:string = urlParams.get('orderId'); if(fullOrderId && fullOrderId.length == 10){ sessionStorage.setItem('lookupOrderId', fullOrderId.substring(2)); //this.sharedService.salesForceURL = urlParams.get('orderId'); } } //Calling okta authentication if(environment.oktaEnable) { if(!UserUtils.canBypassAuthentication(window.location.pathname)) { console.log('Calling okta authentication ..............'); this.checkOktaAuthenticate(); } } // else{ // console.log('Calling wcs authentication ..............'); // this.router.navigate(['/mylogin']); // } console.log('AppComponent.ngOnInit()>>End'); } /** * This function is used to clear the session storage on timeout and navigate to login. * @returns void */ async clearSession(): Promise { const METHOD_NAME: string = 'clearSession()'; console.log('Hiding the session timeout model.') this.sharedService.showSpinner(false); this.sharedService.clearSessionStorage(true); // this.sharedService.clearLocalStorage(); if(environment.oktaEnable) { await this.oktaAuth.logout(); this.oktaAuth.loginRedirect('/login') }else{ this.router.navigate(['login']); } } async checkOktaAuthenticate(): Promise{ let oktaConfig:OktaConfig = this.oktaAuth.getOktaConfig(); // Print OKTA configuration console.log('OKTA Enabled>>'+ environment.oktaEnable); console.log('OKTA Issuer>>'+ oktaConfig.issuer); console.log('OKTA ClientId>>'+ oktaConfig.clientId); console.log('OKTA RedirectUri>>'+ oktaConfig.redirectUri); console.log('OKTA Scope>>'+ oktaConfig.scope); console.log('OKTA responseType>>'+ oktaConfig.responseType); this.sharedService.showSpinner(true); // Get the authentication state for immediate use await this.oktaAuth.isAuthenticated() .then((data) => { this.sharedService.showSpinner(false); this.isAuthenticated = data; console.log('AppComponent.checkOktaAuthenticate()>>Is authenticated from OKTA:'+ this.isAuthenticated); if(!this.isAuthenticated) { console.log("AppComponent.checkOktaAuthenticate()>>Rediecting to okta login page"); let loginCount: number = 1; if(sessionStorage.getItem('_OKTA_LOGIN_COUNT')) { loginCount = Number(sessionStorage.getItem('_OKTA_LOGIN_COUNT')) + 1; } sessionStorage.setItem('_OKTA_LOGIN_COUNT', ''+ loginCount ); if(loginCount <= 3 ) { //this.router.navigate(['/login']); this.oktaAuth.loginRedirect('/login'); }else{ sessionStorage.removeItem('_OKTA_LOGIN_COUNT'); this.navigateErrorPage('_ERR_CHANNEL_ACCESS_DENIED'); } }else{ if(sessionStorage.getItem('_OKTA_LOGIN_COUNT')) { sessionStorage.removeItem('_OKTA_LOGIN_COUNT'); } this.oktaAuth.getAccessToken() .then((data) => { let accessToken: string = data; console.log("AppComponent.checkOktaAuthenticate()>>OKTA Access Token:"+ accessToken); this.oktaAuth.getUser().then((data)=>{ console.log("AppComponent.checkOktaAuthenticate()>>OKTA User:"+ data); if(data && data.NTID ) this.login(data.NTID, '?jwtToken='+ accessToken); //if(data && data.NTID ) this.login(data.NTID, 'Password1'); }) .catch((err) => { console.error('AppComponent.checkOktaAuthenticate()>>error:' + err); this.navigateErrorPage(err); //this.router.navigate(['login/prohibited']); }); }) .catch((err) => { console.error('AppComponent.checkOktaAuthenticate()>>error:'+ err); this.navigateErrorPage(err); //this.router.navigate(['login/prohibited']); }); } }) .catch((err) => { console.error('error==>' + err); this.navigateErrorPage('_ERR_OKTA_LOGIN'); //this.router.navigate(['login/prohibited']); }); } /** * This function is used to authorize the agent's login information * after communicating with the login function in user service component * @return void */ async login(username: string, password: string): Promise{ const METHOD_NAME: string = 'login()'; this.sharedService.addLogging(this.COMPONENT_NAME, METHOD_NAME, 'Agent logged in'); console.log('AppComponent.login()>>Start.'); this.inputData = {logonId:username.toLowerCase(), logonPassword:password}; this.sharedService.showSpinner(true); this.userService.login(this.storeId, this.inputData).subscribe( data => { this.karmaTestResult = data; this.sharedService.showSpinner(false); console.log('AppComponent.login()>>login success..'); let wcToken:IWCToken = Object.assign({}, data); wcToken.logonId = username; wcToken.password = password; this.profile( wcToken ); }, error => { this.sharedService.showSpinner(false); //this.errorMessage = this.sharedService.getErrorMessage(error); console.error('error=>' + error); this.wcsLoginFailed = true; // WCS Login Failed. this.navigateErrorPage('_ERR_WCS_LOGIN'); //this.router.navigate(['login/prohibited']); }); console.log('Appomponent.login()>>End.'); } /** * This function is used to get the agent's profile which is part of * login functionality, and checking the user permission (for channels like CD,BD,CS) * based on agent's roles through getProfile function user service component. * @param {nuIWCTokenmber} wcToken - Contains the wc token * @return void */ async profile(wcToken: IWCToken): Promise { const METHOD_NAME: string = 'profile()'; console.log('AppComponent.profile()>>Start.'); this.sharedService.showSpinner(true); this.userService.getProfile(this.storeId, wcToken.userId).subscribe( data => { this.karmaTestResult = data; this.sharedService.showSpinner(false); console.log('AppComponent.login()>>User prfile success..'); let user:User = Object.assign(wcToken, data); UserUtils.updateFavorites(user); UserUtils.setPermissionsForAgent(user); if (user.channels && user.channels.length > 0) { if(UserUtils.hasAccessStore(this.storeId, user)){ UserUtils.activeSelectedStore(this.storeId, user); this.userService.setUser(user); this.router.navigate(['home/search']); //this.navigateErrorPage('_ERR_CHANNEL_ACCESS_DENIED');//added for testing }else{ let accStroreId = UserUtils.getAccessStore(user); if(accStroreId && accStroreId > 0) { this.sharedService.updateStoreId(accStroreId); this.login(user.logonId, user.password); //reloging in } else { this.navigateErrorPage('_ERR_CHANNEL_ACCESS_DENIED'); //this.errorMessage = this.sharedService.getErrorMessage('_ERR_CHANNEL_ACCESS_DENIED'); } } } else { this.navigateErrorPage('_ERR_CHANNEL_ACCESS_DENIED'); //this.errorMessage = this.sharedService.getErrorMessage('_ERR_CHANNEL_ACCESS_DENIED'); } }, error => { this.sharedService.showSpinner(false); //this.errorMessage = this.sharedService.getErrorMessage(error); console.error('error=>' + error); this.navigateErrorPage(error); //this.router.navigate(['login/prohibited']); }); console.log('AppComponent.profile()>>End.'); } navigateErrorPage(errors: any): void{ let errorCode: string = '_ERR_GENERIC'; if(errors && typeof (errors) === 'string') { const filterErrors = ERROR_LIST.filter((item) => { return errors.indexOf(item.key) !== -1 }); if(filterErrors && filterErrors.length > 0) { errorCode = filterErrors[0].key; } } let navigationExtras: NavigationExtras; if(this.wcsLoginFailed){ navigationExtras = { queryParams: {errorCode: errorCode, inputData: this.inputData } }; }else{ navigationExtras = { queryParams: {errorCode: errorCode} }; } this.router.navigate(['login/prohibited'], navigationExtras); } async oktaLogin() { await this.oktaAuth.loginRedirect('/login'); } async logout() { // Terminates the session with Okta and removes current tokens. await this.oktaAuth.logout(); this.router.navigateByUrl('/'); } }