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

79 lines
2.8 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, Subscription} 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";
import {properties} from "../../../../environments/environment";
@Injectable()
export class ConnectAdminLoginGuard implements CanActivate, CanLoad {
sub: Subscription = null;
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(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.isCommunityManagerByState(properties, properties['communityAPI'] + community,
email);
}
} else {
return of(false);
}
}), mergeMap( authorized => {
return authorized;
}));
//}));
this.sub = 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);
}
canDeactivate() {
if(this.sub) {
this.sub.unsubscribe();
}
return true;
}
}