forked from revel/modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authz.go
49 lines (41 loc) · 1.24 KB
/
authz.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package casbinauthz
import (
"net/http"
"github.com/casbin/casbin"
"github.com/wiselike/revel"
)
type CasbinModule struct {
enforcer *casbin.Enforcer
}
func NewCasbinModule(enforcer *casbin.Enforcer) *CasbinModule {
cm := &CasbinModule{}
cm.enforcer = enforcer
return cm
}
// AuthzFilter enables the authorization based on Casbin.
//
// Usage:
// 1) Add `casbin.AuthzFilter` to the app's filters (it must come after the authentication).
// 2) Init the Casbin enforcer.
func (cm *CasbinModule) AuthzFilter(c *revel.Controller, fc []revel.Filter) {
if !CheckPermission(cm.enforcer, c.Request) {
c.Result = c.Forbidden("Access denied by the Authz plugin.")
return
}
fc[0](c, fc[1:])
}
// GetUserName gets the user name from the request.
// Currently, only HTTP basic authentication is supported.
func GetUserName(r *revel.Request) string {
req := r.In.GetRaw().(*http.Request)
username, _, _ := req.BasicAuth()
return username
}
// CheckPermission checks the user/method/path combination from the request.
// Returns true (permission granted) or false (permission forbidden).
func CheckPermission(e *casbin.Enforcer, r *revel.Request) bool {
user := GetUserName(r)
method := r.Method
path := r.URL.Path
return e.Enforce(user, path, method)
}