Limiting actions access
As you might have noticed in diagrams from adminforth hooks section of this tutorial, AdminForth checks options.allowedActions
before executing any action. In this section we will show real-code examples of how to limit access to actions based on user role or record values.
Before we start it is worth to mention that callbacks or scalars defined in allowedActions
are called/parsed not only before actual request but also before displaying buttons in the UI. So first time, when frontend loads any page of resource, it "calls" allowedActions
to understand whether user has access to each function, and e.g. if it says that user can't delete record, AdminForth will not show delete icon in the UI:
As you can see allowedAction callbacks are called in parallel in async manner. However it is important to keep them fast and not to make any slow operations in them, to keep UI responsive.
Statically disable some action on resource
You can use options.allowedActions
on resource to limit access to the resource actions (list, show, create, edit, delete).
If you want to disable deletion of the resource records for all users:
{
...
resourceId: 'adminuser',
...
options: {
allowedActions: {
delete: false
}
}
}
Disable full access to resource based on logged in user record or role
If you want to disable all actions to the resource for all users except users with role superadmin
:
{
...
resourceId: 'adminuser',
...
options: {
allowedActions: {
all: async ({ adminUser }: { adminUser: AdminUser }): Promise<boolean> => {
return adminUser.dbUser.role === 'superadmin';
}
}
}
}
☝️ This will not hide link to the resource in the menu, you should separately use menuItem.visible to hide it.
☝️ instead of reading role from user you can check permission using complex ACL/RBAC models with permissions stored in the database. However we recommend you to keep in mind that allowedActions callback is called on every request related to resource, so it should be fast. So try to minimize requests to database as much as possible.