example-rbac-programmatic

command
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 6 Imported by: 0

README

RBAC Programmatic Usage Example

This example demonstrates how to use Mithril's RBAC system programmatically in your application code.

Overview

This example shows you can interact with the RBAC system directly in your Go code, without using CLI commands. This is useful for:

  • Application logic (e.g., promoting users to roles)
  • Admin panels
  • API endpoints for role/permission management
  • Automated workflows
  • Testing

Running the Example

# Make sure the database exists from the main RBAC example
cd example-rbac
go run main.go
# Let it create the database, then stop it (Ctrl+C)

# Now run the programmatic example
cd ../example-rbac-programmatic
go run main.go

What It Demonstrates

  1. Creating Roles - Create new roles programmatically
  2. Creating Permissions - Create new permissions with resource/action structure
  3. Assigning Permissions to Roles - Give roles specific permissions
  4. Assigning Roles to Users (Two Methods):
    • Using RBAC manager
    • Using User model directly
  5. Giving Direct Permissions - Give permissions to users directly (bypassing roles)
  6. Checking Permissions - Check if users have specific roles/permissions
  7. Removing Roles - Remove roles from users
  8. Revoking Permissions - Revoke direct permissions from users
  9. Listing - List all roles and permissions

Key Takeaways

Both Approaches Work
// Approach 1: Using RBAC Manager (recommended for complex operations)
rbac := acl.NewRBAC(db)
err := rbac.AssignRoleToUser(userID, roleID)

// Approach 2: Using Model Methods (simpler for direct operations)
err := user.AssignRole(db, role)
When to Use Each

Use RBAC Manager when:

  • You need to find users/roles/permissions by slug or email
  • You're building admin interfaces
  • You need transaction support
  • You want consistent error handling

Use Model Methods when:

  • You already have the user/role/permission objects
  • You're doing simple assignments
  • You want more concise code
All Operations Are Database-Backed

Everything is persisted to the database immediately. No need to call "save" or "commit" manually (unless you're using transactions).

Permission Inheritance
// User gets permissions from:
// 1. Direct permissions (user.Permissions)
// 2. Role permissions (user.Roles[].Permissions)

allPerms := user.GetAllPermissions() // Returns combined list

Integration with Your Application

Example: User Promotion Endpoint
app.Post("/api/users/:id/promote", func(c *fiber.Ctx) error {
    userID := c.Params("id")
    
    rbac := acl.NewRBAC(db)
    
    // Get editor role
    role, err := rbac.GetRoleBySlug("editor")
    if err != nil {
        return c.Status(404).JSON(fiber.Map{"error": "Role not found"})
    }
    
    // Assign role
    if err := rbac.AssignRoleToUser(userID, role.ID.String()); err != nil {
        return c.Status(500).JSON(fiber.Map{"error": err.Error()})
    }
    
    return c.JSON(fiber.Map{"message": "User promoted to editor"})
})
Example: Custom Permission Check
func canPublish(user *models.User) bool {
    return user.HasRole("admin") || 
           user.HasRole("editor") || 
           user.HasPermission("article.publish")
}
Example: Dynamic Role Creation
func createCustomRole(name, slug string, permissionSlugs []string) error {
    rbac := acl.NewRBAC(db)
    
    // Create role
    role := &models.Role{
        Name: name,
        Slug: slug,
    }
    if err := rbac.CreateRole(role); err != nil {
        return err
    }
    
    // Assign permissions
    for _, permSlug := range permissionSlugs {
        perm, err := rbac.GetPermissionBySlug(permSlug)
        if err != nil {
            continue
        }
        rbac.AssignPermissionToRole(role.ID.String(), perm.ID.String())
    }
    
    return nil
}

See Also

  • ../example-rbac/ - Web application example with middleware
  • ../docs/RBAC_USAGE.md - Complete RBAC usage guide
  • ../pkg/acl/rbac.go - RBAC manager implementation
  • ../app/models/user.go - User model with RBAC methods

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

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