简体   繁体   中英

How to manage menu based on user roles/permissions in angular

I have started a new angular project, In my application have 3 types of users (admin, customer, and company). How can restrict customers from access admin users menus?

You should implement the ActivatedRoute interface to restrict navigation to a specific URL/resource, Read more

I like to keep my menu voices on a database. This gives me safer server controls, handling permissions for user levels allowing/denying actions. If you are only interested in the client side, you can simply add a variable on your routing module:

{ path: 'profile/:user_level', component: ProfileComponent }

Then you can implement the differences inside your components. How to ensure that a user can see only contents for his level? Just implement a control that checks if the session user is trying to see a content that's not for him. (Example inside ProfileComponent)

this.user_level= + params['user_level'];
this.utilityService.checkUserLevel(this.user_level);

UtilityService:

 checkUserLevel(url_liv_serial: number) {
    let utente: Utente = JSON.parse(localStorage.getItem('currentUser'));


    if (url_liv_serial < utente.ute_liv_serial) {
        this.router.navigate(['/login']);
        let snackBarRef = this.snackBar.open('Access denied', 'Close', {
            duration: Constants.short_time_sb
        });
    }
}

You can use ngx-permissions library. It support lazy loading, isolated lazy loading, then else syntax. Load library

@NgModule({

 imports: [

 NgxPermissionsModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})

Load roles

this.ngxRolesService.addRole('GUEST', () => {
  return true;
}); 

Secure root

const appRoutes: Routes = [
{ path: 'home',
    component: HomeComponent,
    canActivate: [NgxPermissionsGuard],
    data: {
      permissions: {
        only: 'GUEST'
      }
    }
  },
];

Detailed documentation you can find on WIKI page

You should do two things: 1. Secure your routes to be accessed by these menu items 2. Do not render these menu items for users who should not have access to these.

Permissions can be database driven. You can protect routes using guards in angular 2 and menu items can be restricted from rendering using ng-if directive.

https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html

https://angular.io/docs/ts/latest/guide/router.html

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