3e0ef8f78d4837edc2ba06c8f142fa179f28a301
[osm/NG-UI.git] / src / services / AuthGuardService.ts
1 /*
2  Copyright 2020 TATA ELXSI
3
4  Licensed under the Apache License, Version 2.0 (the 'License');
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15
16  Author: KUMARAN M (kumaran.m@tataelxsi.co.in), RAJESH S (rajesh.s@tataelxsi.co.in), BARATH KUMAR R (barath.r@tataelxsi.co.in)
17  */
18
19 /**
20  * @file Auth gaurd
21  */
22 import { Injectable } from '@angular/core';
23 import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
24 import { AuthenticationService } from 'AuthenticationService';
25 import { combineLatest, Observable } from 'rxjs';
26 import { map } from 'rxjs/operators';
27
28 /**
29  * An Injectable is a class adorned with the @Injectable decorator function.
30  * @Injectable takes a metadata object that tells Angular how to compile and run module code
31  */
32 @Injectable()
33 // eslint-disable-next-line deprecation/deprecation
34 export class AuthGuardService implements CanActivate {
35     /** Holds teh instance of AuthService class of type AuthService @private */
36     private router: Router;
37     /** Holds teh instance of Router class of type Router @private */
38     private authService: AuthenticationService;
39
40     constructor(router: Router, authService: AuthenticationService) {
41         this.router = router;
42         this.authService = authService;
43     }
44
45     /**
46      * Returns Observable<boolean> if authorized @public
47      */
48     public canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
49         // eslint-disable-next-line deprecation/deprecation
50         return combineLatest(
51             this.authService.isLoggedIn,
52             this.authService.isChangePassword
53         ).pipe(
54             map(([isLoggedIn, changePassword]: [boolean, boolean]): boolean => {
55                 if (changePassword || isLoggedIn) {
56                     return true;
57                 } else {
58                     this.router.navigate(['/login']).catch((): void => {
59                         // Catch Navigation Error
60                     });
61                     this.authService.destoryToken();
62                     return false;
63                 }
64             })
65         );
66     }
67 }