-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth_test.go
More file actions
519 lines (401 loc) · 13.8 KB
/
auth_test.go
File metadata and controls
519 lines (401 loc) · 13.8 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package auth
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/boltdb/bolt"
"github.com/dahernan/auth/jwt"
"github.com/dahernan/auth/store"
. "github.com/smartystreets/goconvey/convey"
)
var (
// filled in init at the end of the file
options jwt.Options
Private string
Public string
expiredToken string
)
func TestSignIn(t *testing.T) {
Convey("Singin with a http request", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
req, err := httpRequest("POST", "http://testserver", map[string]string{
"email": email,
"password": pass,
})
So(err, ShouldBeNil)
w := httptest.NewRecorder()
route.Signin(w, req)
t.Logf("%d - %s", w.Code, w.Body.String())
var response map[string]string
code, err := responseToJson(w, &response)
So(err, ShouldBeNil)
So(code, ShouldEqual, http.StatusCreated)
So(response["id"], ShouldEqual, email)
})
}
func TestSignInDuplicateUser(t *testing.T) {
Convey("Singin with a http request returns a error for duplicate user", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
route := NewAuthRoute(bs, options)
req, err := httpRequest("POST", "http://testserver", map[string]string{
"email": email,
"password": pass,
})
So(err, ShouldBeNil)
w := httptest.NewRecorder()
route.Signin(w, req)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusBadRequest)
So(w.Body.String(), ShouldContainSubstring, "The email is already in the store")
})
}
func TestLogin(t *testing.T) {
Convey("Login with a http request", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
req, err := httpRequest("POST", "http://testserver", map[string]string{
"email": email,
"password": pass,
})
So(err, ShouldBeNil)
w := httptest.NewRecorder()
route.Login(w, req)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusOK)
var response map[string]string
_, err = responseToJson(w, &response)
So(err, ShouldBeNil)
So(response["token"], ShouldNotBeEmpty)
})
}
func TestLoginNoUser(t *testing.T) {
Convey("Login with a non existing user", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
req, err := httpRequest("POST", "http://testserver", map[string]string{
"email": "[email protected]",
"password": pass,
})
So(err, ShouldBeNil)
w := httptest.NewRecorder()
route.Login(w, req)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusUnauthorized)
So(w.Body.String(), ShouldContainSubstring, "Username or Password Invalid")
})
}
func TestLoginWrongPass(t *testing.T) {
Convey("Login with a wrong password", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
req, err := httpRequest("POST", "http://testserver", map[string]string{
"email": email,
"password": "xyz",
})
So(err, ShouldBeNil)
w := httptest.NewRecorder()
route.Login(w, req)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusUnauthorized)
So(w.Body.String(), ShouldContainSubstring, "Username or Password Invalid")
})
}
func TestAuthMiddleware(t *testing.T) {
Convey("AuthMiddleware works with the right credentials", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
So(err, ShouldBeNil)
// Login to get the token
token := loginRequest(t, route, email, pass)
// Test the Auth
req, err := httpRequest("POST", "http://auth", nil)
So(err, ShouldBeNil)
req.Header.Add("Authorization", strings.Join([]string{"Bearer", token}, " "))
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
w := httptest.NewRecorder()
route.AuthMiddleware(w, req, handler)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusOK)
})
}
func TestAuthMiddlewareNoHeader(t *testing.T) {
Convey("AuthMiddleware unauthorized without auth header", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
// Test the Auth
req, err := httpRequest("POST", "http://auth", nil)
So(err, ShouldBeNil)
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
w := httptest.NewRecorder()
route.AuthMiddleware(w, req, handler)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusUnauthorized)
})
}
func TestAuthMiddlewareInvalidToken(t *testing.T) {
Convey("AuthMiddleware unauthorized with expired token", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
// Test the Auth
req, err := httpRequest("POST", "http://auth", nil)
So(err, ShouldBeNil)
req.Header.Add("Authorization", strings.Join([]string{"Bearer", expiredToken}, " "))
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
w := httptest.NewRecorder()
route.AuthMiddleware(w, req, handler)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusUnauthorized)
})
}
func TestRefreshToken(t *testing.T) {
Convey("Refresh token generates a new valid token", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
So(err, ShouldBeNil)
// Login to get the token
token := loginRequest(t, route, email, pass)
// Test the Auth
req, err := httpRequest("POST", "http://refresh", nil)
So(err, ShouldBeNil)
req.Header.Add("Authorization", strings.Join([]string{"Bearer", token}, " "))
w := httptest.NewRecorder()
route.RefreshToken(w, req)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusOK)
var response map[string]string
_, err = responseToJson(w, &response)
So(err, ShouldBeNil)
So(response["token"], ShouldNotBeEmpty)
So(response["token"], ShouldNotEqual, token)
})
}
func TestRefreshInvalidToken(t *testing.T) {
Convey("Refresh token generates a new valid token", t, func() {
db, bs := initBoltStore(t)
defer db.Close()
route := NewAuthRoute(bs, options)
email := "[email protected]"
pass := "123456"
id, err := bs.Signin(email, pass)
So(err, ShouldBeNil)
So(id, ShouldNotBeEmpty)
So(err, ShouldBeNil)
// Test the Auth
req, err := httpRequest("POST", "http://refresh", nil)
So(err, ShouldBeNil)
req.Header.Add("Authorization", strings.Join([]string{"Bearer", expiredToken}, " "))
w := httptest.NewRecorder()
route.RefreshToken(w, req)
t.Logf("%d - %s", w.Code, w.Body.String())
So(w.Code, ShouldEqual, http.StatusUnauthorized)
})
}
func loginRequest(t *testing.T, route *AuthRoute, email string, pass string) string {
w := httptest.NewRecorder()
req, err := httpRequest("POST", "http://login", map[string]string{
"email": email,
"password": pass,
})
if err != nil {
t.Error(err)
}
route.Login(w, req)
var response map[string]string
_, err = responseToJson(w, &response)
if err != nil {
t.Error(err)
}
token := response["token"]
if token == "" {
t.Error("Token can not be empty")
}
return token
}
func initBoltStore(t *testing.T) (*bolt.DB, store.UserRepository) {
db := newDB(t, "testHttpUsers.db")
bucket := "testBucket"
deleteBucket(t, db, bucket)
bs, err := store.NewBoltStore(db, bucket)
if err != nil {
t.Error(err)
return nil, nil
}
if bs == nil {
t.Error("Could not start Bolt Store")
}
return db, bs
}
func deleteBucket(t *testing.T, db *bolt.DB, bucket string) {
db.Update(func(tx *bolt.Tx) error {
err := tx.DeleteBucket([]byte(bucket))
if err != nil {
t.Errorf("Deleting bucket: %s", err)
return err
}
return nil
})
}
func newDB(t *testing.T, name string) *bolt.DB {
db, err := bolt.Open(name, 0600, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
t.Error(err)
}
return db
}
func httpRequest(method string, endpoint string, requestBody interface{}) (*http.Request, error) {
var err error
requestBytes := make([]byte, 0)
if requestBody != nil {
requestBytes, err = json.Marshal(&requestBody)
if err != nil {
return nil, err
}
}
clientReq, err := http.NewRequest(method, endpoint, bytes.NewReader(requestBytes))
if err != nil {
return nil, err
}
clientReq.Header.Add("Content-Type", "application/json")
clientReq.Header.Add("Accept", "application/json")
return clientReq, err
}
func responseToJson(response *httptest.ResponseRecorder, jsonResponse interface{}) (int, error) {
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return response.Code, err
}
if len(body) > 0 {
err = json.Unmarshal(body, &jsonResponse)
if err != nil {
return response.Code, err
}
}
return response.Code, nil
}
func init() {
// keys for testing, DO NOT USE FOR ANYTHING ELSE
// private -> openssl genrsa -out app.rsa keysize
// public -> openssl rsa -in app.rsa -pubout > app.rsa.pub
Private = `-----BEGIN RSA PRIVATE KEY-----
MIIG5QIBAAKCAYEA6BeD+MrULVzgSgdEWSo9EbZe3f2F9lWLFsuTl57HygQo51ds
i9iDyUaaN6pFr0xo10PzfntnzNDeOTRzIhUQpdWwND8d6UF17RbUad0uCokrVHUl
OycVFSyzOjUEQna70HEQ14MCfIs8DQj4raDAx5pSSWYpBdjYj6T7qcmy1quk1xCY
JHRlrZKtSECrHortRK80SfEC6uPtjBEPymedZnHws3wetn0PwF6YImvSHEcWnK2X
oUroBSNH5uMQWqWcRbcLtwP/O6duUMZUNuVOgEOpiDsBIrtcWF1OTN+6dGLDJg1y
4O6v/fsom9PuFw93n+zy3NzgqAvVVIeVOnSU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M6b_yQnxCZlEMKj97mhPoxYJ6e4x6InvaBxB6_EAOKDBLnooc9Sn0fYP1reICbO-msJxmKg014AignvJ3xwd0"
options = jwt.Options{
SigningMethod: "RS256",
PublicKey: Public,
PrivateKey: Private,
Expiration: 3 * time.Minute,
}
}