1

In my Angular app has 3 types of users: admin, brewer (vendor) & end user. I want to prevent brewer from accessing admin routes, just as end users should be prevented from accessing admin routes and vendor route.

How I can achieve this through angular routing.

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  {
    path: 'home', component: HomeContentComponent,
  },
  { path: 'auth', loadChildren: './modules/auth/auth.module#AuthModule' },
  {
    path: 'admin',
    loadChildren: './modules/admin/admin.module#AdminModule',
    canActivate: [AuthGuard],
  },
  {
    path: 'vendor',
    loadChildren: './modules/vendor/vendor.module#VendoreModule',
    canActivate: [AuthGuard],
  },
  {
    path: 'user',
    loadChildren: './modules/user/user.module#UserModule',
    canActivate: [AuthGuard],
  }
]

Auth Guard :

import { Injectable } from "@angular/core";
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router,
  CanDeactivate,
} from "@angular/router";
import { Observable } from "rxjs";
import { AuthService } from "../services/firebase/auth.service";

@Injectable({ providedIn: "root" })
export class AuthGuard implements CanActivate {
  constructor(public authService: AuthService, public router: Router) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    // Guard for userRole is login or not
    // var Role=localStorage.getItem('role')
    let user = localStorage.getItem('toke');
    if (!user) {
      this.router.navigate(["/auth/login"]);
      return true;
    }
    return true;
  }
}

I have auth guard like this how I can modify it to achieve desired functionality.

It would be greatly appreciated if anyone could help.

konowo7640
  • 23
  • 1
  • 6
  • 2
    In the `canActivate` property of a route, you can pass in multiple guards. Create the guards that you need and put them in the array, next to the `AuthGuard`. If you have already implemented the guards for vendor and normal user and they don't work as you expect them to, then include those in the body of your question. – Octavian Mărculescu Apr 14 '22 at 10:11
  • 1
    Does this answer your question? [Pass parameter into route guard](https://stackoverflow.com/questions/42719445/pass-parameter-into-route-guard) – MaisOuEtDoncOrNiCar Apr 14 '22 at 10:20
  • 2
    Follow this https://www.geekstrick.com/angular-10-secure-routes-using-authguard-based-on-user-role/ – Abhishek Apr 14 '22 at 10:35
  • Hey @Abhishek you're correct but marked solution seems easy to me that's why I choose that. Thanks for helping me. – konowo7640 Apr 15 '22 at 04:49
  • @konowo7640 there's easy and there's right. Picking easy will not get you far. – AsGoodAsItGets Mar 15 '23 at 10:19

2 Answers2

1

I have achieved this by using logic,

You can use logic like in your app.component.ts

import { Router, NavigationEnd } from '@angular/router';
    
export class AppComponent implements OnInit {
      constructor(
        private router: Router,
      ) {
        this.router.events.subscribe((ev) => {
          if (ev instanceof NavigationEnd) {
    
            const user = localStorage.getItem("Id");
            const Role = localStorage.getItem('UserRole')
            if (user && Role && Role === 'User' && ev.url.includes('/admin)) {
                this.router.navigate(['user/home']);
          }
        }
      }

Similarly for your all roles you can define if condition and can redirect on their main route lets if user then user's default page, if super admin then it might be admin/dashboard anything like this.

Second way:

Another way to achieve this is to use ngx-permissions using which you can control your route based on role.

attaching stackblitz demo for more clarification.

Official doc

NPM Package

Manish Patidar
  • 526
  • 4
  • 14
  • This is **NOT** the proper way to do it (and should not be the accepted answer). The proper way is to use Guards. That's exactly what they're there for. – AsGoodAsItGets Mar 15 '23 at 10:18
0

you can do it with multiple if else condition

const Role = localStorage.getItem('role')
if(Role != "admin"){
    this.router.navigate(["/auth/login"]);
}