openaire-library/login/loginGuard.guard.ts

39 lines
1.4 KiB
TypeScript

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