Home > Back-end >  How to restrict user to access unauthorized path in angular
How to restrict user to access unauthorized path in angular

Time:04-14

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.

CodePudding user response:

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

CodePudding user response:

you can do it with multiple if else condition

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