forked from Laremere/uhack
/
main.go
722 lines (622 loc) · 18.4 KB
/
main.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
package main
import (
"bytes"
"crypto/rand"
"database/sql"
"encoding/base32"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
var root = "https://vps.redig.us"
var db *sql.DB
func main() {
log.Println("Starting server")
var err error
db, err = sql.Open("mysql", "uhack:@/uhack")
if err != nil {
log.Fatal(err)
}
err = db.Ping()
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/register/", simplePage("register"))
http.HandleFunc("/login/", simplePage("login"))
http.HandleFunc("/about/", simplePage("about"))
http.HandleFunc("/recipes/", recipesHandler)
http.HandleFunc("/registercallback/", registerHandler)
http.HandleFunc("/logincallback/", loginHandler)
http.HandleFunc("/search/", searchHandler)
http.HandleFunc("/recipe/", recipeHandler)
http.HandleFunc("/made/", madeHandler)
http.HandleFunc("/badges/", badgesHandler)
http.HandleFunc("/", simplePage("home"))
//http.HandleFunc("/", indexHandler)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
//Redirect http to https
go func() {
log.Fatal(http.ListenAndServe(":8080",
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, root+r.RequestURI, http.StatusMovedPermanently)
})))
}()
//Serve https
log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil))
}
func simplePage(fileName string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
tem, err := template.ParseFiles("html/"+fileName+".html", "html/defines.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tem.Execute(w, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func authenticate(r *http.Request) (uid int) {
authCookie, err := r.Cookie("authtoken")
if err != nil {
return 0
}
authToken := authCookie.Value
underscorePos := 0
for ; underscorePos < len(authToken); underscorePos++ {
if authToken[underscorePos] == '_' {
break
}
}
var tempUid int64
tempUid, err = strconv.ParseInt(authToken[0:underscorePos], 10, 64)
if err != nil {
log.Println(err)
return 0
}
uid = int(tempUid)
authToken = authToken[underscorePos+1:]
var correctToken string
err = db.QueryRow("SELECT authtoken FROM Users WHERE uid=?", uid).Scan(&correctToken)
if err != nil {
log.Println(err)
return 0
}
if authToken != correctToken {
return 0
}
return
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
username := r.PostForm.Get("username")
email := r.PostForm.Get("email")
first := r.PostForm.Get("first")
last := r.PostForm.Get("last")
var count int
err = db.QueryRow("SELECT COUNT(*) FROM Users WHERE Username=? OR Email=?", username, email).Scan(&count)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if count > 0 {
http.Error(w, "Username or email already in use", http.StatusInternalServerError)
return
}
_, err = db.Exec("INSERT INTO Users (Username, Email, First, Last) VALUES (?,?,?,?)", username, email, first, last)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
loginHandler(w, r)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
username := r.PostForm.Get("username")
var uid int
err = db.QueryRow("SELECT UID FROM Users WHERE UPPER(Username)=UPPER(?)", username).Scan(&uid)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if uid <= 0 {
http.Error(w, "invalid user id", http.StatusInternalServerError)
return
}
var authtoken string
{
var buffer bytes.Buffer
encoder := base32.NewEncoder(base32.StdEncoding, &buffer)
_, err = io.CopyN(encoder, rand.Reader, 20)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = encoder.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
authtoken = string(buffer.Bytes())
}
_, err = db.Exec("UPDATE Users SET authtoken=? WHERE UID=?", authtoken, uid)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
authtoken = strconv.FormatInt(int64(uid), 10) + "_" + authtoken
expire := time.Now().AddDate(0, 0, 7)
const cookieName = "authtoken"
cookie := http.Cookie{
Name: cookieName,
Value: authtoken,
Path: "/",
Domain: "vps.redig.us",
Expires: expire,
RawExpires: expire.Format(time.UnixDate),
MaxAge: 60 * 60 * 24 * 7,
Secure: false,
HttpOnly: false,
Raw: cookieName + "=" + authtoken,
Unparsed: []string{cookieName + "=" + authtoken},
}
http.SetCookie(w, &cookie)
http.Redirect(w, r, "https://vps.redig.us", 303)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, authenticate(r))
}
func ApiCall(url string, structure interface{}) error {
ApiResp, err := http.Get(url)
if err != nil {
return err
}
body, err := ioutil.ReadAll(ApiResp.Body)
if err != nil {
return err
}
return json.Unmarshal(body, structure)
}
type RecipeSearchResults struct {
Results []*RecipeSearchResult
NextPage string
PrevPage string
}
type RecipeSearchResult struct {
Name string
Id string
Url string
Cuisine string
Cooking_Method string
Ingredients []string
Image string
Thumb string
}
func searchHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var offset int64
params := make([]string, 0)
if value := r.Form.Get("recipeName"); value != "" {
params = append(params, "name-contains="+value)
}
if value := r.Form.Get("ingredients"); value != "" {
params = append(params, "ingredients-any="+value)
}
if value := r.Form.Get("cuisine"); value != "" {
params = append(params, "cuisine="+value)
}
if value := r.Form.Get("method"); value != "" {
params = append(params, "method="+value)
}
if value := r.Form.Get("offset"); value != "" {
offset, err = strconv.ParseInt(value, 10, 64)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
params = append(params, "offset="+value)
}
params = append(params, "limit=20")
url := "http://api.pearson.com:80/kitchen-manager/v1/recipes?" + strings.Join(params, "&")
var result RecipeSearchResults
if offset > 0 {
r.Form.Set("offset", strconv.FormatInt(offset-20, 10))
result.PrevPage = "https://vps.redig.us/search/?" + r.Form.Encode()
}
r.Form.Set("offset", strconv.FormatInt(offset+20, 10))
result.NextPage = "https://vps.redig.us/search/?" + r.Form.Encode()
err = ApiCall(url, &result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tem, err := template.ParseFiles("html/search.html", "html/defines.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tem.Execute(w, &result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
type RecipeDetail struct {
Auth bool
Name string
Id string
Image string
Thumb string
Cuisine string
Cooking_Method string
Serves float64
Yields string
Ingredients []*IngredientDetail
Directions []string
}
type IngredientDetail struct {
Name string
Id string
Quantity string
Unit string
Preparation string
prince string
}
var AsciiFilter = regexp.MustCompile("[^A-Za-z0-9 [:punct:]]")
func recipeHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
url := "https://api.pearson.com/kitchen-manager/v1/recipes/" + r.Form.Get("id")
var result RecipeDetail
err = ApiCall(url, &result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// for _, gredient := range result.Ingredients {
// type targetResponseRoot struct {
// TotalPages string
// }
// type targetResponse struct {
// Root targetResponseRoot
// }
// var tr targetResponse
// url := "https://api.target.com/v2/products/search?limit=1&searchTerm=" + html.EscapeString(gredient.Name) + "&key=" + "J5PsS2XGuqCnkdQq0Let6RSfvU7oyPwF"
// err = ApiCall(url, &tr)
// if err != nil {
// log.Println(err.Error())
//http.Error(w, err.Error(), http.StatusInternalServerError)
//return
// }
//log.Println(tr.Root.TotalPages)
// }
for i := range result.Directions {
result.Directions[i] = AsciiFilter.ReplaceAllString(result.Directions[i], "")
}
tem, err := template.ParseFiles("html/singleRecipe.html", "html/defines.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
result.Auth = authenticate(r) != 0
err = tem.Execute(w, &result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func madeHandler(w http.ResponseWriter, r *http.Request) {
uid := authenticate(r)
if uid == 0 {
http.Error(w, "Not logged in", http.StatusInternalServerError)
return
}
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//Get id of item
rid := r.Form.Get("id")
//Check if user already has made this
var count int
err = db.QueryRow("SELECT COUNT(*) FROM UsersRecipes WHERE UID=? AND RID=?", uid, rid).Scan(&count)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if count > 0 {
http.Redirect(w, r, "https://vps.redig.us/badges/", 303)
return
}
//Get recipe info
url := "https://api.pearson.com/kitchen-manager/v1/recipes/" + rid
var result RecipeDetail
err = ApiCall(url, &result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//Find if you already have an item of the same skill
var SameSkill int
err = db.QueryRow("SELECT COUNT(*) FROM UsersRecipes WHERE UID=? AND skill=?", uid, result.Cooking_Method).Scan(&SameSkill)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//Find if you already have an item of the same skill
var SameCuisine int
err = db.QueryRow("SELECT COUNT(*) FROM UsersRecipes WHERE UID=? AND cuisine=?", uid, result.Cuisine).Scan(&SameCuisine)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//Insert item into UserRecipes
_, err = db.Exec("INSERT INTO UsersRecipes (UID, RID, skill, cuisine) VALUES ( ? , ? , ? , ? )", uid, rid, result.Cooking_Method, result.Cuisine)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//The badges we need to check
badgesUpdate := make([]int, 0)
//Cusine Badge Check
rows, err := db.Query("SELECT ID FROM Badges WHERE ReqType='Cuisine' AND CuisineReq=?", result.Cuisine)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for rows.Next() {
var bid int
err = rows.Scan(&bid)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
badgesUpdate = append(badgesUpdate, bid)
}
//Anything Badge Check
rows, err = db.Query("SELECT ID FROM Badges WHERE ReqType='Anything'")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for rows.Next() {
var bid int
err = rows.Scan(&bid)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
badgesUpdate = append(badgesUpdate, bid)
}
//CuisineCount Badge Check
if SameCuisine == 0 {
rows, err = db.Query("SELECT ID FROM Badges WHERE ReqType='CuisineCount'")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for rows.Next() {
var bid int
err = rows.Scan(&bid)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
badgesUpdate = append(badgesUpdate, bid)
}
}
//Skill Count Badge Check
if SameSkill == 0 {
rows, err = db.Query("SELECT ID FROM Badges WHERE ReqType='SkillCount'")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for rows.Next() {
var bid int
err = rows.Scan(&bid)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
badgesUpdate = append(badgesUpdate, bid)
}
}
//Update Badge Counts
for _, badgeId := range badgesUpdate {
_, err = db.Exec("insert into UsersBadges (UID, BID, Progress) VALUES (?,?,1) ON DUPLICATE KEY UPDATE Progress= Progress + 1;", uid, badgeId)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
//Get email info
var email, first, last string
err = db.QueryRow("SELECT Email, First, Last FROM Users WHERE UID=?", uid).Scan(&email, &first, &last)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//Detect Completed Badges
rows, err = db.Query("SELECT BadgeTemplateID, Badges.ID FROM Badges JOIN UsersBadges ON Badges.ID = UsersBadges.BID WHERE UsersBadges.UID=? AND Badges.RequiredCount = UsersBadges.Progress AND UsersBadges.Status = 0", uid)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
type BadgeIssue struct {
//UserId string `json:"user_id"`
Email string `json:"recipient_email"`
Temid string `json:"badge_template_id"`
IssuedAt string `json:"issued_at"`
//IssuedTo string `json:"issued_to"`
IssuedToFirst string `json:"issued_to_first_name"`
IssuedToLast string `json:"issued_to_last_name"`
Expires *int `json:"expires_at"`
}
type BadgesIssue struct {
Badges []*BadgeIssue `json:"badges"`
}
var BsI BadgesIssue
BsI.Badges = make([]*BadgeIssue, 0)
for rows.Next() {
var finishedBadgeID string
var b BadgeIssue
err = rows.Scan(&b.Temid, &finishedBadgeID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b.Email = email
b.IssuedAt = time.Now().Format("2006-01-02 03:04:05") + " -0600"
//b.IssuedTo = first + " " + last
b.IssuedToFirst = first
b.IssuedToLast = last
BsI.Badges = append(BsI.Badges, &b)
_, err = db.Exec("UPDATE UsersBadges SET Status=1 WHERE UID=? AND BID=?", uid, finishedBadgeID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
client := &http.Client{}
for _, val := range BsI.Badges {
var postMessage bytes.Buffer
encoder := json.NewEncoder(&postMessage)
encoder.Encode(&val)
req, _ := http.NewRequest("POST", "https://sandbox.youracclaim.com/api/v1/organizations/21a1da4f-d12d-44fb-adc0-c07cbc2c4220/badges", &postMessage)
req.Header.Set("Authorization", "Basic TEFIOVltTHFGLTV4XzlLODRLOFg6")
req.Header.Set("content-type", "application/json")
_, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// io.Copy(os.Stdin, resp.Body)
// {
// var postMessage bytes.Buffer
// encoder := json.NewEncoder(&postMessage)
// encoder.Encode(&val)
// io.Copy(os.Stdin, &postMessage)
// }
}
http.Redirect(w, r, "https://vps.redig.us/badges/", 303)
// resp, err := http.Post("https://sandbox.youracclaim.com/api/v1/organizations/21a1da4f-d12d-44fb-adc0-c07cbc2c4220/badges", "text/json", &postMessage)
// if err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
}
type BadgesPage struct {
Auth bool
Badges []*Badge
}
type Badge struct {
Name string
Description string
ReqCount int64
Progress int64
}
func badgesHandler(w http.ResponseWriter, r *http.Request) {
var result BadgesPage
uid := authenticate(r)
result.Auth = uid != 0
if result.Auth {
rows, err := db.Query(`SELECT
Badges.Name, Badges.Description, Badges.RequiredCount, UB.Progress
FROM Badges
LEFT OUTER JOIN
( SELECT Progress, BID
FROM UsersBadges
WHERE UsersBadges.UID=?
) AS UB
ON UB.BID = Badges.ID
`, uid)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
result.Badges = make([]*Badge, 0)
for rows.Next() {
var b Badge
var progress sql.NullInt64
err = rows.Scan(&b.Name, &b.Description, &b.ReqCount, &progress)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if progress.Valid {
b.Progress = progress.Int64
if b.Progress > b.ReqCount {
b.Progress = b.ReqCount
}
} else {
b.Progress = 0
}
result.Badges = append(result.Badges, &b)
}
}
tem, err := template.ParseFiles("html/badges.html", "html/defines.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tem.Execute(w, &result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func recipesHandler(w http.ResponseWriter, r *http.Request) {
type Cuisines struct {
Name string
Id string
}
type CuisinesResponse struct {
Results []*Cuisines
}
url := "http://api.pearson.com:80/kitchen-manager/v1/cuisines?limit=10000"
var result CuisinesResponse
err := ApiCall(url, &result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tem, err := template.ParseFiles("html/recipes.html", "html/defines.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tem.Execute(w, &result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}