-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_authorizer.go
51 lines (46 loc) · 1.36 KB
/
token_authorizer.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
50
51
package security
import "net/http"
type TokenAuthorizer struct {
Authorization string
Key string
sortedPrivilege bool
exact bool
}
func NewTokenAuthorizer(sortedPrivilege bool, exact bool, key string, options ...string) *TokenAuthorizer {
var authorization string
if len(options) >= 1 {
authorization = options[0]
}
return &TokenAuthorizer{Authorization: authorization, Key: key, sortedPrivilege: sortedPrivilege, exact: exact}
}
func (h *TokenAuthorizer) Authorize(next http.Handler, privilegeId string, action int32) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
privileges := ValuesFromContext(r, h.Authorization, h.Key)
if privileges == nil || len(*privileges) == 0 {
http.Error(w, "no permission: Require privileges for this user", http.StatusForbidden)
return
}
privilegeAction := GetAction(*privileges, privilegeId, h.sortedPrivilege)
if privilegeAction == ActionNone {
http.Error(w, "no permission for this user", http.StatusForbidden)
return
}
if action == ActionNone || action == ActionAll {
next.ServeHTTP(w, r)
return
}
sum := action & privilegeAction
if h.exact {
if sum == action {
next.ServeHTTP(w, r)
return
}
} else {
if sum >= action {
next.ServeHTTP(w, r)
return
}
}
http.Error(w, "no permission", http.StatusForbidden)
})
}