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

55 lines
2.3 KiB
TypeScript
Raw Normal View History

import {filter, map, mergeMap} from 'rxjs/operators';
import { Injectable } from '@angular/core';
import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanLoad, Route} 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 {UserManagementService} from "../../services/user-management.service";
@Injectable()
export class ConnectSubscriberGuard implements CanActivate {
constructor(private router: Router,
private communityService: CommunityService,
private userManagementService: UserManagementService,
private propertiesService: EnvironmentSpecificService) {}
check(community: string, path: string): Observable<boolean> | boolean {
let errorCode = LoginErrorCodes.NOT_LOGIN;
let email = null;
const subscribed = this.propertiesService.subscribeEnvironment().pipe(map(res => res), mergeMap(properties => {
return typeof document !== 'undefined' && this.userManagementService.getUserInfo(properties.userInfoUrl).pipe(map(user => {
if (user) {
errorCode = LoginErrorCodes.NOT_SUBSCRIBER;
email = user.email;
let communityDomain = ConnectHelper.getCommunityFromDomain(properties.domain);
if(communityDomain) {
community = communityDomain;
}
return this.communityService.isSubscribedToCommunity( community, email, properties["adminToolsAPIURL"])
} else {
return of(false);
}
}), mergeMap( authorized => {
return authorized;
}));
}));
subscribed.pipe(filter(subscribed => !subscribed)).subscribe(() => {
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': errorCode,
'redirectUrl': path
}
})});
return subscribed;
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.check(route.queryParams['communityId'], state.url);
}
}