Skip to content

Instantly share code, notes, and snippets.

@timoyuen
Forked from stefanwuthrich/middleware.go
Created October 31, 2018 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timoyuen/2fc8c009ce47b3f2f345a221edf12e6b to your computer and use it in GitHub Desktop.
Save timoyuen/2fc8c009ce47b3f2f345a221edf12e6b to your computer and use it in GitHub Desktop.
Casbin Authorization for qiangxue/golang-restful-starter-kit
package util
import (
"net/http"
"github.com/casbin/casbin"
"github.com/qiangxue/golang-restful-starter-kit/app"
"github.com/go-ozzo/ozzo-routing"
)
// Authorizer is a middleware that controls the access to the HTTP service, it is based
// on Casbin, which supports access control models like ACL, RBAC, ABAC.
// The plugin determines whether to allow a request based on (user, path, method).
// user: the authenticated user name.
// path: the URL for the requested resource.
// method: one of HTTP methods like GET, POST, PUT, DELETE.
//
// This middleware should be inserted fairly early in the middleware stack to
// protect subsequent layers. All the denied requests will not go further.
//
// It's notable that this middleware should be behind the authentication (e.g.,
// HTTP basic authentication, OAuth), so this plugin can get the logged-in user name
// to perform the authorization.
func Authorizer(e *casbin.Enforcer) routing.Handler {
return func(c *routing.Context) error {
userID:=app.GetRequestScope(c).UserID()
method := c.Request.Method
path := c.Request.URL.Path
if e.Enforce(userID, path, method) {
return nil
} else {
return routing.NewHTTPError(http.StatusUnauthorized, "NOT AUTHORIZED")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment