src/app/guards/sso.guard.ts
Properties |
token |
token:
|
Type : string
|
Defined in src/app/guards/sso.guard.ts:14
|
import { LoaderStore } from './../stores/loader.store';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { JwtHelperService } from '@auth0/angular-jwt';
import { JWT_KEY } from '../app.constants';
import { IJwt } from '../models/i-jwt.model';
import { StorageService } from '../services';
import { AuthService } from '../services/auth.service';
import { ErrorStore, SessionStore } from '../stores';
import { Session } from '../models';
import { map, first } from 'rxjs/operators';
interface IHaveToken {
token: string;
}
@Injectable()
export class SsoGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService,
private helper: JwtHelperService,
private sessionStore: SessionStore,
private storage: StorageService,
private errors: ErrorStore,
private loader: LoaderStore
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.loader.show();
console.log('sso guard activated');
const params = route.queryParams as IHaveToken;
if (!this.hasToken(params.token) || this.helper.isTokenExpired(params.token)) {
return true;
}
if (this.authService.authenticated) {
console.log('sso guard authenticated: clear current session');
this.storage.delete(JWT_KEY);
this.sessionStore.clearSession();
}
this.storage.set(JWT_KEY, params.token);
const jwt = this.helper.decodeToken(params.token) as IJwt;
this.sessionStore.createSession(jwt);
return this.sessionStore.session$.pipe(
first((session) => !!session && !!session.accounts),
map((session) => {
if (!this.hasContactMethods(session)) {
return this.showContactMethodError();
}
return this.goToStart();
})
);
}
private showContactMethodError() {
this.errors.addError(
'You are missing the necessary contact information to use this feature.',
'Please contact your financial institution.'
);
this.errors.displayErrors();
return false;
}
private hasContactMethods(session: Session): boolean {
if (session.email.length === 0 && session.phones.length === 0) {
return false;
}
return true;
}
private goToStart(): boolean {
this.router.navigate(['/']);
return false;
}
private hasToken(token: string): boolean {
return token !== null && token !== undefined && token.length > 0;
}
}