Frontend checks
On this page
This guide covers permission checks in Inertia pages. You will learn how to:
- Share the user's permissions with every page
- Show part of a page only to users who hold a permission
- Import the permission types in your frontend
Overview
Section titled "Overview"The configure step creates a Guard component in inertia/utils/permissions.tsx (React) or inertia/utils/permissions.vue (Vue). Guard renders its children only when the user holds a permission. It reads the permissions from the userPermissions page prop, which you share from the Inertia middleware.
Guard only hides UI. Keep the check on the route or in the controller.
Sharing the permissions
Section titled "Sharing the permissions"Share access.permissions(), not the raw getPermissions() list. Guard compares strings, and only Access resolves aliases and drops inactive keys.
import type { HttpContext } from '@adonisjs/core/http'
import BaseInertiaMiddleware from '@adonisjs/inertia/inertia_middleware'
import { permissions } from '#start/permissions'
export default class InertiaMiddleware extends BaseInertiaMiddleware {
async share(ctx: HttpContext) {
const { auth } = ctx as Partial<HttpContext>
return {
// ...rest of the properties
userPermissions: ctx.inertia.always(
auth?.user ? (await permissions.createAccessFor(auth.user)).permissions() : []
),
}
}
}
Using the Guard component
Section titled "Using the Guard component"Pass one key to for, or an array of keys. With an array, Guard renders its children when the user holds any of the keys. Add match="all" to require every key.
import { Guard } from '~/utils/permissions'
export default function ShowProduct() {
return (
<>
<Guard for="product.delete">
<button>Delete</button>
</Guard>
<Guard for={['product.update', 'billing.refund']} match="all">
<button>Refund and edit</button>
</Guard>
</>
)
}<script setup lang="ts">
import Guard from '~/utils/permissions.vue'
</script>
<template>
<Guard for="product.delete">
<button>Delete</button>
</Guard>
<Guard :for="['product.update', 'billing.refund']" match="all">
<button>Refund and edit</button>
</Guard>
</template>For a check outside a component, call hasAccess with the same arguments.
import { hasAccess } from '@adonisplus/permissions/client'
hasAccess(userPermissions, 'product.delete')
hasAccess(userPermissions, ['product.update', 'billing.refund'], 'all')Permission types
Section titled "Permission types"The indexPermissions hook in adonisrc.ts writes .adonisjs/client/permissions.d.ts when the dev server or the build starts. Import the types from @generated/permissions: PermissionKey is the union of your keys, and PermissionEntry is the shape that permissions.all() returns.
import type { PermissionKey, PermissionEntry } from '@generated/permissions'