Skip to Content
Module developmentModule basics

Module permissions

How a module declares its permissions, checks them in code and on routes, and how they show up in the role editor.

By the end your module has its own permissions: the owner grants them to roles in the role editor, and your code checks them on admin screens, routes and individual records.

Minimal example

The Example module lists player reports. admin.example.view opens the list, admin.example lets staff close reports and includes the view permission.

app/Modules/Example/module.json
{
    "name": "Example",
    "version": "1.0.0",
    "providers": ["Flute\\Modules\\Example\\Providers\\ExampleProvider"],
    "dependencies": { "flute": "^2.0" },
    "permissions": [
        {
            "name": "admin.example",
            "desc": "example.permissions.manage",
            "group": "example",
            "implies": ["admin.example.view"]
        },
        {
            "name": "admin.example.view",
            "desc": "example.permissions.view",
            "group": "example"
        }
    ]
}
app/Modules/Example/Resources/lang/en/example.php
<?php

return [
    'title' => 'Reports',
    'permissions' => [
        'manage' => 'Reports: close and delete reports',
        'view' => 'Reports: see the list of reports',
    ],
];

A check on the route and on one record:

app/Modules/Example/Controllers/ReportController.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\Example\Controllers;

use DateTimeImmutable;
use Flute\Core\Router\Annotations\Route;
use Flute\Core\Support\BaseController;
use Flute\Modules\Example\database\Entities\Report;
use Symfony\Component\HttpFoundation\JsonResponse;

final class ReportController extends BaseController
{
    #[Route(
        uri: '/example/reports/{id}/close',
        methods: ['POST'],
        name: 'example.reports.close',
        middleware: ['can:admin.example', 'csrf'],
    )]
    public function close(int $id): JsonResponse
    {
        $report = Report::findByPK($id);

        if ($report === null || !user()->can('example.reports.close', $report)) {
            return $this->json(['error' => __('def.permission_denied')], 403);
        }

        $report->closedAt = new DateTimeImmutable();
        $report->saveOrFail();

        return $this->json(['ok' => true]);
    }
}
app/Modules/Example/Policies/ReportPolicy.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\Example\Policies;

use Flute\Core\Database\Entities\User;
use Flute\Modules\Example\database\Entities\Report;

final class ReportPolicy
{
    public function close(User $user, Report $report): bool
    {
        return user()->userCan($user, 'admin.example') && $report->closedAt === null;
    }
}
app/Modules/Example/Providers/ExampleProvider.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\Example\Providers;

use DI\Container;
use Flute\Core\Authorization\PolicyRegistry;
use Flute\Core\Support\ModuleServiceProvider;
use Flute\Modules\Example\database\Entities\Report;
use Flute\Modules\Example\Policies\ReportPolicy;

final class ExampleProvider extends ModuleServiceProvider
{
    public function boot(Container $container): void
    {
        $this->bootstrapModule();
        $container->get(PolicyRegistry::class)->register(Report::class, ReportPolicy::class);
    }
}

How it works

The core collects module permissions on every request, in every context: web, admin, console, worker. In its own boot(), AuthorizationServiceProvider takes the active modules and hands each one to PermissionSync::syncModule(). That reads module.json.permissions[] plus the static permissions() method of the module's providers, if there is one, and writes everything into PermissionRegistry. Permissions of a disabled or deleted module are marked orphaned and kept, so role assignments survive a reinstall.

The role editor shows only permissions that have a row in the permissions table. CorePermissionsSeeder creates the rows whenever the set of permission names changes. A new permission appears in the editor on the next request after the module is enabled.

implies resolves transitively: a role holding admin.example also passes a check for admin.example.view. admin.boss passes every check by name.

How a permission looks in the role editor

The owner grants permissions in AdminRoles, on the "Permissions" tab. Your declaration decides what they see there:

In the editorComes from
groupthe group field. The group caption is the key admin-roles.editor.groups.<group>, otherwise the module name (the <module key>.title key in its translations)
row namethe translation of the desc key. A leading part up to the colon ("Reports: ") is cut off, since the group already names it
"None / View / Manage" switcha pair X and X.view where X implies X.view. The pair is drawn as one row
"Sensitive" mark"sensitive": true on the permission or on something it implies
"On because “…” includes it"the permission is granted through another permission's implies

A module cannot ship its own role template or default role. Its permissions land in the "Junior moderator", "Moderator" and "Administrator" templates by rule: "Administrator" gets everything, "Moderator" everything except sensitive permissions, "Junior moderator" only non-sensitive permissions whose name ends in .view or .read. Role rank is the owner's setting and the module does not touch it, see role rank.

Reference

Fields of one module.json.permissions[] entry:

FieldTypeDefaultWhat it does
namestringrequiredpermission name. An empty name is skipped
descstringpermissions.<name>translation key with the permission name
groupstringthe part of the name before the first dotgroup in the role editor
impliesstring[][]permissions granted together with this one
sensitiveboolfalse"Sensitive" mark, keeps the permission out of the "Moderator" and "Junior moderator" templates

Checks:

WhereWhat to writeWhat it does
PHPuser()->can('admin.example')one permission or an array (all required). false on any error
PHPuser()->canAny([...]), user()->canAll([...])any of the list, all of the list
PHPuser()->userCan($user, 'admin.example')another account's permission, with implies and admin.boss
PHPcan_read('admin.example'), can_write('admin.example')can('admin.example.view') and can('admin.example')
PHPPerm::view($domain), Perm::write($domain)the read and write permission name of a domain (Flute\Core\Authorization\Perm)
recorduser()->can('example.reports.close', $report)the record's policy decides, otherwise denied
routemiddleware: ['can:a,b']all listed permissions are required
routemiddleware: ['can.any:a,b']any one of them is enough
Blade@can('admin.example') … @endcan, @cannot(...)same as user()->can()

PolicyRegistry::register(string $entityClass, string $policyClass) links an entity to a policy. The policy method comes from the last segment of the ability: example.reports.close calls close(User $user, Report $report): bool, example.reports.assign-roles calls assignRoles(). The policy is looked up by the record's class and its parents and resolved from the container.

Common mistakes

PermissionSync: module 'Example' tried to redeclare core permission

The permission name matches a core permission, and the module did not get it. The entry is in the modules log. The module's other permissions still work. Name it after the module key, for example admin.example.

A module cannot grant a core permission through implies. A reference to admin, admin.boss or any other core permission is silently dropped from implies.

Without the admin permission ("Open the admin panel") the module's admin package does not load, and its screens answer as if they did not exist. A module cannot grant it; the owner turns it on in the staff role.

A record check without a policy is always a denial, and the log gets Record authorization for … denied: no policy registered. A policy does not let admin.boss through on its own: check the owner with userCan(), as in the example, which accounts for admin.boss.

can: without an argument throws InvalidArgumentException with Permission parameter is required.. A guest gets 401, a signed-in user without the permission gets 403 with "Access denied".

You changed desc on an existing permission and the editor still shows the old name. The set of names did not change, so the catalog is rewritten only after a day. Run php flute cache:clear.

Learn more

On this page