This is a super simple middleware integrating with Gin and Casbin to implement RBAC in Gin apps.
$ go get github.com/xskit/gin-casbin
See examples.
You will have to provide a custom function to look up the current subject in runtime when you initialize this middleware.
// SubjectFn is used to look up current subject in runtime.
// If it can not find anything, just return an empty string.
type SubjectFn func(c *gin.Context) string
I am pretty sure there are many ways to do this. I provided two examples using JWT and session respectively.
This is one of the two core functionalities. You can use it to filter requests if the subjects don't have the required permissions.
func (am *CasbinMiddleware) RequiresPermissions(permissions []string, opts ...Option) gin.HandlerFunc
The first parameter is a slice of formatted strings representing required permissions. For example, "book:read"
stands for the permission to read a book. Note that if you pass in an illegal string such as "bookread"
or ":"
, it will abort immediately and respond HTTP 500.
This is the other core functionality. It is a little simpler than RequiresPermissions
since you just need to specify what roles you expect the subjects to have.
func (am *CasbinMiddleware) RequiresRoles(requiredRoles []string, opts ...Option) gin.HandlerFunc