Project

General

Profile

1
import {map, filter, mergeMap} from 'rxjs/operators';
2
import {Injectable} from '@angular/core';
3
import {
4
  Router,
5
  CanActivate,
6
  ActivatedRouteSnapshot,
7
  RouterStateSnapshot,
8
  CanLoad, Route, UrlSegment
9
} from '@angular/router';
10
import {Observable, of} from 'rxjs';
11
import {Session} from '../../login/utils/helper.class';
12
import {LoginErrorCodes} from '../../login/utils/guardHelper.class';
13
import {CommunityService} from '../community/community.service';
14
import {EnvironmentSpecificService} from '../../utils/properties/environment-specific.service';
15
import {ConnectHelper} from '../connectHelper';
16
import {StringUtils} from '../../utils/string-utils.class';
17
import {UserManagementService} from "../../services/user-management.service";
18

    
19
@Injectable()
20
export class ConnectAdminLoginGuard implements CanActivate, CanLoad {
21
  constructor(private router: Router,
22
              private communityService: CommunityService,
23
              private propertiesService: EnvironmentSpecificService,
24
              private userManagementService: UserManagementService) {
25
  }
26

    
27
  check(community: string, path: string): Observable<boolean> | boolean {
28
    let errorCode = LoginErrorCodes.NOT_LOGIN;
29
    let email = null;
30
    const authorized = this.propertiesService.subscribeEnvironment().pipe(map(res => res), mergeMap(properties => {
31
      return this.userManagementService.getUserInfo(properties.userInfoUrl).pipe(map(user => {
32
        if (user) {
33
          email = user.email;
34
          if (Session.isPortalAdministrator(user) || Session.isCommunityCurator(user)) {
35
            return of(true);
36
          } else {
37
            errorCode = LoginErrorCodes.NOT_ADMIN;
38
            return this.communityService.isCommunityManager(properties, properties['communityAPI'] + community,
39
              email);
40
          }
41
        } else {
42
          return of(false);
43
        }
44
      }), mergeMap( authorized => {
45
        return authorized;
46
      }));
47
    }));
48
    authorized.pipe(filter(authorized => !authorized)).subscribe(() => {
49
      this.router.navigate(['/user-info'], {
50
        queryParams: {
51
          'errorCode': errorCode,
52
          'redirectUrl': path
53
        }
54
    })});
55
    return authorized;
56
  }
57

    
58
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
59
    return this.check(route.queryParams['communityId'], state.url);
60
  }
61

    
62
  canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
63
    const path = StringUtils.URLSegmentsToPath(segments) + document.location.search;
64
    return this.check(ConnectHelper.getCommunityFromPath(path), path);
65
  }
66
}
(3-3/8)