Documentation

API reference

How your own code asks RoleWarden whether the signed-in user may do something, adds permissions of its own, and reacts to what happens in the panel. Every check takes a permission slug in area.action form, never a role.

Adding your own permissions

The panel lists permissions and assigns them to roles; it does not create them, because a permission only means something to the code that checks it. Your application adds its own with a migration, which also makes them arrive on every server with the code:

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddInvoicePermissions extends Migration
{
    private const PERMISSIONS = [
        'invoices.view' => 'See invoices',
        'invoices.approve' => 'Approve invoices',
    ];

    public function up(): void
    {
        $table = config('RoleWarden')->table('permissions');
        $now = date('Y-m-d H:i:s');

        foreach (self::PERMISSIONS as $slug => $description) {
            $this->db->table($table)->insert([
                'slug' => $slug,
                'area' => strstr($slug, '.', true),
                'description' => $description,
                'is_system' => 0,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }
    }

    public function down(): void
    {
        $this->db->table(config('RoleWarden')->table('permissions'))
            ->whereIn('slug', array_keys(self::PERMISSIONS))->delete();
    }
}

Run php spark migrate, then give the new permissions to roles from the panel. The demo app's installer (DemoInstaller.php) does the same, and also creates roles.

On routes: the can filter

$routes->get('invoices', 'Invoices::index', ['filter' => 'can:invoices.view']);
$routes->post('invoices/(:num)/approve', 'Invoices::approve/$1', ['filter' => 'can:invoices.approve']);

// Several permissions: any one of them lets the request through.
$routes->get('reports', 'Reports::index', ['filter' => 'can:reports.view,invoices.view']);

Put Shield's session filter before it on the same routes (or in a group), so that a guest is sent to sign in. A signed-in user without the permission is sent to Shield's permissionDeniedRedirect() with an error message.

In views and controllers: helpers

Load them with helper('rolewarden'), or add 'rolewarden' to $helpers in a controller or in app/Config/Autoload.php. A guest is denied everything.

FunctionReturns
can(string $permission): boolWhether the signed-in user holds the permission.
can_any(array $permissions): boolWhether they hold at least one of them.
can_all(array $permissions): boolWhether they hold every one of them.
permissions(): arrayThe slugs they hold, sorted. A super admin also passes checks on slugs not listed.
<?php if (can('invoices.approve')) : ?>
  <button type="submit">Approve</button>
<?php endif ?>

Show a button only to who may use it, and still check on the route or in the controller: hiding a button is not a protection.

Shield's user entity

With $userProvider pointing at \RoleWarden\Models\UserModel, Shield's own calls are answered by RoleWarden:

auth()->user()->can('invoices.view');                     // true if any one is granted
auth()->user()->can('invoices.view', 'reports.view');
auth()->user()->hasPermission('invoices.view');

inGroup() and getGroups() still work and read the user's roles, for code written for Shield's groups; new code should check permissions instead.

Any user: the rolewarden service

For a user other than the signed-in one, or outside a request (a command, a queue job):

$rolewarden = service('rolewarden');

$rolewarden->can($userId, 'invoices.approve');                       // bool
$rolewarden->canAny($userId, ['invoices.view', 'reports.view']);     // bool
$rolewarden->canAll($userId, ['invoices.view', 'invoices.approve']); // bool
$rolewarden->permissions($userId);                                  // list of slugs
$rolewarden->authorize($userId, 'invoices.approve');                // throws if denied

authorize() throws RoleWarden\Authorization\AuthorizationException. A slug not in area.action form throws InvalidArgumentException: checks never accept wildcards.

Cache

Each user's permissions are cached and forgotten whenever the panel changes something that affects them. If your own code writes the module's tables directly (assigning a role in a migration, for example), tell the service:

service('rolewarden')->forgetUser($userId);       // after changing one user's roles or overrides
service('rolewarden')->forgetRole($roleId);       // after changing a role, its permissions or its parent

Assigning a role through (new \RoleWarden\Models\UserRoles())->assign($userId, $roleId) does it for you.

Events

rolewarden.activity

Fires for every entry written to the activity log, with the row:

use CodeIgniter\Events\Events;

Events::on('rolewarden.activity', static function (array $entry): void {
    // $entry['action'] is e.g. 'role.updated'; $entry['details'] is JSON.
});

rolewarden.mail

Fires before each security email with the message (to, subject, view, data, locale). A listener that returns false takes the message over, for example to put it on your own queue, and the module does not send it:

// With the official codeigniter4/queue package and a job class of yours named 'security-email'.
Events::on('rolewarden.mail', static function (array $message) {
    service('queue')->push('emails', 'security-email', $message);

    return false;
});

The job then renders view('RoleWarden\Views\emails\\' . $message['view'], $message['data']) and sends it; set the language first with service('language')->setLocale($message['locale']).

Protections

Whatever the caller, the module refuses changes that would break the system, with a RoleWarden\Authorization\ProtectionException: leaving no active super admin, a role inheriting from itself or a descendant, deleting a system role or a role that still has child roles, an administrator removing the role that lets them manage roles.