gofiber / contrib

🧬 Repository for third party middlewares with dependencies
https://docs.gofiber.io/contrib/
MIT License
223 stars 119 forks source link

🚀 [Feature]: Casbin: Allow users to use other types of Enforcers #715

Open achmadafriza opened 1 year ago

achmadafriza commented 1 year ago

Feature Description

Currently, Casbin supports multiple types of Enforcer:

This doesn't deviate from the core functionalities of the Enforcer, which is described in the interface IEnforcer. The types of enforcers acts as a decorator to the actual Enforcer. As such, users should be able to use the middleware with other types of Enforcer.

Additional Context (optional)

No response

Code Snippet (optional)

package main

import (
    c "github.com/casbin/casbin/v2"
    "github.com/gofiber/contrib/casbin"
    "github.com/gofiber/fiber/v2"
)

func main() {
    enforcer, _ := c.NewEnforcer("path/to/basic_model.conf", "path/to/basic_policy.csv")
    //enforcer, _ := c.NewSyncedEnforcer("path/to/basic_model.conf", "path/to/basic_policy.csv") // This fails, but it should work.
    return casbin.New(casbin.Config{
        Enforcer: enforcer,
        Lookup: func(c *fiber.Ctx) string {
            claims, ok := c.UserContext().Value(model.AuthContextKey).(*model.AuthClaims)
            if !ok {
                logger.Error(nil, "failed to get auth claims")
                return ""
            }
            return claims.Role
        },
        Unauthorized: func(c *fiber.Ctx) error {
            return model.Response(c, http.StatusUnauthorized)
        },
        Forbidden: func(c *fiber.Ctx) error {
            return model.Response(c, http.StatusForbidden)
        },
    })
}

Checklist:

achmadafriza commented 1 year ago

There's a simple fix which just changes /gofiber/casbin.Config.Enforcer type from casbin.*Enforcer to casbin.IEnforcer. However this does not take into account the behavior of DistributedEnforcer, which have another interface casbin.IDistributedEnforcer.

I could submit a PR for it later.