openaire-library/login/loginGuard.guard.ts

53 lines
1.5 KiB
TypeScript
Raw Normal View History

import {Injectable} from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
CanActivateChild,
CanLoad,
Route,
Router,
RouterStateSnapshot,
UrlTree
} from '@angular/router';
import {Observable} from 'rxjs';
import {LoginErrorCodes} from './utils/guardHelper.class';
import {map, tap} from "rxjs/operators";
import {UserManagementService} from "../services/user-management.service";
@Injectable({
providedIn: 'root'
})
export class LoginGuard implements CanActivate, CanLoad, CanActivateChild {
constructor(private router: Router,
private userManagementService: UserManagementService) {
}
check(path: string): Observable<boolean> | boolean {
return this.userManagementService.getUserInfo().pipe(map(user => {
return user !== null;
}),tap(isLoggedIn => {
if(!isLoggedIn) {
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_LOGIN,
'redirectUrl': path
}
});
}
}));
}
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);
}
}