Skip to content

prongbang/fiber-casbinrest

Repository files navigation

Fiber Casbin REST πŸ›‘οΈ

Codecov Go Report Card Go Reference License: MIT

RESTful adapter for Casbin on Fiber web framework. Simplify your authorization with powerful and flexible access control.

✨ Features

  • πŸš€ Simple Integration - Easy to integrate with Fiber applications
  • πŸ” JWT Support - Built-in JWT token authentication
  • 🎯 Role-Based Access Control - Fine-grained RBAC support
  • πŸ”Œ Custom Adapter - Flexible adapter system for various storage backends
  • πŸ“¦ MongoDB Support - Ready-to-use MongoDB adapter
  • ⚑ High Performance - Optimized for speed and efficiency

πŸ“¦ Installation

go get github.com/prongbang/fiber-casbinrest

πŸš€ Quick Start

1. Configure Casbin Model

Create model.conf:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.sub == p.sub && (keyMatch(r.obj, p.obj) || keyMatch2(r.obj, p.obj)) && (r.act == p.act || regexMatch(r.act, p.act))

2. Define Policies

Example policies:

p, admin, /user/*, (GET)|(POST)
p, anonymous, /login, (GET)
p, admin, /admin/user/:id, (GET)|(POST)

3. Implement in Your Application

import (
    "github.com/casbin/casbin/v2"
    "github.com/gofiber/fiber/v2"
    fibercasbinrest "github.com/prongbang/fiber-casbinrest"
    "log"
)

func main() {
    e, _ := casbin.NewEnforcer("auth_model.conf", "policy.csv")
    
    app := fiber.New()
    app.Use(fibercasbinrest.NewDefault(e, "secret"))
    
    app.Get("/admin/user/:id", func(c *fiber.Ctx) error {
        return c.SendString("Hello, Admin! πŸ‘‹")
    })
    
    log.Fatal(app.Listen(":3000"))
}

πŸ”‘ JWT Authentication

The middleware supports JWT tokens with role claims:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022,
  "roles": ["ADMIN"]
}

Example JWT token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJyb2xlcyI6WyJBRE1JTiJdfQ.oW8uC8uyL4nZSjcDGRkW3ZHoEoHShPD7ft0cppgvQe4

πŸ› οΈ Advanced Usage

Custom Adapter

Create your own adapter for different storage backends:

type redisAdapter struct {}

func NewRedisAdapter() fibercasbinrest.Adapter {
    return &redisAdapter{}
}

func (r *redisAdapter) GetRoleByToken(reqToken string) ([]string, error) {
    // Implement your token validation and role retrieval logic
    if reqToken == "ADMIN_TOKEN" {
        return []string{"admin"}, nil
    }
    return []string{"anonymous"}, nil
}

func main() {
    adapter := NewRedisAdapter()
    e, _ := casbin.NewEnforcer("auth_model.conf", "policy.csv")
    
    app := fiber.New()
    app.Use(fibercasbinrest.New(e, adapter))
    
    app.Get("/admin/user/:id", func(c *fiber.Ctx) error {
        return c.SendString("Hello, Admin! πŸ‘‹")
    })
    
    log.Fatal(app.Listen(":3000"))
}

MongoDB Integration

Use MongoDB as your policy storage:

import (
    mongodbadapter "github.com/casbin/mongodb-adapter/v3"
)

func main() {
    a, _ := mongodbadapter.NewAdapter("127.0.0.1:27017")
    e, _ := casbin.NewEnforcer("model.conf", a)
    
    // Add policies
    _, _ = e.AddPolicy("anonymous", "/login", "GET")
    _, _ = e.AddPolicy("admin", "/admin", "(GET)|(POST)")
    _, _ = e.AddPolicy("admin", "/admin/user/:id", "GET")
    
    // Save and load policies
    _ = e.SavePolicy()
    _ = e.LoadPolicy()
    
    app := fiber.New()
    app.Use(fibercasbinrest.NewDefault(e, "secret"))
    
    app.Get("/admin/user/:id", func(c *fiber.Ctx) error {
        return c.SendString("Hello, Admin! πŸ‘‹")
    })
    
    log.Fatal(app.Listen(":3000"))
}

πŸ“š API Reference

Middleware Functions

Function Description
NewDefault(e *casbin.Enforcer, secret string) Creates middleware with default JWT configuration
New(e *casbin.Enforcer, adapter Adapter) Creates middleware with custom adapter

Adapter Interface

type Adapter interface {
    GetRoleByToken(reqToken string) ([]string, error)
}

πŸ”§ Configuration Options

Supported Matcher Functions

  • keyMatch: URL path matching
  • keyMatch2: URL path matching with wildcard support
  • regexMatch: Regular expression matching

For more matcher functions, visit: Casbin Functions

πŸ§ͺ Testing Your Policies

Use the Casbin Editor to test and validate your policies online.

🀝 Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ’– Support

If you find this library helpful, please consider buying me a coffee:

"Buy Me A Coffee"

πŸ”— Related Projects