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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
