import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router'; import {Observable} from 'rxjs/Observable'; import {Session} from './utils/helper.class'; import {LoginErrorCodes} from './utils/guardHelper.class'; import {catchError, filter, map, mergeMap} from "rxjs/operators"; import {UserManagementService} from "../services/user-management.service"; import {UserRegistryService} from "../services/user-registry.service"; import {of} from "rxjs"; import {properties} from "../../../environments/environment"; import {ConnectHelper} from "../connect/connectHelper"; @Injectable() export class VerificationGuard implements CanActivate { constructor(private router: Router, private userRegistryService: UserRegistryService, private userManagementService: UserManagementService) { } check(path: string, id: string, type: string, entity: string): Observable | boolean { if (Session.isLoggedIn()) { return this.userManagementService.getUserInfo(false).pipe(map(user => { if(user) { if(id) { return this.userRegistryService.getInvitation(id).pipe(map(invitation => { if(invitation.type !== type || invitation.entity !== entity) { this.router.navigate(['/error'], {queryParams: {'page': path}}); return false; } else { return true; } }), catchError(error => { if(error.status === 404) { this.router.navigate(['/error'], {queryParams: {'page': path}}); } else { this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_AUTHORIZED, 'redirectUrl': path}}); } return of(false); })); } else { this.router.navigate(['/error'], {queryParams: {'page': path}}); return of(false); } } else { this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_LOGIN, 'redirectUrl': path}}); return of(false); } }), mergeMap(authorized => { return authorized; })); } else { this.router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_LOGIN,'redirectUrl': path}}); return false; } } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | boolean { if(properties.dashboard === "connect" && properties.environment === 'development') { let communityId = ConnectHelper.getCommunityFromDomain(properties.domain); communityId = (communityId)?communityId:route.queryParams['communityId']; return this.check(state.url, route.params.id, 'community', communityId); } else { return false; } } }