rbac

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package rbac provides a lightweight RBAC (Role-Based Access Control) wrapper around [Casbin](https://github.com/casbin/casbin/v2) with pluggable policy storage adapters.

It offers:

  • a unified Enforcer manager with cached enforcement;
  • policy CRUD (add/remove/clear/list rules);
  • role management (assign/revoke roles, check inheritance);
  • a framework-agnostic Checker for embedding in any HTTP framework;
  • an optional Gin middleware (in subpackage gin).

Quick start (in-memory)

mgr, err := rbac.NewMemory()
if err != nil { ... }
defer mgr.Close()

// Grant role "admin" access to GET /api/users.
mgr.AddPolicy("admin", "/api/users", "GET")

// Check.
ok, _ := mgr.Enforce("admin", "/api/users", "GET") // true
ok, _ = mgr.Enforce("viewer", "/api/users", "GET")  // false

With GORM adapter

mgr, err := rbac.New(rbac.WithGormAdapter(db))

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptySubject is returned when a subject (role/user) is empty.
	ErrEmptySubject = fmt.Errorf("rbac: subject must not be empty")
	// ErrEmptyObject is returned when an object (path/resource) is empty.
	ErrEmptyObject = fmt.Errorf("rbac: object must not be empty")
	// ErrEmptyAction is returned when an action (HTTP method) is empty.
	ErrEmptyAction = fmt.Errorf("rbac: action must not be empty")
	// ErrPolicyNotFound is returned when a requested policy does not exist.
	ErrPolicyNotFound = fmt.Errorf("rbac: policy not found")
)

Functions

func NormalizePath

func NormalizePath(path, prefix string) string

NormalizePath removes a prefix from a path and trims trailing slashes. This is useful for stripping framework route prefixes before enforcement.

Types

type CheckContext

type CheckContext interface {
	// Subject returns the authenticated subject (user ID, role, etc.).
	Subject() string
	// Object returns the resource being accessed (e.g. URL path).
	Object() string
	// Action returns the action being performed (e.g. HTTP method).
	Action() string
}

CheckContext is the context passed to Checker functions. It is framework-agnostic — adapters convert framework-specific request objects into this interface.

type Checker

type Checker struct {
	// contains filtered or unexported fields
}

Checker is a framework-agnostic permission checker. It extracts the subject, object, and action from a request context and delegates to the Manager for enforcement.

func NewChecker

func NewChecker(mgr *Manager, opts ...CheckerOption) *Checker

NewChecker creates a permission checker.

func (*Checker) Check

func (c *Checker) Check(ctx CheckContext) (bool, error)

Check evaluates whether the context's subject can perform the context's action on the context's object.

type CheckerOption

type CheckerOption func(*Checker)

CheckerOption configures a Checker.

func WithActionFunc

func WithActionFunc(f func(ctx CheckContext) string) CheckerOption

WithActionFunc sets the function that extracts the action from a context.

func WithObjectFunc

func WithObjectFunc(f func(ctx CheckContext) string) CheckerOption

WithObjectFunc sets the function that extracts the object from a context.

func WithSubjectFunc

func WithSubjectFunc(f func(ctx CheckContext) string) CheckerOption

WithSubjectFunc sets the function that extracts the subject from a context.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager wraps a Casbin enforcer with convenience methods for policy and role management. The zero value is NOT ready to use; call New or NewMemory.

func New

func New(opts ...Option) (*Manager, error)

New creates a new RBAC manager. At least one adapter option must be provided (or use NewMemory for an in-memory enforcer).

func NewMemory

func NewMemory() (*Manager, error)

NewMemory creates a manager with an in-memory enforcer (no persistence). This is useful for testing and simple applications.

func (*Manager) AddPolicies

func (m *Manager) AddPolicies(rules [][]string) (bool, error)

AddPolicies adds multiple policy rules atomically.

func (*Manager) AddPolicy

func (m *Manager) AddPolicy(sub, obj, act string) (bool, error)

AddPolicy adds a single policy rule (sub, obj, act). Returns (true, nil) if the policy was added (false if it already existed).

func (*Manager) AssignRole

func (m *Manager) AssignRole(user, role string) (bool, error)

AssignRole assigns a role (or user) to a parent role (role inheritance). e.g. AssignRole("alice", "admin") means alice inherits admin's permissions.

func (*Manager) ClearPolicies

func (m *Manager) ClearPolicies(sub string) error

ClearPolicies removes all policies for a given subject (role/user).

func (*Manager) Close

func (m *Manager) Close()

Close releases resources held by the enforcer.

func (*Manager) DeleteRole

func (m *Manager) DeleteRole(role string) error

DeleteRole deletes a role and all its assignments.

func (*Manager) Enforce

func (m *Manager) Enforce(sub, obj, act string) (bool, error)

Enforce checks whether a subject can perform an action on an object. Returns (true, nil) if access is allowed.

func (*Manager) Enforcer

func (m *Manager) Enforcer() *casbin.SyncedCachedEnforcer

Enforcer returns the underlying Casbin enforcer for advanced operations.

func (*Manager) HasPolicy

func (m *Manager) HasPolicy(sub, obj, act string) (bool, error)

HasPolicy checks whether a policy rule exists.

func (*Manager) HasRole

func (m *Manager) HasRole(user, role string) (bool, error)

HasRole checks whether a user has a given role (directly or inherited).

func (*Manager) ListPolicies

func (m *Manager) ListPolicies() [][]string

ListPolicies returns all policy rules.

func (*Manager) ListPoliciesForSubject

func (m *Manager) ListPoliciesForSubject(sub string) [][]string

ListPoliciesForSubject returns all policy rules for a given subject.

func (*Manager) RemovePolicies

func (m *Manager) RemovePolicies(rules [][]string) (bool, error)

RemovePolicies removes multiple policy rules atomically.

func (*Manager) RemovePolicy

func (m *Manager) RemovePolicy(sub, obj, act string) (bool, error)

RemovePolicy removes a single policy rule. Returns (true, nil) if the policy was removed.

func (*Manager) RevokeRole

func (m *Manager) RevokeRole(user, role string) (bool, error)

RevokeRole removes a role assignment.

func (*Manager) RolesForUser

func (m *Manager) RolesForUser(user string) ([]string, error)

RolesForUser returns all roles assigned to a user (direct and inherited).

func (*Manager) SetPolicies

func (m *Manager) SetPolicies(sub string, rules [][2]string) error

SetPolicies replaces all policies for a subject with the given rules. This is useful for updating a role's permissions atomically.

func (*Manager) UsersForRole

func (m *Manager) UsersForRole(role string) ([]string, error)

UsersForRole returns all users that have the given role.

type Option

type Option func(*Manager) error

Option configures a Manager.

func WithEnforcer

func WithEnforcer(e *casbin.SyncedCachedEnforcer) Option

WithEnforcer uses a pre-configured Casbin enforcer.

func WithGormAdapter

func WithGormAdapter(db *gorm.DB) Option

WithGormAdapter uses a GORM-backed policy adapter for persistence.

func WithModelText

func WithModelText(text string) Option

WithModelText uses a custom Casbin model text instead of the default. Must be combined with an adapter option.

type SimpleCheckContext

type SimpleCheckContext struct {
	Sub string
	Obj string
	Act string
}

SimpleCheckContext is a basic implementation of CheckContext.

func (SimpleCheckContext) Action

func (s SimpleCheckContext) Action() string

Action returns the action.

func (SimpleCheckContext) Object

func (s SimpleCheckContext) Object() string

Object returns the object.

func (SimpleCheckContext) Subject

func (s SimpleCheckContext) Subject() string

Subject returns the subject.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL