-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_handler_test.go
94 lines (80 loc) · 2.52 KB
/
token_handler_test.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
package middlewares
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestExtractBearer(t *testing.T) {
req, err := http.NewRequest("GET", "/tokens", nil)
if err != nil {
t.Fatal(err)
}
raw := "thisisabearertokenthatshouldbefound"
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", raw))
tval, err := bearer(req.Header)
assert.Nil(t, err, "should be nil")
assert.Equal(t, raw, tval, "should be equal")
t.Run("Empty bearer", func(t *testing.T) {
req.Header.Set("Authorization", "Bearer ")
tval, err := bearer(req.Header)
assert.NotNil(t, err, "should not be nil")
assert.Empty(t, tval, "should be empty")
assert.Equal(t, "empty bearer token", err.Error(), "should be equal")
})
t.Run("Empty authentication", func(t *testing.T) {
req.Header.Del("Authorization")
tval, err := bearer(req.Header)
assert.NotNil(t, err, "should not be nil")
assert.Empty(t, tval, "should be empty")
assert.Equal(t, "no Authorization header found", err.Error(), "should be equal")
})
}
func TestTokenHandler(t *testing.T) {
req, err := http.NewRequest("GET", "/tokens", nil)
if err != nil {
t.Fatal(err)
}
t.Run("Empty token", func(t *testing.T) {
req.Header.Set("Authorization", "Bearer")
ctxHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := Token(r.Context())
assert.NotNil(t, err, "should not be nil")
assert.Empty(t, token, "should be empty")
assert.Equal(t, "no token found in context", err.Error(), "should be equal")
})
rr := httptest.NewRecorder()
handler := TokenHandler(ctxHandler)
handler.ServeHTTP(rr, req)
})
t.Run("With token", func(t *testing.T) {
req.Header.Set("Authorization", "Bearer thisisatoken")
ctxHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := Token(r.Context())
assert.Nil(t, err, "should be nil")
assert.Equal(t, "thisisatoken", token, "should be equal")
})
rr := httptest.NewRecorder()
handler := TokenHandler(ctxHandler)
handler.ServeHTTP(rr, req)
})
}
func ExampleToken() {
defaultHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := Token(r.Context())
if err != nil {
// error handling
}
fmt.Printf("%s", token)
})
// ...
http.Handle("/", defaultHandler)
}
func ExampleTokenHandler() {
defaultHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// do something
})
http.Handle("/", TokenHandler(defaultHandler))
http.ListenAndServe(":3000", nil)
}