Skip to content

Permission-Based Access Control ​

Added: v1.6.0

PBAC provides granular access control using permission strings (for example, "read:users" or "write:reports").

Permissions are defined on roles in an RBAC config file (r.EnableRBAC); a user is granted permissions through the roles they hold. See RBAC for how to register roles and inheritance.

Permission Middleware ​

These middlewares check permissions granted through the user's roles.

RequirePermission ​

go
// Requires the "posts:read" permission, sends 403 on failure
r.Use(zen.RequirePermission("posts:read"))

// Custom error handler
r.Use(zen.RequirePermission("posts:read", func(c *zen.Ctx) {
    c.Error(403, "access denied")
}))

RequireAnyPermission ​

go
// Requires at least one of the given permissions
r.Use(zen.RequireAnyPermission("posts:read", "posts:write"))

RequireAllPermissions ​

go
// Requires every listed permission
r.Use(zen.RequireAllPermissions("posts:read", "posts:write"))

Must be used after EnableAuth since they read the user from the context.

For per-route usage - e.g. r.POST("/posts", zen.RequirePermission("posts:write"), handler) - see Middleware.

Programmatic Checks ​

go
user := c.GetUser()

if user.HasPermission("write:reports") {
    // user's role grants this permission
}

if user.HasAnyPermission("read:reports", "write:reports") {
    // user has at least one of these permissions
}

if user.HasAllPermissions("read:reports", "write:reports") {
    // user has every listed permission
}

Granting Permissions ​

Permissions are granted by assigning the user a role that owns them:

json
{
  "roles": [
    { "name": "reporter", "permissions": ["read:reports", "write:reports"] }
  ]
}
go
return &zen.User{
    ID:     "123",
    Username: "john",
    Roles:  []string{"reporter"},
}, nil

Released under the MIT License.