-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
766 lines (679 loc) · 21.3 KB
/
handlers.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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
package notary
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/NTRYPlatform/ntry-backend/config"
"github.com/NTRYPlatform/ntry-backend/eth"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/context"
"github.com/gorilla/mux"
)
type Token struct {
Token string `json:"token"`
}
func Index(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler.data = "Welcome to Notary Platform"
handler.ServeHTTP(w, r)
})
}
}
func NotImplemented(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler.data = "Function not implemented yet!"
handler.ServeHTTP(w, r)
})
}
}
func Logging(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler.logger.Info(fmt.Sprintf("[ntry] new request %s: %s %s", r.UserAgent(), r.Method, r.URL))
h.ServeHTTP(w, r)
})
}
}
//TODO
func Authorization(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
})
}
}
func CreateUser(handler *Handler, email *emailConf) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u := &User{}
if err := decode(r, u); err != nil {
// Set error data and jump to the last handler
// implemented by *Handler
handler.status = http.StatusBadRequest
handler.data = err
handler.ServeHTTP(w, r)
return
}
// check if user is valid
if err := u.OK(); err != nil {
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
// check for pre-existence
if exists, err := handler.db.UserExistsByUniqueField(u); err != nil {
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
} else if exists {
handler.logger.Error(
fmt.Sprintf("[handler ] User with either of these values already exists!user: %v, err: %v", u, err))
handler.status = http.StatusInternalServerError
handler.data = "User already Exists"
handler.ServeHTTP(w, r)
return
} else {
cTime := time.Now().UTC()
u.RegTime = &cTime
u.AccountVerified = false
fmt.Printf("Password: %s", u.Password)
if u.Password, err = HashPassword(u.Password); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Couldn't hash password! user: %v, err: %v", u, err))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
if err := handler.db.Insert(u, UserCollection); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] User insertion to db error! user: %v, err: %v", u, err))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
handler.logger.Info(fmt.Sprint("[handler ] User successfully saved to db!", u.String()))
msg := verificationAccountMessage(email.from, u.EmailAddress, u.UID)
if err := email.sendEmail(u.EmailAddress, msg); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to send verification email! user: %v, err: %v", u, err))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
handler.status = http.StatusCreated
handler.data = u.UID
}
h.ServeHTTP(w, r)
})
}
}
//TODO: shouldn't update everything/ handle the password update cond
func UpdateUserInfo(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u := &User{}
if err := decode(r, u); err != nil {
// Set error data and jump to the last handler
// implemented by *Handler
handler.status = http.StatusBadRequest
// w.Header().Set("Content-Type", "application/json; charset=UTF-8")
handler.data = err
handler.ServeHTTP(w, r)
return
}
uid := context.Get(r, "uid")
(*u).UID = uid.(string)
if err := handler.db.UpdateUser(u); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to update user record!user: %v, err: %v", u, err))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = true
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func SearchUsers(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := mux.Vars(r)
users, err := handler.db.SearchUserByName(v["q"])
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to fetch users with query: %v", v["q"]))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = users
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func GetUserContacts(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u := context.Get(r, "uid")
users, err := handler.db.FetchUserContacts(u.(string))
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to fetch users with query: %v", u.(string)))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = users
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func GetUser(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := mux.Vars(r)
uid := v["user"]
users := handler.db.GetUserByUID(uid)
if users == nil {
msg := fmt.Sprintf("Failed to fetch users with query: %v", uid)
handler.logger.Error(
fmt.Sprintf("[handler ] %v", msg))
handler.status = http.StatusInternalServerError
handler.data = msg
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = users
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func GetUserBalance(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uid := context.Get(r, "uid")
//TODO: find a more efficient method.. maybe add the eth address in JWT?
user := handler.db.GetUserByUID(uid.(string))
if user == nil {
msg := fmt.Sprintf("Failed to fetch users with query: %v", uid)
handler.logger.Error(
fmt.Sprintf("[handler ] %v", msg))
handler.status = http.StatusInternalServerError
handler.data = msg
handler.ServeHTTP(w, r)
return
}
bal, err := handler.ec.NotaryBalance(user.EthAddress)
if err != nil {
msg := fmt.Sprintf("Failed to get notary balance: %v", uid)
handler.logger.Error(
fmt.Sprintf("[handler ] %v", msg))
handler.status = http.StatusInternalServerError
handler.data = msg
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = *bal
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func AddContact(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := mux.Vars(r)
u := context.Get(r, "uid")
c := UserContact{PUid: u.(string), SUid: v["u"]}
if err := handler.db.Insert(&c, UserContacts); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] User insertion to db error! user: %v, err: %v", u, err))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = true
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func CreateCarContract(handler *Handler, contracts chan interface{}) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c := ð.CarContract{}
if err := decode(r, c); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Car contract couldn't be parsed! user: %v, err: %v", c, err))
handler.status = http.StatusBadRequest
handler.data = "Car contract couldn't be parsed!"
handler.ServeHTTP(w, r)
return
}
c.CID = int64(time.Now().Unix())
//TODO: check if the contract is valid
if err := handler.db.Insert(c, CarContractCollection); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Car contract insertion to db error! user: %v, err: %v", c, err))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
handler.logger.Info(fmt.Sprint("[handler ] Contract successfully saved to db!", (*c).CID))
uid := context.Get(r, "uid")
cn := eth.ContractNotification{Contract: *c}
if cn.NotifyParty = c.Seller; c.Seller == uid {
cn.NotifyParty = c.Buyer
}
handler.status = http.StatusCreated
handler.data = c.CID
contracts <- cn
h.ServeHTTP(w, r)
})
}
}
func SubmitCarContract(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := mux.Vars(r)
cid := v["cid"]
//TODO: handle
i, err := strconv.ParseInt(cid, 10, 64)
c := handler.db.GetContractByCID(i)
buyer, seller, err := handler.db.GetContractParticipants(c.Buyer, c.Seller)
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Can't get contract participants db error! cid: %v,", cid))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
err = handler.ec.CarDeal(c.Hash(), buyer, seller, i)
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Can't write contract to the blockchain! cid: %v,", cid))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
handler.status = http.StatusOK
h.ServeHTTP(w, r)
})
}
}
func UpdateCarContract(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c := ð.CarContract{}
if err := decode(r, c); err != nil {
// Set error data and jump to the last handler
// implemented by *Handler
handler.status = http.StatusBadRequest
handler.data = err
handler.ServeHTTP(w, r)
return
}
if err := handler.db.UpdateContract(c); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to update car contract! contract: %v, err: %v", c, err))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = true
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func GetUserContracts(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u := context.Get(r, "uid")
users, err := handler.db.FetchUserContracts(u.(string))
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to fetch user contracts with query: %v", u.(string)))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = users
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func GetContract(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := mux.Vars(r)
cid, err := strconv.ParseInt(v["cid"], 10, 64)
if err != nil {
msg := fmt.Sprintf("Failed to get cid: %v", cid)
handler.logger.Error(
fmt.Sprintf("[handler ] %v", msg))
handler.status = http.StatusBadRequest
handler.data = msg
handler.ServeHTTP(w, r)
return
}
c := handler.db.GetContractByCID(cid)
if c == nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to fetch user contracts with query: %v", cid))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = c
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func GetContractFieldsList(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f := eth.GetContractFields()
// Follow the normal flow
handler.status = http.StatusOK
handler.data = f
w.Header().Set("Content-Type", "application/json")
h.ServeHTTP(w, r)
return
})
}
}
func LoginHandler(handler *Handler, conf *config.Config) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u := &LoginUser{}
user := &User{}
var err error
if err = decode(r, u); err != nil {
// Set error data and jump to the last handler
// implemented by *Handler
handler.status = http.StatusForbidden
handler.data = err
handler.ServeHTTP(w, r)
return
}
// check if user is valid
if err := u.OK(); err != nil {
handler.status = http.StatusInternalServerError
handler.data = u.OK()
handler.ServeHTTP(w, r)
return
}
if user, err = handler.db.LoginUserValidation(u); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to verify user! user: %v, err: %v", u, err))
handler.status = http.StatusForbidden
handler.data = err
handler.ServeHTTP(w, r)
return
}
if user == nil {
handler.logger.Info(
fmt.Sprintf("[handler ] Invalid credentials! user: %v", user))
handler.status = http.StatusForbidden
handler.data = "Invalid credentials"
handler.ServeHTTP(w, r)
return
}
//TODO: trigger eth network check
// Create a map to store user claims
claims := jwt.StandardClaims{
IssuedAt: time.Now().Unix(),
// expires in an hour
ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
//TODO: change in production - should be configurable
Issuer: conf.GetServerAddress(),
Id: (*user).UID,
}
// Create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
pvtKey, err := conf.GetPvtKey()
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Unable to get private key! user: %v, err: %v", user, err))
handler.status = http.StatusInternalServerError
handler.data = "Server Error" // TODO: may be some meaningful message
handler.ServeHTTP(w, r)
return
}
tokenString, err := token.SignedString(pvtKey)
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Error while signing the token! user: %v, err: %v", user, err))
handler.status = http.StatusInternalServerError
handler.data = "Error while signing the token"
handler.ServeHTTP(w, r)
return
}
json, err := json.Marshal(&Token{tokenString})
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Error in json marshaling of token string! user: %v, err: %v", user, err))
handler.status = http.StatusInternalServerError
handler.data = "Internal Error"
handler.ServeHTTP(w, r)
return
}
// Follow the normal flow
handler.status = http.StatusOK
handler.data = string(json)
h.ServeHTTP(w, r)
})
}
}
func UploadAvatar(handler *Handler, conf *config.Config) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseMultipartForm(32 << 20)
file, fheader, err := r.FormFile("uploadfile")
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Error while parsing file: %v", err))
handler.status = http.StatusInternalServerError
handler.data = "Error while parsing file"
handler.ServeHTTP(w, r)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", fheader.Header)
ext := filepath.Ext(fheader.Filename)
uid := context.Get(r, "uid").(string)
filename := conf.GetAvatarDir() + uid + ext
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Error while trying to save file: %v", err))
handler.status = http.StatusInternalServerError
handler.data = "Error while trying to save file"
handler.ServeHTTP(w, r)
return
}
defer f.Close()
_, err = io.Copy(f, file)
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Error while writing avatar to file: %v", err))
handler.status = http.StatusInternalServerError
handler.data = "Error while trying to store file"
handler.ServeHTTP(w, r)
return
}
u := User{UID: uid, Avatar: filename}
if err := handler.db.UpdateUser(&u); err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Failed to update user record!user: %v, err: %v", u, err))
handler.status = http.StatusInternalServerError
handler.data = err
handler.ServeHTTP(w, r)
return
}
} else {
handler.status = http.StatusMethodNotAllowed
handler.data = "Method not allowed!"
h.ServeHTTP(w, r)
}
})
}
}
func DownloadAvatar(handler *Handler) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
v := mux.Vars(r)
uid := v["uid"]
//TODO: check
u := handler.db.GetUserByUID(uid)
filename := u.Avatar
if len(filename) < 1 {
handler.logger.Error(
fmt.Sprintf("[handler ] No avatar filepath for user: %v", u.UID))
handler.status = http.StatusNoContent
handler.ServeHTTP(w, r)
return
}
f, err := os.OpenFile(u.Avatar, os.O_RDONLY, 0666)
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Error while trying to read from file: %v", err))
handler.status = http.StatusInternalServerError
handler.data = "Error while trying to read from file"
handler.ServeHTTP(w, r)
return
}
defer f.Close()
_, err = io.Copy(w, f)
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Error while writing avatar response: %v", err))
handler.status = http.StatusInternalServerError
handler.data = "Error while writing response"
handler.ServeHTTP(w, r)
return
}
handler.status = http.StatusOK
handler.data = "attachment"
} else {
handler.status = http.StatusMethodNotAllowed
handler.data = "Method not allowed!"
h.ServeHTTP(w, r)
}
})
}
}
/* --------------- Middlewares ---------------- */
//ValidateTokenMiddleware
func ValidateTokenMiddleware(handler *Handler, conf *config.Config) Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var token string
// Get token from the Authorization header
// format: Authorization: Bearer
tokens, ok := r.Header["Authorization"]
if ok && len(tokens) >= 1 {
token = tokens[0]
token = strings.TrimPrefix(token, "Bearer ")
}
// check if token is empty
if token == "" {
handler.logger.Error(
fmt.Sprint("[handler ] Token string is empty!"))
handler.status = http.StatusForbidden
handler.data = "Token string is empty!"
handler.ServeHTTP(w, r)
return
}
// Parse token (TODO: Assuming pubkey will always be there)
key, _ := conf.GetPubKey()
parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
msg := fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
return nil, msg
}
return key, nil
})
if err != nil {
handler.logger.Error(
fmt.Sprintf("[handler ] Token couldn't be parsed! %v", err))
handler.status = http.StatusForbidden
handler.data = err.Error()
handler.ServeHTTP(w, r)
return
}
if parsedToken.Valid {
id := parsedToken.Claims.(jwt.MapClaims)["jti"]
context.Set(r, "uid", id)
handler.status = http.StatusOK
h.ServeHTTP(w, r)
} else {
handler.logger.Error(
fmt.Sprintf("[handler ] Invalid Token! %v", err))
handler.status = http.StatusForbidden
handler.data = "Not allowed"
handler.ServeHTTP(w, r)
}
})
}
}