openaire-library/connect/communityGuard/connectAdminLoginGuard.guar...

54 lines
1.9 KiB
TypeScript

import {filter, map, mergeMap, take} from 'rxjs/operators';
import {Injectable} from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
CanActivateChild,
Router,
RouterStateSnapshot,
UrlTree
} from '@angular/router';
import {Observable, of} from 'rxjs';
import {Session} from '../../login/utils/helper.class';
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
import {UserManagementService} from "../../services/user-management.service";
@Injectable()
export class ConnectAdminLoginGuard implements CanActivate, CanActivateChild {
constructor(private router: Router,
private userManagementService: UserManagementService) {
}
check(community: string, path: string): Observable<boolean> | boolean {
let errorCode = LoginErrorCodes.NOT_LOGIN;
const authorized = this.userManagementService.getUserInfo().pipe(take(1), map(user => {
if (user) {
if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user) || Session.isManager('community', community, user)) {
return of(true);
}
}
return of(false);
}), mergeMap(authorized => {
return authorized;
}));
authorized.pipe(filter(authorized => !authorized)).subscribe(() => {
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': errorCode,
'redirectUrl': path
}
})
});
return authorized;
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.check(route.params['community'], state.url);
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.check(childRoute.params['community'], state.url);
}
}