-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrbac.go
More file actions
60 lines (57 loc) · 1.72 KB
/
rbac.go
File metadata and controls
60 lines (57 loc) · 1.72 KB
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 util
import (
"net/http"
"reflect"
"runtime"
"strconv"
"strings"
)
func RBAC(handler func(http.ResponseWriter, *http.Request), privilege string, returnCollection bool) func(http.ResponseWriter, *http.Request) {
finalHandler := func(pass bool) func(http.ResponseWriter, *http.Request) {
if pass {
return handler
} else {
return func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
handlerFunctionName := runtime.FuncForPC(reflect.ValueOf(handler).Pointer()).Name()
parts := strings.Split(handlerFunctionName, "/")
Logging(WARN, handlerFunctionName, GetIPAddress(request), "Unauthorized access", parts[1])
writer.Header().Set("Content-Type", "application/json")
if returnCollection {
_, _ = writer.Write([]byte("[{\"status\":\"fail\", \"reason\":\"unauthorized\"}]"))
} else {
_, _ = writer.Write([]byte("{\"status\":\"fail\", \"reason\":\"unauthorized\"}"))
}
}
}
}
return func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("initiator", "NO_TOKEN")
var handleFunc func(http.ResponseWriter, *http.Request)
id := GetLoggedUserIDFromToken(request)
if id == 0 {
writer.Header().Set("initiator", "UNAUTHORIZED")
handleFunc = finalHandler(false)
} else {
writer.Header().Set("initiator", strconv.Itoa(int(id)))
validPrivileges, ok := GetUserPrivileges(id)
if !ok {
handleFunc = finalHandler(false)
} else {
valid := false
for _, val := range validPrivileges {
if val == privilege {
valid = true
break
}
}
if valid {
handleFunc = finalHandler(true)
} else {
handleFunc = finalHandler(false)
}
}
}
handleFunc(writer, request)
}
}