openaire-library/connect/communityGuard/connectSubscriber.guard.ts

51 lines
2.2 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@angular/core';
import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanLoad, Route} from '@angular/router';
import {Observable} from 'rxjs/Observable';
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';
@Injectable()
export class ConnectSubscriberGuard implements CanActivate, CanLoad {
constructor(private router: Router,
private communityService: CommunityService,
private propertiesService: EnvironmentSpecificService) {}
check(community: string, path: string): Observable<boolean> | boolean {
let errorCode = LoginErrorCodes.NOT_SUBSCRIBER;
if (!Session.isLoggedIn()) {
errorCode = LoginErrorCodes.NOT_LOGIN;
this.router.navigate(['/user-info'], {queryParams: {'errorCode': errorCode, 'redirectUrl': path, communityId:community}});
return false;
} else {
const obs = this.propertiesService.subscribeEnvironment().mergeMap(properties => {
if(!community){
community = ConnectHelper.getCommunityFromDomain(properties.domain);
}
return this.communityService.isSubscribedToCommunity( community, Session.getUserEmail(), properties["adminToolsAPIURL"])
});
obs.filter(enabled => !enabled)
.subscribe(() => this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': errorCode,
'redirectUrl': path,
communityId:community
}
}));
return obs;
}
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.check(route.queryParams['communityId'], state.url);
}
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
const path = '/' + route.path + document.location.search;
return this.check(ConnectHelper.getCommunityFromPath(path), path);
}
}