-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
683 lines (613 loc) · 17.5 KB
/
auth.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
package auth
import (
"bytes"
"errors"
"fmt"
"net/http"
"regexp"
"strings"
"github.com/goccy/go-json"
"github.com/benitogf/katamari"
"github.com/benitogf/katamari/objects"
"github.com/benitogf/pivot"
"github.com/gorilla/mux"
"golang.org/x/crypto/bcrypt"
)
// User :
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Phone string `json:"phone"`
Account string `json:"account"`
Password string `json:"password,omitempty"`
Role string `json:"role"`
}
// Credentials :
type Credentials struct {
Account string `json:"account"`
Password string `json:"password,omitempty"`
Token string `json:"token"`
Role string `json:"role"`
}
// TokenAuth :
type TokenAuth struct {
tokenStore *JwtStore
store katamari.Database
getter TokenGetter
UnauthorizedHandler http.HandlerFunc
client *http.Client
}
// TokenGetter :
type TokenGetter interface {
GetTokenFromRequest(req *http.Request) string
}
// Token :
type Token interface {
IsExpired() bool
fmt.Stringer
ClaimGetter
}
// ClaimSetter :
type ClaimSetter interface {
SetClaim(string, interface{}) ClaimSetter
}
// ClaimGetter :
type ClaimGetter interface {
Claims(string) interface{}
}
// BearerGetter :
type BearerGetter struct {
Header string
}
var (
userRegexp = regexp.MustCompile("^[a-zA-Z0-9_]{2,15}$")
emailRegexp = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
roles = map[string]string{"root": "root"}
)
// DefaultUnauthorizedHandler :
func DefaultUnauthorizedHandler(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "unauthorized")
}
// GetTokenFromRequest :
func (b *BearerGetter) GetTokenFromRequest(req *http.Request) string {
// log.Println("header:", req.Header)
authStr := req.Header.Get(b.Header)
if !strings.HasPrefix(authStr, "Bearer ") {
return ""
}
return authStr[7:]
}
// NewHeaderBearerTokenGetter :
func NewHeaderBearerTokenGetter(header string) *BearerGetter {
return &BearerGetter{
Header: header,
}
}
// New :
//
// # Returns a TokenAuth object implemting Handler interface
//
// if a handler is given it proxies the request to the handler
//
// if a unauthorizedHandler is provided, unauthorized requests
//
// will be handled by this HandlerFunc, otherwise a default
//
// unauthorized handler is used.
//
// store is the TokenStore that stores and verify the tokens
func New(tokenStore *JwtStore, store katamari.Database) *TokenAuth {
t := &TokenAuth{
tokenStore: tokenStore,
store: store,
}
t.getter = NewHeaderBearerTokenGetter("Authorization")
t.UnauthorizedHandler = DefaultUnauthorizedHandler
return t
}
// Verify : wrap a HandlerFunc to be authenticated
func (t *TokenAuth) Verify(req *http.Request) bool {
_, err := t.Authenticate(req)
return err == nil
}
// Authenticate :
func (t *TokenAuth) Authenticate(r *http.Request) (Token, error) {
strToken := t.getter.GetTokenFromRequest(r)
if strToken == "" {
return nil, errors.New("token required")
}
token, err := t.tokenStore.CheckToken(strToken)
if err != nil {
return nil, err
}
return token, nil
}
// Audit : get websocket token, return token claims
func (t *TokenAuth) Audit(r *http.Request) (string, string, error) {
// get the header from a websocket connection
// https://stackoverflow.com/questions/22383089/is-it-possible-to-use-bearer-authentication-for-websocket-upgrade-requests
if r.Header.Get("Upgrade") == "websocket" && r.Header.Get("Sec-WebSocket-Protocol") != "" {
r.Header.Add("Authorization", "Bearer "+strings.Replace(r.Header.Get("Sec-WebSocket-Protocol"), "bearer, ", "", 1))
}
token, err := t.Authenticate(r)
if err != nil {
return "", "", err
}
role := token.Claims("role").(string)
account := token.Claims("iss").(string)
return role, account, nil
}
// Authorize method
func (t *TokenAuth) getUser(account string) (User, error) {
var user User
raw, err := t.store.Get("users/" + account)
if err != nil {
return user, err
}
var obj objects.Object
err = json.Unmarshal(raw, &obj)
if err != nil {
return user, err
}
err = json.Unmarshal([]byte(obj.Data), &user)
if err != nil {
return user, err
}
return user, nil
}
func (t *TokenAuth) getUsers() ([]User, error) {
var users []User
raw, err := t.store.Get("users/*")
if err != nil {
return nil, err
}
var objects []objects.Object
err = json.Unmarshal(raw, &objects)
if err != nil {
return nil, err
}
for _, object := range objects {
var user User
err = json.Unmarshal([]byte(object.Data), &user)
if err == nil {
user.Password = ""
users = append(users, user)
}
}
return users, nil
}
func getCredentials(r *http.Request) (Credentials, error) {
dec := json.NewDecoder(r.Body)
var credentials Credentials
err := dec.Decode(&credentials)
if err != nil {
return credentials, err
}
return credentials, nil
}
func (t *TokenAuth) checkCredentials(credentials Credentials) (User, error) {
user, err := t.getUser(credentials.Account)
if err != nil {
return user, errors.New("user not found")
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(credentials.Password))
if err != nil {
return user, errors.New("wrong password")
}
return user, nil
}
// Profile returns to the client the correspondent user profile for the token provided
func (t *TokenAuth) Profile(pivotIP string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if pivotIP != "" {
pivot.Synchronize(t.client, t.store, pivotIP, []string{"users/*"})
}
token, err := t.Authenticate(r)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "%s", errors.New("this request is not authorized"))
return
}
switch r.Method {
case "GET":
user, err := t.getUser(token.Claims("iss").(string))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "bad token, couldnt find the issuer profile")
return
}
user.Password = ""
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
enc.Encode(&user)
return
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Method not suported")
return
}
}
}
// Authorize will claim a token on POST and refresh the claim on PUT
func (t *TokenAuth) Authorize(pivotIP string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if pivotIP != "" {
pivot.Synchronize(t.client, t.store, pivotIP, []string{"users/*"})
}
credentials, err := getCredentials(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
user, err := t.getUser(credentials.Account)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err.Error())
return
}
switch r.Method {
case "POST":
_, err = t.checkCredentials(credentials)
if err != nil {
w.WriteHeader(http.StatusForbidden)
fmt.Fprint(w, err.Error())
return
}
case "PUT":
if credentials.Token != "" {
oldToken, err := t.tokenStore.CheckToken(credentials.Token)
if err == nil {
w.WriteHeader(http.StatusNotModified)
fmt.Fprint(w, errors.New("token not expired"))
return
}
if err.Error() != "token expired" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, err)
return
}
if oldToken.Claims("iss").(string) != credentials.Account {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, errors.New("token doesn't match the account"))
return
}
} else {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, errors.New("empty token"))
return
}
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Method not suported")
return
}
newToken := t.tokenStore.NewToken()
newToken.SetClaim("iss", credentials.Account)
newToken.SetClaim("role", user.Role)
credentials.Password = ""
credentials.Role = user.Role
credentials.Token = newToken.String()
w.Header().Add("content-type", "application/json")
enc := json.NewEncoder(w)
enc.Encode(&credentials)
}
}
// Register will create a new user
func (t *TokenAuth) Register(w http.ResponseWriter, r *http.Request) {
var user User
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
err := decoder.Decode(&user)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", err)
return
}
if user.Account == "" || user.Name == "" || user.Password == "" || user.Email == "" || user.Phone == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("new user data incomplete"))
return
}
if !userRegexp.MatchString(user.Account) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("account cannot contain special characters, only numbers or lowercase letters and character count must be between 2 and 15"))
return
}
if len(user.Password) < 3 || len(user.Password) > 88 {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("password character count must be between 2 and 88"))
return
}
if !userRegexp.MatchString(user.Phone) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("phone cannot contain special characters othen than '-' and character count must be between 6 and 15"))
return
}
if !emailRegexp.MatchString(user.Email) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("invalid email address"))
return
}
_, err = t.getUser(user.Account)
if err == nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("account name taken"))
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.MinCost)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
user.Password = string(hash)
user.Role = "user"
role, otherRole := roles[user.Account]
if otherRole {
user.Role = role
}
dataBytes := new(bytes.Buffer)
json.NewEncoder(dataBytes).Encode(user)
_, err = t.store.Set("users/"+user.Account, dataBytes.String())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
newToken := t.tokenStore.NewToken()
newToken.SetClaim("iss", user.Account)
newToken.SetClaim("role", user.Role)
credentials := Credentials{
Account: user.Account,
Token: newToken.String(),
Role: user.Role,
}
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
enc.Encode(&credentials)
}
// NewPassword is for updating account password
func (t *TokenAuth) NewPassword(w http.ResponseWriter, r *http.Request) {
token, err := t.Authenticate(r)
authorized := (err == nil)
role := "user"
if authorized {
role = token.Claims("role").(string)
}
// root authorization
if role != "root" {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "Method not suported for your role")
return
}
account := mux.Vars(r)["account"]
user, err := t.getUser(account)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, err.Error())
return
}
switch r.Method {
case "PUT":
dec := json.NewDecoder(r.Body)
var userData User
err := dec.Decode(&userData)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, errors.New("invalid user data"))
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(userData.Password), bcrypt.MinCost)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
user.Password = string(hash)
dataBytes := new(bytes.Buffer)
json.NewEncoder(dataBytes).Encode(user)
_, err = t.store.Set("users/"+user.Account, dataBytes.String())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err)
return
}
user.Password = ""
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.Encode(&user)
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Method not suported")
return
}
}
// Available will check if an account is taken
func (t *TokenAuth) Available(pivotIP string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if pivotIP != "" {
pivot.Synchronize(t.client, t.store, pivotIP, []string{"users/*"})
}
account := r.FormValue("account")
_, err := t.getUser(account)
if err == nil {
w.WriteHeader(http.StatusConflict)
fmt.Fprintf(w, "account taken")
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "account available")
}
}
// Create will create a new user (root only access)
func (t *TokenAuth) Create(w http.ResponseWriter, r *http.Request) {
token, err := t.Authenticate(r)
authorized := (err == nil)
role := "user"
if authorized {
role = token.Claims("role").(string)
}
if !authorized {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "Method not suported for your role")
return
}
// root authorization
if role != "root" {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "Method not suported for your role")
return
}
var user User
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
err = decoder.Decode(&user)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", err)
return
}
if user.Account == "" || user.Name == "" || user.Password == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("new user data incomplete"))
return
}
if !userRegexp.MatchString(user.Account) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("account cannot contain special characters, only numbers or lowercase letters and character count must be between 2 and 15"))
return
}
if len(user.Password) < 3 || len(user.Password) > 88 {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("password character count must be between 2 and 88"))
return
}
_, err = t.getUser(user.Account)
if err == nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "%s", errors.New("account name taken"))
return
}
}
// Users will send the user list to a root user
func (t *TokenAuth) Users(pivotIP string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
token, err := t.Authenticate(r)
authorized := (err == nil)
role := "user"
if authorized {
role = token.Claims("role").(string)
}
// root authorization
if !authorized || role != "root" {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "Method not suported for your role")
return
}
if pivotIP != "" {
pivot.Synchronize(t.client, t.store, pivotIP, []string{"users/*"})
}
users, err := t.getUsers()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.Encode(&users)
}
}
// User will send the user list to a root user
func (t *TokenAuth) User(w http.ResponseWriter, r *http.Request) {
token, err := t.Authenticate(r)
authorized := (err == nil)
role := "user"
if authorized {
role = token.Claims("role").(string)
}
// root authorization
if !authorized || role != "root" {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "Method not suported for your role")
return
}
account := mux.Vars(r)["account"]
user, err := t.getUser(account)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, err.Error())
return
}
switch r.Method {
case "GET":
user.Password = ""
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.Encode(&user)
case "DELETE":
err := t.store.Del("users/" + user.Account)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err)
return
}
w.WriteHeader(http.StatusNoContent)
fmt.Fprintf(w, "deleted "+account)
case "POST":
dec := json.NewDecoder(r.Body)
var userData User
err := dec.Decode(&userData)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, errors.New("invalid user data"))
return
}
if userData.Email != "" {
user.Email = userData.Email
}
if userData.Name != "" {
user.Name = userData.Name
}
if userData.Phone != "" {
user.Phone = userData.Phone
}
if userData.Role != "" {
user.Role = userData.Role
}
dataBytes := new(bytes.Buffer)
json.NewEncoder(dataBytes).Encode(user)
_, err = t.store.Set("users/"+user.Account, dataBytes.String())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err)
return
}
user.Password = ""
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.Encode(&user)
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Method not suported")
return
}
}
// Router handle for auth enpoints
func (t *TokenAuth) Router(server *katamari.Server) {
server.Router.HandleFunc("/authorize", t.Authorize(server.Pivot))
server.Router.HandleFunc("/profile", t.Profile(server.Pivot))
server.Router.HandleFunc("/users", t.Users(server.Pivot)).Methods("GET")
server.Router.HandleFunc("/user/{account:[a-zA-Z\\d]+}", t.User).Methods("GET", "POST", "DELETE")
server.Router.HandleFunc("/password/{account:[a-zA-Z\\d]+}", t.NewPassword).Methods("PUT")
server.Router.HandleFunc("/register", t.Register).Methods("POST")
server.Router.HandleFunc("/create", t.Create).Methods("POST")
server.Router.HandleFunc("/available", t.Available(server.Pivot)).Queries("account", "{[a-zA-Z\\d]}").Methods("GET")
t.client = server.Client
pivot.Router(server.Router, t.store, server.Client, server.Pivot, []string{"users/*"})
}