import { Injectable } from '@angular/core'; import { Location } from '@angular/common'; import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { CanActivate } from '@angular/router'; import { UserService } from './user.service'; import { AuthService } from './auth.service'; import { environment } from './../../environments/environment'; import { AppStorageService } from './../common/app-storage.service'; import { AppConstants } from './../../common/AppConstants'; @Injectable() export class RouteGuard implements CanActivate { constructor(private userService: UserService, private authService: AuthService, private appStorageService: AppStorageService) { } getAuthURLWithoutHistory(): string { const state = this.generateState(); if (!location.hash) { this.appStorageService.set(AppConstants.ReturnUrl, '/'); } const locale = this.appStorageService.get(AppConstants.LOCALE); const authURL = this.authService.getAuthorizeUrl(locale.toString(), state); console.log('Auth URL ', authURL); return authURL; } getAuthURL(): string { const state = this.generateState(); if (location.hash && location.hash !== '#/' && location.hash !== '#') { const url = location.href ? location.href : '/'; this.appStorageService.set(AppConstants.ReturnUrl, url); console.log('Setting Return URL to ', url); } const locale = this.appStorageService.get(AppConstants.LOCALE); const authURL = this.authService.getAuthorizeUrl(locale.toString(), state); console.log('Auth URL ', authURL); return authURL; } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (environment.envName !== 'test') { if (!this.userService.isAuthenticated) { location.assign(this.getAuthURL()); } else { return true; } } else if (environment.envName === 'test' && this.userService.isAuthenticated) { return true; } } private generateState(): string { const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const length = 5; let result = ''; for (let i = length; i > 0; --i) { result += chars[Math.round(Math.random() * (chars.length - 1))]; } return result; } }