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

60 lines
2.4 KiB
TypeScript

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";
import {SubscribeService} from "../../utils/subscribe/subscribe.service";
import {properties} from "../../../../environments/environment";
@Injectable()
export class ConnectSubscriberGuard implements CanActivate {
constructor(private router: Router,
private communityService: CommunityService,
private subscribeService: SubscribeService,
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.userManagementService.getUserInfo(false).pipe(map(user => {
if (user) {
errorCode = LoginErrorCodes.NOT_SUBSCRIBER;
email = user.email;
let communityDomain = ConnectHelper.getCommunityFromDomain(properties.domain);
if (communityDomain) {
community = communityDomain;
}
if (Session.isSubscribedTo('community', community, user)) {
return of(true);
}
return this.subscribeService.isSubscribedToCommunity(properties, community)
} 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);
}
}