-
Notifications
You must be signed in to change notification settings - Fork 1
/
firebaseauth_test.go
109 lines (92 loc) · 2.46 KB
/
firebaseauth_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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package firebaseauth
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"firebase.google.com/go/v4/auth"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestMiddleware(t *testing.T) {
tests := []struct {
name string
authorization string
status int
body string
nextCalled bool
tokenUID string
rawToken string
}{
{
name: "success",
authorization: "Bearer valid-token",
status: http.StatusOK,
body: "success",
nextCalled: true,
tokenUID: "userid",
rawToken: "valid-token",
},
{
name: "missing header",
status: http.StatusForbidden,
body: "missing authorization header\n",
},
{
name: "malformed header",
authorization: "valid-token",
status: http.StatusForbidden,
body: "malformed authorization header\n",
},
{
name: "invalid",
authorization: "Bearer invalid-token",
status: http.StatusForbidden,
body: "invalid token\n",
},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
nextCalled := false
nextCtx := context.Background()
next := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
nextCalled = true
nextCtx = req.Context() //nolint:fatcontext // not creating a new context
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("success"))
})
fbAuth := NewMockfirebaseAuth(t)
fbAuth.EXPECT().
VerifyIDToken(mock.Anything, mock.Anything).
RunAndReturn(func(_ context.Context, s string) (*auth.Token, error) {
switch {
case s == "valid-token":
return &auth.Token{UID: tc.tokenUID}, nil
default:
return nil, errors.New("invalid signature")
}
}).
Maybe()
h := &handler{next: next, fbAuth: fbAuth}
req := httptest.NewRequest(http.MethodPost, "/", nil)
req.Header.Set("Authorization", tc.authorization)
res := httptest.NewRecorder()
h.ServeHTTP(res, req)
require.Equal(t, tc.status, res.Code)
require.Equal(t, tc.body, res.Body.String())
require.Equal(t, tc.nextCalled, nextCalled)
if tc.tokenUID != "" {
require.Equal(t, tc.tokenUID, TokenFromContext(nextCtx).UID)
} else {
require.Nil(t, TokenFromContext(nextCtx))
}
if tc.rawToken != "" {
require.Equal(t, tc.rawToken, RawTokenFromContext(nextCtx))
} else {
require.Empty(t, RawTokenFromContext(nextCtx))
}
})
}
}