-
Notifications
You must be signed in to change notification settings - Fork 8
/
gofiberfirebaseauth_test.go
266 lines (202 loc) · 5.67 KB
/
gofiberfirebaseauth_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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package gofiberfirebaseauth
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
firebase "firebase.google.com/go"
"github.com/gofiber/fiber/v2"
"github.com/joho/godotenv"
"google.golang.org/api/option"
)
// Global varible for IDToken
var IDToken string
func init() {
localDev := os.Getenv("STAGE") == ""
// loads values from .env into the system
if localDev { // no in build, only in local
if err := godotenv.Load(); err != nil {
log.Print("No .env file found")
}
}
// Get idToken form firebase and save globally
getIDToken()
}
/**
*
* Helper Functions
*
*/
// Get Idtoken by calling Firebase Auth Rest API. DOCS:: https://firebase.google.com/docs/reference/rest/auth
func getIDToken() {
// curl 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY]' \
// -H 'Content-Type: application/json' \
// --data-binary '{"email":"[user@example.com]","password":"[PASSWORD]","returnSecureToken":true}'
// Load envirment variable
testUserEmail, emailExit := os.LookupEnv("TEST_USER_EMAIL")
testUserPassword, passExit := os.LookupEnv("TEST_USER_PASSWORD")
if !emailExit || !passExit {
log.Println("Please provide TEST_USER_EMAIL and TEST_USER_PASSWORD")
}
webAPIKey, keyExitx := os.LookupEnv("WEB_API_KEY")
if !keyExitx {
log.Println("WEB_API_KEY is not configured.Please add the WEB_API_KEY to your .env")
}
// preparing payload
type Payload struct {
Email string `json:"email"`
Password string `json:"password"`
ReturnSecureToken bool `json:"returnSecureToken"`
}
data := Payload{
Email: testUserEmail,
Password: testUserPassword,
ReturnSecureToken: true,
}
payloadBytes, err := json.Marshal(data)
if err != nil {
log.Println("Error getting idToken")
}
body := bytes.NewReader(payloadBytes)
req, err := http.NewRequest("POST", "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key="+webAPIKey+"", body)
if err != nil {
log.Println("Error generating idToken")
}
req.Header.Set("content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Println("Error generating IDToken")
}
type response struct {
IDToken string `json:"idToken"`
}
defer resp.Body.Close()
bodyResponse, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Error Getting IDToken")
}
var Response response
json.Unmarshal(bodyResponse, &Response)
IDToken = Response.IDToken
}
// Create FirebaseAuth
func CreateFirebaseAuthApp() (*firebase.App, error) {
serviceAccountJSON, fileExi := os.LookupEnv("SERVICE_ACCOUNT_JSON")
if !fileExi {
log.Println("fireauth config not found")
}
// Create a firebase app
opt := option.WithCredentialsFile(serviceAccountJSON)
fireApp, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return nil, err
}
return fireApp, nil
}
/**
*
* TEST CASES
*
*/
// 1 TEST for Malformed Token
func TestWithMalformedToken(t *testing.T) {
// intialiae fiber app and firebase app
app := fiber.New()
fireApp, err := CreateFirebaseAuthApp()
if err != nil {
t.Fatalf(`%s: %s`, t.Name(), err)
}
// configure the gofiberfirebaseauth
app.Use(New(Config{
FirebaseApp: fireApp,
}))
// hard coded Invalid Id token
idToken := "0i30-ir-302309ei3f30-i32-0f-2300"
// crete test route
app.Get("/testauth", func(c *fiber.Ctx) error {
msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
return c.SendString(msg) // => Hello john 👋!
})
req := httptest.NewRequest("GET", "/testauth", nil)
req.Header.Set("Authorization", idToken)
// test
resp, err := app.Test(req)
if err != nil {
t.Fatalf(`%s: %s`, t.Name(), err)
}
if resp.StatusCode == fiber.StatusBadRequest || resp.StatusCode == fiber.StatusUnauthorized {
// fmt.Println("TEST case pass for TestWithMalformedToken")
} else {
log.Fatalf(`%s: %s`, t.Name(), err)
}
}
// 2 TEST for Ignore Url
func TestIgnoreUrlsWorking(t *testing.T) {
// t.Parallel()
app := fiber.New()
// Create firebase app
fireApp, errf := CreateFirebaseAuthApp()
if errf != nil {
t.Fatalf(`%s: %s`, t.Name(), errf)
}
app.Use(New(Config{
FirebaseApp: fireApp,
IgnoreUrls: []string{"GET::/testauth", "POST::/testauth "},
}))
// crete test route
app.Get("/testauth", func(c *fiber.Ctx) error {
msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
return c.SendString(msg) // => Hello john 👋!
})
req := httptest.NewRequest("GET", "/testauth", nil)
// test
_, err := app.Test(req)
if err != nil {
t.Fatalf(`%s: %s`, t.Name(), err)
}
}
// 3 TEST for FirebaseApp
func TestWithoutFirebaseApp(t *testing.T) {
// t.Parallel()
app := fiber.New()
// Config without firebase App object
app.Use(New(Config{}))
// crete test route
app.Get("/testauth", func(c *fiber.Ctx) error {
msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
return c.SendString(msg) // => Hello john 👋!
})
req := httptest.NewRequest("GET", "/testauth", nil)
// test
_, err := app.Test(req)
if err != nil {
t.Fatalf(`%s: %s`, t.Name(), err)
}
}
// 4 TEST token with valid authorization token
func TestTokenWithCorrectToken(t *testing.T) {
app := fiber.New()
fireApp, err := CreateFirebaseAuthApp()
if err != nil {
t.Fatalf(`%s: %s`, t.Name(), err)
}
// configure the gofiberfirebaseauth
app.Use(New(Config{
FirebaseApp: fireApp,
}))
req := httptest.NewRequest("GET", "/testauth", nil)
req.Header.Set("Authorization", IDToken)
resp, err := app.Test(req)
if err != nil {
t.Fatalf(`%s: %s`, t.Name(), err)
}
if resp.StatusCode == fiber.StatusBadRequest || resp.StatusCode == fiber.StatusUnauthorized {
fmt.Println("TEST case FAILED for TestTokenWithCorrectToken ")
}
}