Role-Based Access Control
Added: v1.6.0
RBAC lets you restrict access based on roles assigned to a user. Roles define permissions, and users carry only roles.
Defining Roles
Define roles in a JSON config file. Each role owns a list of resource:action permissions and can inherit permissions from other roles.
configs/rbac.json:
{
"roles": [
{
"name": "viewer",
"permissions": ["posts:read"]
},
{
"name": "editor",
"permissions": ["posts:write"],
"inheritsFrom": ["viewer"]
},
{
"name": "admin",
"permissions": ["posts:delete", "users:delete"]
}
]
}Enable it at startup - the default path is configs/rbac.json, or give a custom path or inline definitions:
r.EnableRBAC() // loads configs/rbac.json
r.EnableRBAC("rbac.json") // custom file
r.EnableRBACRoles( // programmatic roles (any source)
rbac.Role{Name: "viewer", Permissions: []string{"posts:read"}},
rbac.Role{Name: "editor", Permissions: []string{"posts:write"}, InheritsFrom: []string{"viewer"}},
)Both methods enable RBAC for the engine, differing only in where role definitions come from. EnableRBAC loads them from a JSON config file (configs/rbac.json by default, or any path you give it); EnableRBACRoles registers them programmatically — inline in code, from a database, or any other source. Neither is a prerequisite for the other: calling EnableRBACRoles alone is enough to enable RBAC, and each call merges into the same role registry, so order does not matter. If the same role name appears in both, the definition registered last wins.
- Permissions are exact
resource:actionstrings - wildcards (users:*) are not supported - With
InheritsFrom, only list the additional permissions; inherited ones are included automatically - Inheritance is transitive:
editorabove also grantsposts:readfromviewer
Role Middleware
These middlewares check the roles held by the authenticated user.
RequireRole
// Requires the "admin" role, sends 403 on failure
r.Use(zen.RequireRole("admin"))
// Custom error handler
r.Use(zen.RequireRole("admin", func(c *zen.Ctx) {
c.Error(403, "admins only")
}))RequireAnyRole
// Requires at least one of the given roles
r.Use(zen.RequireAnyRole("admin", "editor"))RequireAllRoles
// Requires every listed role
r.Use(zen.RequireAllRoles("admin", "editor"))Must be used after EnableAuth since it reads the user from the context.
For per-route usage - e.g. r.GET("/admin/panel", zen.RequireRole("admin"), handler) - see Middleware.
Programmatic Checks
user := c.GetUser()
if user.HasRole("editor") {
// user holds the editor role
}
if user.HasPermission("posts:write") {
// granted via the editor role (or an inherited role)
}Assigning Roles
Assign role names on the User returned by your authenticator. No prefix or special format is needed - names must match the registered roles exactly:
return &zen.User{
ID: "123",
Username: "john",
Roles: []string{"admin", "editor"},
}, nil