openaire-library/login/loginGuard.guard.ts

56 lines
1.8 KiB
TypeScript

import {Injectable} from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
CanActivateChild,
CanLoad,
Route,
Router,
RouterStateSnapshot, UrlTree
} from '@angular/router';
import {Observable} from 'rxjs';
import {Session} from './utils/helper.class';
import {LoginErrorCodes} from './utils/guardHelper.class';
import {map, tap} from "rxjs/operators";
import {UserManagementService} from "../services/user-management.service";
@Injectable()
export class LoginGuard implements CanActivate, CanLoad, CanActivateChild {
constructor(private router: Router,
private userManagementService: UserManagementService) {
}
check(path: string): Observable<boolean> | boolean {
if (Session.isLoggedIn()) {
return this.userManagementService.getUserInfo(false).pipe(map(user => {
return user !== null;
}),tap(isLoggedIn => {
if(!isLoggedIn) {
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_LOGIN,
'redirectUrl': path
}
});
}
}));
} else {
this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_LOGIN, 'redirectUrl':path}});
return false;
}
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.check(state.url);
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.check(state.url);
}
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
return this.check('/' + route.path);
}
}