简体   繁体   中英

How to return true value dynamically in AuthGuard?

I have an auth guard with multiple condition and I want to return true value dynamically. How can I do that? Below is my code

auth.guard.ts

canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean {
    const isSuperAdmin = this.authService.getAuth().role === 'SUPERADMIN';
    const isAdmin = this.authService.getAuth().role === 'ADMIN';
    if (!isAdmin || !isSuperAdmin) {
      this.router.navigate(['/notifications']);
    }
    return true;  //how can I return true dynamically?
}

you can define a boolean variable and change it accordingly:

like this:

    canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean {

        let dynamicReturn = false;

          const isSuperAdmin = this.authService.getAuth().role === 'SUPERADMIN';
            const isAdmin = this.authService.getAuth().role === 'ADMIN';
            if (!isAdmin || !isSuperAdmin) {

              //change dynamicReturn value accordingly
              dynamicReturn = true
              this.router.navigate(['/notifications']);
            }
            return dynamicReturn ;  //how can I return true dynamically?
        }

I suggest its not [AuthGuard] call it as [AuthorizeGuard] since you are dealing with Application user roles.

you can use something similar like this

import { Injectable } from '@angular/core';
import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthorizationService } from './authorization.service';
@Injectable({
    providedIn: 'root'
})
export class AuthorizeGuard implements CanActivateChild {


    constructor(private authorizeService: AuthorizationService, private router: Router) {
    }
    canActivateChild(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {

        if (this.hasPermissions(route.data.roles)) {
            return true;
        } else {
            this.router.navigate(['/']);
        }
    }

    private hasPermissions(allowedRoles: string[]): boolean {
        const idxArray: number[] = [];
        allowedRoles.forEach((role: string) => {
            const idx: number = this.authorizeService.permissions.indexOf(role);
            if (idx !== -1) {
                idxArray.push(idx);
            }
        });
        if (idxArray.length > 0) {
            return true;
        } else {
            return false;
        }
    }


}

AuthorizationService is using for retrieve login user permissions from API.in my scenario its an Array list.

If login user doesn't have required permission from the array its throw Boolean false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM