1
|
import {Injectable} from '@angular/core';
|
2
|
import {
|
3
|
ActivatedRouteSnapshot,
|
4
|
CanActivate,
|
5
|
CanActivateChild,
|
6
|
CanLoad,
|
7
|
Route,
|
8
|
Router,
|
9
|
RouterStateSnapshot, UrlTree
|
10
|
} from '@angular/router';
|
11
|
import {Observable} from 'rxjs';
|
12
|
import {Session} from './utils/helper.class';
|
13
|
import {LoginErrorCodes} from './utils/guardHelper.class';
|
14
|
import {map, tap} from "rxjs/operators";
|
15
|
import {UserManagementService} from "../services/user-management.service";
|
16
|
|
17
|
@Injectable()
|
18
|
export class LoginGuard implements CanActivate, CanLoad, CanActivateChild {
|
19
|
|
20
|
constructor(private router: Router,
|
21
|
private userManagementService: UserManagementService) {
|
22
|
}
|
23
|
|
24
|
check(path: string): Observable<boolean> | boolean {
|
25
|
if (Session.isLoggedIn()) {
|
26
|
return this.userManagementService.getUserInfo(false).pipe(map(user => {
|
27
|
return user !== null;
|
28
|
}),tap(isLoggedIn => {
|
29
|
if(!isLoggedIn) {
|
30
|
this.router.navigate(['/user-info'], {
|
31
|
queryParams: {
|
32
|
'errorCode': LoginErrorCodes.NOT_LOGIN,
|
33
|
'redirectUrl': path
|
34
|
}
|
35
|
});
|
36
|
}
|
37
|
}));
|
38
|
} else {
|
39
|
this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_LOGIN, 'redirectUrl':path}});
|
40
|
return false;
|
41
|
}
|
42
|
}
|
43
|
|
44
|
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
|
45
|
return this.check(state.url);
|
46
|
}
|
47
|
|
48
|
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
|
49
|
return this.check(state.url);
|
50
|
}
|
51
|
|
52
|
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
|
53
|
return this.check('/' + route.path);
|
54
|
}
|
55
|
}
|