Project

General

Profile

1
import {Injectable} from '@angular/core';
2
import {ActivatedRouteSnapshot, CanActivate, CanLoad, Route, Router, RouterStateSnapshot} from '@angular/router';
3
import {Observable} from 'rxjs/Observable';
4
import {Session} from './utils/helper.class';
5
import {LoginErrorCodes} from './utils/guardHelper.class';
6
import {map, tap} from "rxjs/operators";
7
import {UserManagementService} from "../services/user-management.service";
8

    
9
@Injectable()
10
export class LoginGuard implements CanActivate, CanLoad {
11
  
12
  constructor(private router: Router,
13
              private userManagementService: UserManagementService) {
14
  }
15
  
16
  check(path: string): Observable<boolean> | boolean {
17
    if (Session.isLoggedIn()) {
18
      return this.userManagementService.getUserInfo(false).pipe(map(user => {
19
        return user !== null;
20
      }),tap(isLoggedIn => {
21
        if(!isLoggedIn) {
22
          this.router.navigate(['/user-info'], {
23
            queryParams: {
24
              'errorCode': LoginErrorCodes.NOT_LOGIN,
25
              'redirectUrl': path
26
            }
27
          });
28
        }
29
      }));
30
    } else {
31
      this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_LOGIN, 'redirectUrl':path}});
32
      return false;
33
    }
34
  }
35
  
36
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
37
    return this.check(state.url);
38
  }
39
  
40
  canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
41
    return this.check('/' + route.path);
42
  }
43
}
(4-4/11)