/
middleware.go
79 lines (70 loc) · 1.64 KB
/
middleware.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
package common
import (
"errors"
"net/http"
"strings"
)
func RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if !strings.Contains(authHeader, "Bearer") {
exc := NewSingleMessageException(
EUNAUTHORIZED,
"RequiredAuth",
"Not Authorized",
errors.New("missing value in authorization header"),
)
SendError(w, exc)
return
}
token, payload, err := ParseToken(authHeader[7:])
if err != nil {
exc := NewSingleMessageException(
EUNAUTHORIZED,
"RequiredAuth",
"Not Authorized",
errors.New("invalid token"),
)
SendError(w, exc)
return
}
if !token.Valid {
exc := NewSingleMessageException(
EUNAUTHORIZED,
"RequiredAuth",
"Not Authorized",
errors.New("invalid token"),
)
SendError(w, exc)
return
}
ctx := UserPayloadToContext(payload, r)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func RequireOneOfRole(roles ...string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userPayload, err := UserPayloadFromContext("RequireRoles", r)
if err != nil {
SendError(w, err)
return
}
for _, role := range roles {
for _, userRole := range userPayload.Roles {
if role == userRole {
next.ServeHTTP(w, r)
return
}
}
}
exc := NewSingleMessageException(
EUNAUTHORIZED,
"RequireRoles",
"Not Authorized",
errors.New("trying to access endpoint without appropiate role"),
)
SendError(w, exc)
})
}
}