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

50 lines
1.7 KiB
TypeScript

import {filter, map, mergeMap, take} from 'rxjs/operators';
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {Observable, of} from 'rxjs';
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
import {properties} from "../../../../environments/environment";
import {ConnectHelper} from "../connectHelper";
import {Session} from "../../login/utils/helper.class";
import {UserManagementService} from "../../services/user-management.service";
@Injectable()
export class ConnectSubscriberGuard implements CanActivate {
constructor(private router: Router,
private userManagementService: UserManagementService) {
}
check(community: string, path: string): Observable<boolean> {
let errorCode = LoginErrorCodes.NOT_SUBSCRIBER;
let communityDomain = ConnectHelper.getCommunityFromDomain(properties.domain);
if (communityDomain) {
community = communityDomain;
}
const authorized = this.userManagementService.getUserInfo(false).pipe(take(1), map(user => {
if (user) {
if (Session.isSubscribedTo('community', community, user)) {
return of(true);
}
}
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);
}
}