An open API service indexing awesome lists of open source software.

https://github.com/prongbang/fiber-casbinrest

Casbin RESTful Adapter on Fiber Web Framework
https://github.com/prongbang/fiber-casbinrest

adapter casbin-adapter fiber fiber-framework go golang role-api

Last synced: about 1 year ago
JSON representation

Casbin RESTful Adapter on Fiber Web Framework

Awesome Lists containing this project

README

          

# Fiber Casbin REST ๐Ÿ›ก๏ธ

[![Codecov](https://img.shields.io/codecov/c/github/prongbang/fiber-casbinrest.svg)](https://codecov.io/gh/prongbang/fiber-casbinrest)
[![Go Report Card](https://goreportcard.com/badge/github.com/prongbang/fiber-casbinrest)](https://goreportcard.com/report/github.com/prongbang/fiber-casbinrest)
[![Go Reference](https://pkg.go.dev/badge/github.com/prongbang/fiber-casbinrest.svg)](https://pkg.go.dev/github.com/prongbang/fiber-casbinrest)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

> RESTful adapter for [Casbin](https://github.com/casbin/casbin) on [Fiber](https://github.com/gofiber/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

```shell
go get github.com/prongbang/fiber-casbinrest
```

## ๐Ÿš€ Quick Start

### 1. Configure Casbin Model

Create `model.conf`:

```ini
[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

```go
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:

```json
{
"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:

```go
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:

```go
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

```go
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](https://casbin.org/docs/en/function)

## ๐Ÿงช Testing Your Policies

Use the [Casbin Editor](https://casbin.org/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](LICENSE) file for details.

## ๐Ÿ’– Support

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

[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/prongbang)

## ๐Ÿ”— Related Projects

- [Casbin](https://github.com/casbin/casbin) - Authorization library
- [Fiber](https://github.com/gofiber/fiber) - Express-inspired web framework
- [MongoDB Adapter](https://github.com/casbin/mongodb-adapter) - MongoDB storage adapter for Casbin

---