-
Notifications
You must be signed in to change notification settings - Fork 13
/
middleware_accesstoken.go
104 lines (84 loc) · 2.51 KB
/
middleware_accesstoken.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
package rye
import (
"errors"
"fmt"
"net/http"
)
type accessTokens struct {
paramName string
tokens []string
getFunc func(string, *http.Request) string
missingMessage string
}
/*
NewMiddlewareAccessToken creates a new handler to verify access tokens passed as a header.
Example usage:
routes.Handle("/some/route", a.Dependencies.MWHandler.Handle(
[]rye.Handler{
rye.NewMiddlewareAccessToken(tokenHeaderName, []string{token1, token2}),
yourHandler,
})).Methods("POST")
*/
func NewMiddlewareAccessToken(headerName string, tokens []string) func(rw http.ResponseWriter, req *http.Request) *Response {
return newAccessTokenHandler(headerName, tokens, "header")
}
/*
NewMiddlewareAccessQueryToken creates a new handler to verify access tokens passed as a query parameter.
Example usage:
routes.Handle("/some/route", a.Dependencies.MWHandler.Handle(
[]rye.Handler{
rye.NewMiddlewareAccessQueryToken(queryParamName, []string{token1, token2}),
yourHandler,
})).Methods("POST")
*/
func NewMiddlewareAccessQueryToken(queryParamName string, tokens []string) func(rw http.ResponseWriter, req *http.Request) *Response {
return newAccessTokenHandler(queryParamName, tokens, "query")
}
func newAccessTokenHandler(name string, tokens []string, tokenType string) func(rw http.ResponseWriter, req *http.Request) *Response {
a := &accessTokens{
paramName: name,
tokens: tokens,
}
switch tokenType {
case "query":
a.getFunc = func(s string, r *http.Request) string {
q, ok := r.URL.Query()[s]
if !ok {
return ""
}
return q[0]
}
a.missingMessage = fmt.Sprintf("No access token found; ensure you pass the '%s' parameter", name)
default:
// default to using the header
a.getFunc = func(s string, r *http.Request) string {
return r.Header.Get(s)
}
a.missingMessage = fmt.Sprintf("No access token found; ensure you pass '%s' in header", name)
}
return a.handle
}
func (a *accessTokens) handle(rw http.ResponseWriter, r *http.Request) *Response {
token := a.getFunc(a.paramName, r)
if token == "" {
return &Response{
Err: errors.New(a.missingMessage),
StatusCode: http.StatusUnauthorized,
}
}
if ok := stringListContains(a.tokens, token); !ok {
return &Response{
Err: errors.New("Unauthorized request: invalid access token"),
StatusCode: http.StatusUnauthorized,
}
}
return nil
}
func stringListContains(stringList []string, element string) bool {
for _, v := range stringList {
if v == element {
return true
}
}
return false
}