-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
88 lines (71 loc) · 2.15 KB
/
handler.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
package auth
import (
"errors"
"github.com/redesblock/mop/core/api/jsonhttp"
urlSigner "github.com/redesblock/mop/core/util/urlsigner"
"net/http"
"strings"
)
type auth interface {
Enforce(string, string, string) (bool, error)
SecretKey(string) (string, error)
}
func PermissionCheckHandler(auth auth) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqToken := r.Header.Get("Authorization")
if !strings.HasPrefix(reqToken, "Bearer ") {
jsonhttp.Forbidden(w, "Missing bearer token")
return
}
keys := strings.Split(reqToken, "Bearer ")
if len(keys) != 2 || strings.Trim(keys[1], " ") == "" {
jsonhttp.Unauthorized(w, "Missing security token")
return
}
apiKey := keys[1]
allowed, err := auth.Enforce(apiKey, r.URL.Path, r.Method)
if errors.Is(err, ErrTokenExpired) {
jsonhttp.Unauthorized(w, "Token expired")
return
}
if err != nil {
jsonhttp.InternalServerError(w, "Error occurred while validating the security token")
return
}
if !allowed {
jsonhttp.Forbidden(w, "Provided security token does not grant access to the resource")
return
}
h.ServeHTTP(w, r)
})
}
}
func URLSignCheckHandler(auth auth) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqToken := r.Header.Get("Authorization")
if !strings.HasPrefix(reqToken, "Bearer ") {
jsonhttp.Forbidden(w, "Missing bearer token")
return
}
keys := strings.Split(reqToken, "Bearer ")
if len(keys) != 2 || strings.Trim(keys[1], " ") == "" {
jsonhttp.Unauthorized(w, "Missing security token")
return
}
apiKey := keys[1]
secretKey, err := auth.SecretKey(apiKey)
if err != nil {
jsonhttp.InternalServerError(w, "Error occurred while get secret from the security token")
return
}
singer := urlSigner.New(secretKey)
if !singer.VerifyTemporary(*r.URL) {
jsonhttp.Forbidden(w, "Provided sign does not grant access to the resource")
return
}
h.ServeHTTP(w, r)
})
}
}