简体   繁体   中英

How to guard route by user role ? Angular

I need to make a role base guard.

If the user has activeType = 0 he can access certain routes. If the user has activeType = 1 he can access other routes.

I already have one guard for routes but if you are logged in or not and I need to add this one for another guard but how?

    userData: User;
      authData: AuthData;
      constructor(private router: Router, 
                  private userService: UserService,
                  private location: Location) {
      }
    
      canActivate() {
        const userData = JSON.parse(localStorage.getItem("userData"));
        const authData = JSON.parse(localStorage.getItem("authData"));
        const route = this.location.path();
        if (!userData && !authData) {
          return true;
        } else {
          if (route == '/login'  || route === '/register') {
            this.location.back();
            return false;
          } else {
            return true;
          }
        }
      }
    
      canLoad() {
        const userData = JSON.parse(localStorage.getItem("userData"));
        const authData = JSON.parse(localStorage.getItem("authData"));
        if (userData && authData) {
          // logged in so return true
          return true;
        }
    
        // not logged in so redirect to login page with the return url
        this.userService.logout();
        this.router.navigate(["/login"]);
        return false;
      }

    const routes: Routes = [
      {
        path: "route-for-user-activeType-1",
        loadChildren: () =>
          import("./one/one.module").then(
            (m) => m.OneModule
          ),
        canLoad: [AuthGuard]
      },
      {
        path: "route-for-user-activeType-0",
        loadChildren: () =>
          import("./two/two.module").then((m) => m.twoModule),
          canActivate: [AuthGuard]
      },
      {
        path: "route-path-for-user-activeType-1",
        loadChildren: () =>
          import("./test/test.module").then((m) => m.testModule),
          canActivate: [AuthGuard]
      }
    ]

We will provide the Routes object with information about the role. This process is simple. All you have to do is add a guard and add your data to the role.

Adding guard like below,

canActivate: [AuthGuard]

You can give the role information that will access that page like below,

data: {
          role: 'ROLE_ADMIN'
     }`

So routing-module.ts should be like this.

 {
    path: 'admin', component: AdminDashboardComponent,
    canActivate: [AuthGuard],
    data: {
      role: 'ROLE_ADMIN'
    }
  }

Created an Auth service that provides information about the user's login status and roles. I don't have any integration about jwt token implementation. This is just a simple simulation for login and getting roles.

@Injectable({
      providedIn: 'root'
    })
    export class AuthService {
      isLogin = false;
    
      roleAs: string;
    
      constructor() { }
    
      login(value: string) {
        this.isLogin = true;
        this.roleAs = value;
        localStorage.setItem('STATE', 'true');
        localStorage.setItem('ROLE', this.roleAs);
        return of({ success: this.isLogin, role: this.roleAs });
      }
    
      logout() {
        this.isLogin = false;
        this.roleAs = '';
        localStorage.setItem('STATE', 'false');
        localStorage.setItem('ROLE', '');
        return of({ success: this.isLogin, role: '' });
      }
    
      isLoggedIn() {
        const loggedIn = localStorage.getItem('STATE');
        if (loggedIn == 'true')
          this.isLogin = true;
        else
          this.isLogin = false;
        return this.isLogin;
      }
    
      getRole() {
        this.roleAs = localStorage.getItem('ROLE');
        return this.roleAs;
      }
    
    }

AuthGuard.ts should be

@Injectable({
      providedIn: 'root'
    })
    export class AuthGuard implements CanActivate, CanActivateChild, CanDeactivate<unknown>, CanLoad {
    
    
      constructor(private authService: AuthService, private router: Router) { }
    
      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        let url: string = state.url;
        return this.checkUserLogin(next, url);
      }
      canActivateChild(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        return this.canActivate(next, state);
      }
      canDeactivate(
        component: unknown,
        currentRoute: ActivatedRouteSnapshot,
        currentState: RouterStateSnapshot,
        nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        return true;
      }
      canLoad(
        route: Route,
        segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
        return true;
      }
    
      checkUserLogin(route: ActivatedRouteSnapshot, url: any): boolean {
        if (this.authService.isLoggedIn()) {
          const userRole = this.authService.getRole();
          if (route.data.role && route.data.role.indexOf(userRole) === -1) {
            this.router.navigate(['/home']);
            return false;
          }
          return true;
        }
    
        this.router.navigate(['/home']);
        return false;
      }
    }

Hope this answer helps

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