-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
executable file
·627 lines (578 loc) · 15.9 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
//"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gorilla/context"
"github.com/gorilla/mux"
"github.com/satori/go.uuid"
"github.com/demsullivan/owl"
"time"
)
//type key int
//const TokenKey key = 0
//const AdminKey key = 1
type S3PutRequest struct {
Bucket string `json:"bucket"`
Key string `json:"key"`
URL string `json:"url"`
Error string `json:"error"`
}
type UUID struct {
UUID string `json:"uuid"`
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "To be implemented.\n")
}
func ListContentHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "To be implemented.\n")
}
func CreateContentReservationHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := r.Body.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
c := Content{}
if err := json.Unmarshal(body, &c); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = CreateContentReservation(&c)
if err != nil {
c.Error = err
}
id := ID{}
id.ID = c.ID.String()
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func ReadContentHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
contentID := vars["id"]
e, err := NewestEntryForContentID(contentID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(e); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func UpdateContentHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := r.Body.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
e := Entry{}
if err := json.Unmarshal(body, &e); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
e.ID = uuid.NewV4()
e.Timestamp = time.Now()
err = CreateEntryForContentID(&e)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(e); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func ListTagsHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "To be implemented.\n")
}
func CreateTagHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
vars := mux.Vars(r)
tag := vars["tag"]
appID := vars["app-uuid"]
err := CreateTag(tag, appID)
if err != nil {
log.Println(err)
}
}
func DeleteTagHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
fmt.Fprint(w, "To be implemented.\n")
}
func ReadAllContentForTagHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
tag := vars["tag"]
appID := vars["app-uuid"]
e, err := AllContentForTag(tag, appID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(e); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func ReadNewestLocalizedContentEntriesForTagHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
tag := vars["tag"]
locale := vars["locale"]
appID := vars["app-uuid"]
e, err := NewestLocalizedContentEntriesForTag(tag, locale, appID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(e); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func AssignTagToContentHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
vars := mux.Vars(r)
contentID := vars["content-uuid"]
tag := vars["tag"]
appID, err := fromContext("AppID", r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := TagContent(contentID, tag, appID); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func AssetUploadURLHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := r.Body.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
put := S3PutRequest{}
if err := json.Unmarshal(body, &put); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
svc := s3.New(session.New(), &aws.Config{
Region: aws.String("us-east-1"),
Credentials: credentials.NewEnvCredentials(),
})
por, _ := svc.PutObjectRequest(&s3.PutObjectInput{
Bucket: aws.String(put.Bucket),
Key: aws.String(put.Key),
})
url, err := por.Presign(15 * time.Minute)
if err != nil {
put.Error = err.Error()
w.WriteHeader(http.StatusBadRequest)
} else {
put.URL = url
w.WriteHeader(http.StatusOK)
}
if err := json.NewEncoder(w).Encode(&put); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func LoginHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := r.Body.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user := User{}
if err := json.Unmarshal(body, &user); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userPtr, err := Login(&user)
if err != nil {
if err.Error() == "QueryRow / Scan select from user | sql: no rows in result set" {
w.WriteHeader(http.StatusUnauthorized)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
} else {
user = *userPtr
w.Header().Set("Authorization", *user.Token)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(user); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
userID, err := fromContext("UserID", r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = Logout(userID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := r.Body.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user := User{}
if err := json.Unmarshal(body, &user); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userPtr, err := CreateUser(&user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
user = *userPtr
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(user); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
id := r.URL.Query().Get("id")
appID, err := fromContext("AppID", r)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
if id != "" {
u, err := GetUser(id, appID)
user := *u
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
if err := json.NewEncoder(w).Encode(user); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
} else {
users, err := GetAllUsers(appID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
if err := json.NewEncoder(w).Encode(users); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
}
func DeleteUserHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
var err error
userID := r.URL.Query().Get("user-id")
appID := r.URL.Query().Get("app-id")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if userID == "" {
userID, err = fromContext("UserID", r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if appID == "" {
appID, err = fromContext("AppID", r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
err = DeleteUser(userID, appID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func AuthenticateTokenHandler(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
_, err := Authenticate(token)
if err == nil {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
func AuthHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("Accept", "application/json")
token := r.Header.Get("Authorization")
if token != "" {
claims, err := Authenticate(token)
if err == nil {
//w.Header().Set("Authorization", token)
context.Set(r, "Token", token)
context.Set(r, "UserID", claims["UserID"])
context.Set(r, "FirstName", claims["FirstName"])
context.Set(r, "LastName", claims["LastName"])
context.Set(r, "Email", claims["Email"])
context.Set(r, "Username", claims["Username"])
context.Set(r, "AppID", claims["AppID"])
context.Set(r, "TokenExpires", claims["exp"])
context.Set(r, "TokenCreated", claims["iat"])
fmt.Println("TokenExpires: " + claims["exp"].(string))
fmt.Println("TokenCreated: " + claims["iat"].(string))
}
}
h.ServeHTTP(w, r)
})
}
func verifyAdmin(r *http.Request) bool {
// Temp using AppID below from within the tokenID
// as a proxy for validating a user is an admin.
val, err := fromContext("AppID", r)
if err != nil {
return false
}
// This test below is insuffient. Needs real test.
if val == "" {
return false
}
return true
}
func NewUUIDHandler(w http.ResponseWriter, r *http.Request) {
uuid := UUID{}
uuid.UUID = NewUUID()
if err := json.NewEncoder(w).Encode(uuid); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func ForgotPasswordHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := r.Body.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var inputUser User
var dbUser *User
var msg owl.Message
var msgParams owl.Params
var newPass string
if err := json.Unmarshal(body, &inputUser); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if inputUser.Email == "" {
http.Error(w, "Invalid e-mail address!", http.StatusBadRequest)
return
}
if inputUser.AppID.String() == "" {
http.Error(w, "Invalid app ID!", http.StatusBadRequest)
return
}
dbUser, err = GetUserByEmail(inputUser.Email, inputUser.AppID.String())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
newPass = generatePassword()
toEmails := []string{""}
toEmails[0] = dbUser.Email
msg.From = "[email protected]"
msg.To = toEmails
msg.Subject = "Schutt Sports Password Reset Request"
msg.Body = "Hello,\n" +
"You are receiving this e-mail because you requested your admin password for schuttsports.com to be reset.\n\n" +
"Your new password is " + newPass + ". Please login using your username " +
"and this new password at https://schuttsports.com/login"
msgParams.Provider = owl.AWSSES
err = msg.Send(&msgParams)
if err != nil {
http.Error(w, "msg.Send | " + err.Error(), http.StatusInternalServerError)
return
}
err = UpdatePassword(newPass, dbUser.ID.String())
if err != nil {
http.Error(w, "UpdatePassword | " + err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(struct{}{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func UpdatePasswordHandler(w http.ResponseWriter, r *http.Request) {
if !verifyAdmin(r) {
http.Error(w, "Unauthorized!", http.StatusUnauthorized)
return
}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := r.Body.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var user User
if err := json.Unmarshal(body, &user); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userID, err := fromContext("UserID", r)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
if user.ID.String() == "00000000-0000-0000-0000-000000000000" {
err = UpdatePassword(user.Password, userID)
} else {
err = UpdatePassword(user.Password, user.ID.String())
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(struct{}{}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func UserCryptoBootstrapHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := r.Body.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
crypto := UserCryptoBootstrap{}
if err := json.Unmarshal(body, &crypto); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = validatePassword(crypto.PlainText)
if err != nil {
//
}
salt, err := createSalt(SALT_BYTES)
if err != nil {
//
}
hashedPassword, err := hashPassword(crypto.PlainText, crypto.Salt)
if err != nil {
//
}
privateKey, publicKey, err := createKeys()
if err != nil {
//
}
crypto.Hash = hashedPassword
crypto.Salt = salt
crypto.PrivateKey = privateKey
crypto.PublicKey = publicKey
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(&crypto); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
/*
UTILITIES
*/
func fromContext(key string, r *http.Request) (string, error) {
val, ok := context.GetOk(r, key)
if !ok {
return "", errors.New("Failed to retrieve value from context with key.")
}
v, ok := val.(string)
if !ok {
return "", errors.New("Type coersion of interface value to string failed.")
}
return v, nil
}