-
Notifications
You must be signed in to change notification settings - Fork 129
Common use cases
- Two guards when first make request for authorisation and gets permissions second checks for permissions
- Save permissions on page refresh
- Disable element
Two guards when first make request for authorisation and gets permissions second checks for permissions
This method only works with angular 4.3.2
or higher see https://github.com/angular/angular/issues/15670
There are a lot of times you have 2 guard one for authorisation when it makes request for permissions and second is permissions guard and you want them to work in chain. To make them work in chain You should use them next
let routes = [
{ path: '',
canActivate: [AuthGuard],
children: [
{path: 'component',
component: ComponentName,
canActivate: [NgxPermissionsGuard],
data: {
permissions: {
only: ['ADMIN', 'MODERATOR'],
redirectTo: 'another-route'
}
}}
]
}
]
Note: Make sure the permission request in chained in auth guard
canActivate() {
return authLogin().then((obj) => {
// or load here if you dont need second request
// this.permissions.service.loadPermissions(obj.permissions)
return this.authPermissions.getPermissions('url');
}).then((permissions) => {
this.permissions.service.loadPermissions(permissions)
)
}
When user refreshed the page all data is lost including permissions for that user. There are a lot of approaches saving user permissions depending on your business requirements. But most common is to save them to localStorage. And then load them from localStorage when an application starts.
login() {
return authLogin().then((obj) => {
// Save permissions to localStorage.
localStorage.setItem('permissions', JSON.stringify(obj.permissions));
this.permissions.service.loadPermissions(obj.permissions);
})
}
To disable element specify disable and enable function in your main component
this.ngxPermissionsConfigurationService.addPermissionStrategy('disable', (templateRef: TemplateRef) => {
this.renderer2.setAttribute(tF.elementRef.nativeElement.nextSibling, 'disabled', 'true');
//or directly not recommended
templateRef.elementRef.nativeElement.nextSibling.setAttribute('disabled', true)
});
this.ngxPermissionsConfigurationService.addPermissionStrategy('enable', (templateRef: TemplateRef) => {
this.renderer2.removeAttribute(tF.elementRef.nativeElement.nextSibling, 'disabled');
});
Then You can use this strategy with ngxPermissions directive
<button *ngxPermissionsOnly="'ADMIN'; authorisedStrategy: 'enable'; unauthorisedStrategy: 'disable'">
<div>Admin will only see this</div>
</button>
You can also set disable and enable as default behavior
this.ngxPermissionsConfigurationService.setDefaultOnAuthorizedStrategy('enable');
or
this.ngxPermissionsConfigurationService.setDefaultOnUnauthorizedStrategy('disable')
Thank You for using the library and support 🌟 . HAVE A GREAT DAY!