Permissions
WebJET Elements includes a simple permissions system that you can use to conditionally display or remove components from the DOM according to the user's current permissions.
How it works
The Permissions class stores a list of permissions in localStorage. The WJElement base element then evaluates the permission, permission-check and no-show attributes during rendering.
This means that the check is done directly in the component and you don't need to write a custom condition in each view for it.
API for permissions
| Name | Type | Description |
|---|---|---|
permissionKey | string | The key used to store permissions in localStorage. The default value is 'permissions'. |
permissions | string[] | An array of the user's current permissions. When written, it is stored in localStorage. |
Methods
| Name | Parameters | Return value | Description |
|---|---|---|---|
includesKey(key) | key: string | boolean | Verifies that the user has a specific permission. |
isPermissionFulfilled(permissions) | permissions: string[] | boolean | Returns true if at least one permission from the passed field is satisfied. |
Setting permissions
import { Permissions } from 'wj-elements';
// Sets the permissions field of the current user
Permissions.permissions = ['admin', 'editor', 'viewer'];
// Optionally changes the key in localStorage
Permissions.permissionKey = 'myPermissions';
If you need to delete permissions, simply set a blank field:
Permissions.permissions = [];
Checking permissions in JavaScript
const maAdminPermission = Permissions.includesKey('admin');
const maAt leastOnePermission = Permissions.isPermissionFulfilled(['admin', 'editor']);
Checking permissions in a component
Components can use three related attributes:
permission- comma separated list of required permissions,permission-check- enables permission checking on render,no-show- the component is removed from the DOM on render, regardless of permissions.
<!-- Štandardné tlačidlo bez obmedzení -->
<wje-button>Standard button</wje-button>
<!-- Bez permission-check sa atribút permission sám o sebe nevyhodnocuje -->
<wje-button permission="admin">With permission attribute only</wje-button>
<!-- Zobrazí sa, ak má používateľ oprávnenie admin alebo editor -->
<wje-button permission="admin,editor" permission-check>
Requires permission
</wje-button>
<!-- Ak oprávnenie chýba, prvok sa vôbec nevykreslí -->
<wje-button permission="admin" permission-check no-show>
Hidden without permission
</wje-button>
Important notes
- The value of the
permissionattribute is comma delimited in the component, so use the formatpermission="admin,editor", for example. - The
isPermissionFulfilled()method uses the "at least one permission" logic. - If you want to change the behavior globally, edit the
Permissions.permissionKeybefore reading the permissions for the first time.