-
-
Save timoyuen/2fc8c009ce47b3f2f345a221edf12e6b to your computer and use it in GitHub Desktop.
Casbin Authorization for qiangxue/golang-restful-starter-kit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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