How to Add Custom Super‑Admin Functions in Casbin

This guide explains step‑by‑step how to create, register, and use a custom function in Casbin to support multiple super‑admin users, including code examples for PHP anonymous functions and Enforcer registration.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
How to Add Custom Super‑Admin Functions in Casbin

The official Casbin documentation shows only how to designate a single user (e.g., "root") as a super‑admin. To support multiple super‑admin accounts, you can define a custom function and integrate it into the policy model.

Steps to create a custom function

Prepare the custom function logic.

Register the function with the Casbin Enforcer.

Reference the function in the model configuration file (CONF).

When using the function, ensure the number of parameters matches the definition.

Example: Custom function implementation

public function isSuperAdmin(string $key1) {
    $superAdminMap = ['root', 'admin'];
    if (in_array($key1, $superAdminMap, true)) {
        return true;
    }
    return false;
}

Convert it to an anonymous function so it can capture external variables:

$superAdminMap = ['root', 'admin'];
$isSuperAdmin = function (string $key1) use ($superAdminMap) {
    if (in_array($key1, $superAdminMap, true)) {
        return true;
    }
    return false;
};
Use the use keyword to pass $superAdminMap into the anonymous function.

Registering the function with Casbin

// Register function
Enforcer::addFunction('isSuperAdmin', $isSuperAdmin);

Or register it directly without a separate variable:

$superAdminMap = ['root', 'admin'];
Enforcer::addFunction('isSuperAdmin', function (string $key1) use ($superAdminMap) {
    if (in_array($key1, $superAdminMap, true)) {
        return true;
    }
    return false;
});

Using the custom function in the model

[matchers]
m = g(r.sub, p.sub) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act) || isSuperAdmin(r.sub)

With this matcher, any request where r.sub matches one of the entries in $superAdminMap will be treated as coming from a super‑admin, bypassing the usual policy checks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPCasbincustom-functionsuper admin
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.