-
Notifications
You must be signed in to change notification settings - Fork 0
/
privileges_authorizer.go
60 lines (55 loc) · 1.69 KB
/
privileges_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
52
53
54
55
56
57
58
59
60
package security
import (
"context"
"net/http"
)
type PrivilegesAuthorizer struct {
Privileges func(ctx context.Context, userId string) []string
Authorization string
Key string
sortedPrivilege bool
exact bool
}
func NewPrivilegesAuthorizer(loadPrivileges func(ctx context.Context, userId string) []string, sortedPrivilege bool, exact bool, key string, options ...string) *PrivilegesAuthorizer {
var authorization string
if len(options) >= 1 {
authorization = options[0]
}
return &PrivilegesAuthorizer{Privileges: loadPrivileges, Authorization: authorization, Key: key, sortedPrivilege: sortedPrivilege, exact: exact}
}
func (h *PrivilegesAuthorizer) Authorize(next http.Handler, privilegeId string, action int32) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userId := FromContext(r, h.Authorization, h.Key)
if len(userId) == 0 {
http.Error(w, "invalid User Id", http.StatusForbidden)
return
}
privileges := h.Privileges(r.Context(), userId)
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)
})
}