| kumaran.m | 3b4814a | 2020-05-01 19:48:54 +0530 | [diff] [blame] | 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 { Observable } from 'rxjs'; |
| 26 | import { map, take } 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 | export class AuthGuardService implements CanActivate { |
| 34 | /** Holds teh instance of AuthService class of type AuthService @private */ |
| 35 | private router: Router; |
| 36 | /** Holds teh instance of Router class of type Router @private */ |
| 37 | private authService: AuthenticationService; |
| 38 | |
| 39 | constructor(router: Router, authService: AuthenticationService) { |
| 40 | this.router = router; |
| 41 | this.authService = authService; |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Returns Observable<boolean> if authorized @public |
| 46 | */ |
| 47 | public canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { |
| 48 | return this.authService.isLoggedIn |
| 49 | .pipe( |
| 50 | take(1), |
| 51 | map((isLoggedIn: boolean) => { |
| 52 | if (!isLoggedIn) { |
| 53 | this.router.navigate(['/login']).catch(() => { |
| 54 | //TODO: Handle error notification |
| 55 | }); |
| 56 | } |
| 57 | return true; |
| 58 | }) |
| 59 | ); |
| 60 | } |
| 61 | } |