| /******************************************************************************** |
| * Copyright (c) 2020 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0 |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ********************************************************************************/ |
| |
| import {Injectable} from "@angular/core"; |
| import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from "@angular/router"; |
| import {select, Store} from "@ngrx/store"; |
| import {Observable} from "rxjs"; |
| import {filter, map, switchMap} from "rxjs/operators"; |
| import {EAPIUserRoles} from "../../../core/api/core"; |
| import {arrayJoin} from "../../../util/store"; |
| import {isLoadingSelector, userRolesSelector} from "../selectors"; |
| |
| export interface IUserRoleRouteGuardConfiguration { |
| |
| allowed: EAPIUserRoles[]; |
| |
| } |
| |
| export abstract class UserRoleRouteGuardService implements CanActivate { |
| |
| public redirectUrlTree: UrlTree = this.router.createUrlTree(["/"]); |
| |
| public isInitialized$ = this.store.pipe( |
| select(isLoadingSelector), |
| filter((isLoading) => !isLoading) |
| ); |
| |
| public isAllowed$ = this.store.pipe( |
| select(userRolesSelector), |
| map((userRoles) => arrayJoin(userRoles).some((role) => this.isUserRoleAllowed(role))) |
| ); |
| |
| protected constructor( |
| public store: Store, |
| public router: Router, |
| public config: IUserRoleRouteGuardConfiguration |
| ) { |
| |
| } |
| |
| public isUserRoleAllowed(role: EAPIUserRoles): boolean { |
| return arrayJoin(this.config?.allowed).indexOf(role) > -1; |
| } |
| |
| public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> { |
| return this.isInitialized$.pipe( |
| switchMap(() => this.isAllowed$), |
| map((isAllowed) => isAllowed ? isAllowed : this.redirectUrlTree) |
| ); |
| } |
| |
| } |
| |
| |
| @Injectable({providedIn: "root"}) |
| export class OfficialInChargeRouteGuardService extends UserRoleRouteGuardService { |
| |
| public constructor(store: Store, router: Router) { |
| super(store, router, {allowed: [EAPIUserRoles.SPA_OFFICIAL_IN_CHARGE]}); |
| } |
| |
| } |
| |
| @Injectable({providedIn: "root"}) |
| export class OfficialInChargeOrAdminRouteGuardService extends UserRoleRouteGuardService { |
| |
| public constructor(store: Store, router: Router) { |
| super(store, router, {allowed: [EAPIUserRoles.SPA_OFFICIAL_IN_CHARGE, EAPIUserRoles.SPA_ADMIN]}); |
| } |
| |
| } |