Reputation: 5273
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?
Upvotes: 6
Views: 21448
Reputation: 172
You should implement the ActivatedRoute interface to restrict navigation to a specific URL/resource, Read more
Upvotes: 3
Reputation: 5598
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
Upvotes: 5
Reputation: 597
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
});
}
}
Upvotes: 2
Reputation: 66
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
Upvotes: 0