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

67 lines
2.6 KiB
TypeScript

import {map, filter, mergeMap} from 'rxjs/operators';
import {Injectable} from '@angular/core';
import {
Router,
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
CanLoad, Route, UrlSegment
} from '@angular/router';
import {Observable, of} from 'rxjs';
import {Session} from '../../login/utils/helper.class';
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
import {CommunityService} from '../community/community.service';
import {EnvironmentSpecificService} from '../../utils/properties/environment-specific.service';
import {ConnectHelper} from '../connectHelper';
import {StringUtils} from '../../utils/string-utils.class';
import {UserManagementService} from "../../services/user-management.service";
@Injectable()
export class ConnectAdminLoginGuard implements CanActivate, CanLoad {
constructor(private router: Router,
private communityService: CommunityService,
private propertiesService: EnvironmentSpecificService,
private userManagementService: UserManagementService) {
}
check(community: string, path: string): Observable<boolean> | boolean {
let errorCode = LoginErrorCodes.NOT_LOGIN;
let email = null;
const authorized = this.propertiesService.subscribeEnvironment().pipe(map(res => res), mergeMap(properties => {
return this.userManagementService.getUserInfo(false).pipe(map(user => {
if (user) {
email = user.email;
if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user)) {
return of(true);
} else {
errorCode = LoginErrorCodes.NOT_ADMIN;
return this.communityService.isCommunityManager(properties, properties['communityAPI'] + community,
email);
}
} else {
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> | boolean {
return this.check(route.queryParams['communityId'], state.url);
}
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
const path = StringUtils.URLSegmentsToPath(segments) + document.location.search;
return this.check(ConnectHelper.getCommunityFromPath(path), path);
}
}