-
Notifications
You must be signed in to change notification settings - Fork 0
/
func.go
116 lines (109 loc) · 2.56 KB
/
func.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package security
import (
"fmt"
"net"
"net/http"
"sort"
"strconv"
"strings"
)
func GetPositionFromSortedPrivileges(privileges []string, privilegeId string) int {
return sort.Search(len(privileges), func(i int) bool { return privileges[i][:strings.Index(privileges[i], ":")] >= privilegeId })
}
func GetAction(privileges []string, privilegeId string, sortedPrivilege bool) int32 {
prefix := fmt.Sprintf("%s:", privilegeId)
prefixLen := len(prefix)
if sortedPrivilege {
i := GetPositionFromSortedPrivileges(privileges, privilegeId)
if i >= 0 && i < len(privileges) && strings.HasPrefix(privileges[i], prefix) {
hexAction := privileges[i][prefixLen:]
if action, err := ConvertHexAction(hexAction); err == nil {
return action
}
}
} else {
for _, privilege := range privileges {
if strings.HasPrefix(privilege, prefix) {
hexAction := privilege[prefixLen:]
if action, err := ConvertHexAction(hexAction); err == nil {
return action
}
}
}
}
return ActionNone
}
func ConvertHexAction(hexAction string) (int32, error) {
if action64, err := strconv.ParseInt(hexAction, 16, 64); err == nil {
return int32(action64), nil
} else {
return 0, err
}
}
func Include(vs []string, v string) bool {
for _, s := range vs {
if v == s {
return true
}
}
return false
}
func IncludeOfSort(vs []string, v string) bool {
i := sort.SearchStrings(vs, v)
if i >= 0 && vs[i] == v {
return true
}
return false
}
func ValueFromMap(key string, data map[string]interface{}) string {
u := data[key]
if u != nil {
v, ok := u.(string)
if ok {
return v
}
}
return ""
}
func FromContext(r *http.Request, authorization string, key string) string {
if len(authorization) > 0 {
token := r.Context().Value(authorization)
if token != nil {
if authorizationToken, exist := token.(map[string]interface{}); exist {
return ValueFromMap(key, authorizationToken)
}
}
return ""
} else {
u := r.Context().Value(key)
if u != nil {
v, ok := u.(string)
if ok {
return v
}
}
return ""
}
}
func ValuesFromContext(r *http.Request, authorization string, key string) *[]string {
token := r.Context().Value(authorization)
if token != nil {
if authorizationToken, exist := token.(map[string]interface{}); exist {
v, ok2 := authorizationToken[key]
if !ok2 || v == nil {
return nil
}
if values, ok3 := v.(*[]string); ok3 {
return values
}
}
}
return nil
}
func getRemoteIp(r *http.Request) string {
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
remoteIP = r.RemoteAddr
}
return remoteIP
}