-
Notifications
You must be signed in to change notification settings - Fork 128
Managing roles
Make sure you are familiar with:
- Introduction
- Defining roles
- Individual roles
- Multiple roles
- Roles with permissions
- Removing roles
- Getting all roles
- Confusion with roles
By definition a role is a named set of abilities (permissions) by which a specific group of users is identified.
So for example USER
or ANONYMOUS
would be roles and not permissions. We can represent our USER
role as a group of permissions that the role should be able to perform. For example: listArticles
, editArticles
and other custom server/browser validated privileges.
🔥 Important
Roles are for and operator(&&)
between permissions. The whole library is based on permissions.
so this line
NgxRolesService
.addRole('ADMIN', ['read', 'write']);
This means that the user should have read and write permission already loaded to make this line work
<a *ngxPermissionsOnly="['ADMIN']" href="#" data-toggle="modal"></a>
Its possible to do in two ways
- Create role with already preloaded permissions
NgxRolesService
.addRoleWithPermissions('ADMIN', ['read', 'write']);
- add permissions
this.ngxPermissionsService.loadPermissions(['read', 'write'])
and then add role
NgxRolesService
.addRole('ADMIN', ['read', 'write']);
in this case this lines will work
<a *ngxPermissionsOnly="['ADMIN']" href="#" data-toggle="modal"></a>
<a *ngxPermissionsOnly="['read']" href="#" data-toggle="modal"></a>
💡 Note
It's a good convention to name roles with UPPER_CASE, so roles likeACCOUNTANT
orADMIN
are easier to distinguish from permissions.
💡 Note
If You have only names like USER, ADMIN without permissions inside like read, write. Its better to use permissions USER, ADMIN in this case this.ngxPermissionsService.loadPermissions(["USER", "ADMIN"])
Similarly to permissions we are gonna use here RolesService
that exposes addRole
allowing to define custom roles used by users in your application.
[...]
//permissionNameA,B,C should be defined by permissions service
//this.ngxPermissionsService.loadPermissions(["permissionNameA", "permissionNameB", "permissionNameC"])
// If at least one is not available the check will fail.
NgxRolesService
.addRole('ROLE_NAME', ['permissionNameA', 'permissionNameB', 'permissionNameC', ...])
NgxRolesService.addRole('Guest', (roleName, roleObject) => {
return this.sessionService.checkSession().toPromise();
});
NgxRolesService.addRole('Guest', (roleName, roleObject) => {
return true;
});
//Alternative You can add permissions with role at the same time
NgxRolesService
.addRoleWithPermissions('ROLE_NAME', ['permissionNameA', 'permissionNameB', 'permissionNameC', ...])
//or multiple permissions with roles at once
NgxRolesService
.addRolesWithPermissions({
'USER': ['canReadInvoices'],
'ADMIN': ['canReadInvoices','canEditInvoices','canUploadImages']
});
Validation function are injected with any angular services. There are 2 local injectables available that can be used to implement more complex validation logic.
Parameter | Description |
---|---|
roleName |
String representing name of checked role |
transitionProperties |
Array or validation function |
It also have to return one of values to properly represent results:
Validation result | Returned value |
---|---|
Valid | [true |Promise.resolve() but it should not resolve false ] |
Invalid | [false |Promise.reject() or Promise.resolve(false) ] |
Note: Right now to make request to the backend it only supports promises Note: If at least one of request fulfils it will show the component
Usage of addRole
is very similar to addPermissions
:
NgxRolesService
// Library will internally validate if 'listEvents' and 'editEvents' permissions are valid when checking if role is valid
.addRole('ADMIN', ['listEvents', 'editEvents']);
NgxRolesService.addRole('Guest', () => {
return this.sessionService.checkSession().toPromise();
});
Service NgxRolesService
allows you define multiple roles with addRoles
method. This method accepts Object
containing keys as a role names and corresponding validators as values.
NgxRolesService
// Or use your own function/service to validate role
.addRoles({
'USER': ['canReadInvoices'],
'ADMIN': ['canReadInvoices','canEditInvoices','canUploadImages'],
'GUEST': () => {
return this.sessionService.checkSessions().toPromise();
}
});
addRoleWithPermissions
function - add roles with permissions preloaded.
addRolesWithPermissions
function - add roles with permissions preloaded.
The difference between addRole
and addRoleWithPermissions
:
addRole
doesn't load permissions.
addRoleWithPermissions
load permissions.
NgxRolesService
.addRoleWithPermissions('ROLE_NAME', ['permissionNameA', 'permissionNameB', 'permissionNameC', ...])
NgxRolesService
.addRolesWithPermissions({
'USER': ['canReadInvoices'],
'ADMIN': ['canReadInvoices','canEditInvoices','canUploadImages']
});
💡 Note
To remove all roles use flushRoles
method:
NgxRolesService.flushRoles();
To remove all roles and permissions flushRolesAndPermissions
method:
NgxRolesService.flushRolesAndPermissions();
Alternatively you can use removeRole
to delete defined role manually:
NgxRolesService.removeRole('USER');
🔥 Important
This line will not remove permissions of user.
To get specific role use method getRole
:
let role = NgxRolesService.getRole('roleName');
And to get all roles form NgxRolesService
use method getRoles
or use Observable roles$
:
let roles = NgxRolesService.getRoles();
NgxRolesService.roles$.subscribe((data) => {
console.log(data);
})
Given
.addRoles({
'USER': ['canReadInvoices'],
'ADMIN': ['canReadInvoices', 'canEditInvoices', 'canUploadImages'],
'MANAGER': ['canEditInvoices'],
});
based on comment yd021976 Thank to him a lot
Hi, if I can help :
-
If you use "roles", then use in your template the role name to check permissions e.g, according to the @cubet-rahul code sample:
<a *ngxPermissionsOnly="['ADMIN']" href="#" data-toggle="modal"></a>
This will allow "ADMIN" role only, but all permissions of ADMIN role -
If you use "permissions", then use "permission name" in your template e.g, according to the @cubet-rahul code sample:
<a *ngxPermissionsOnly="['canEditInvoices']" href="#" data-toggle="modal"></a>
this will allow users that have "canEditInvoices", no matter of their roles
In addition, if this doesn't fit your needs, you can provide a validation function when defining role and/or permission.
Example:
NgxRolesService.addRole('ADMIN",()=>{ check whatever you want and return boolean })
If You have more problems with roles please look into this issues
https://github.com/AlexKhymenko/ngx-permissions/issues/80
https://github.com/AlexKhymenko/ngx-permissions/issues/58
If You have even more please create issue. Or just change the library so it will suit Your needs.
Hope it helps
Thank You for using the library and support 🌟 . HAVE A GREAT DAY!