about summary refs log tree commit diff
path: root/src/user.go
blob: 48bc299e44f5b8c71b6344cf42826d4efe3d6c50 (plain)
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
package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/gorilla/mux"
	"golang.org/x/crypto/argon2"
)

type User struct {
	ID           int
	Name         string
	PasswordHash []byte
}

//////////////////////////////////////////////////////////////////////////////
// GENERAL PURPOSE

func UserRegister(username string, passwordHash []byte) (int, error) {
	id, err := globalState.InsertUser(User{Name: username, PasswordHash: passwordHash})
	if err != nil {
		return 0, err
	} else {
		return id, nil
	}
}

// UserCheckPasswordHash returns a boolean that is true if the users password
// is correct and false if the users password is false and thus doesn't match
// the one stored in the database
func UserCheckPasswordHash(username string, passwordHash []byte) bool {
	return globalState.CheckUserHash(username, passwordHash)
}

// UserUpdatePasswordHash does exactly that
func UserUpdatePasswordHash(orig_username string, passwordHash []byte) error {
	return globalState.UpdateUserPasswordHash(orig_username, passwordHash)
}

func UserUpdateUsername(id int, new_username string) error {
	return globalState.UpdateUserUsername(id, new_username)
}

func UserLinkBot(username string, botid int) error {
	return globalState.LinkUserBot(username, botid)
}

func UserGetBotsUsingUsername(username string) ([]Bot, error) {
	return globalState.GetUserBotsUsername(username)
}

func UserGetBotsUsingUserID(userid int) ([]Bot, error) {
	return globalState.GetUserBotsId(userid)
}

func UserGetUserFromID(userid int) (User, error) {
	return globalState.GetUserFromId(userid)
}

func UserGetUserFromUsername(username string) (User, error) {
	return globalState.GetUserFromUsername(username)
}

func UserGetAll() ([]User, error) {
	return globalState.GetAllUsers()
}

//////////////////////////////////////////////////////////////////////////////
// DATABASE

func (s *State) InsertUser(user User) (int, error) {
	res, err := s.db.Exec("INSERT INTO users VALUES(NULL,?,?,?);", time.Now(), user.Name, user.PasswordHash)
	if err != nil {
		return 0, err
	}

	var id int64
	if id, err = res.LastInsertId(); err != nil {
		return 0, err
	}
	return int(id), nil
}

// returns true if the password matches
func (s *State) CheckUserHash(username string, passwordHash []byte) bool {
	var created time.Time
	err := s.db.QueryRow("SELECT created_at FROM users WHERE name=? AND passwordHash=?", username, passwordHash).Scan(&created)
	switch {
	case err != nil:
		return false
	default:
		return true
	}
}

func (s *State) UpdateUserPasswordHash(username string, passwordHash []byte) error {
	_, err := s.db.Exec("UPDATE users SET passwordHash=? WHERE name=?", passwordHash, username)
	if err != nil {
		return err
	} else {
		return nil
	}
}

func (s *State) UpdateUserUsername(id int, new_username string) error {
	_, err := s.db.Exec("UPDATE users SET name=? WHERE id=?", new_username, id)
	if err != nil {
		return err
	} else {
		return nil
	}
}

// Links the given bot to the given user in the user_bot_rel table
func (s *State) LinkUserBot(username string, botid int) error {
	_, err := s.db.Exec("INSERT INTO user_bot_rel VALUES ((SELECT id FROM users WHERE name=?), ?)", username, botid)
	if err != nil {
		return err
	} else {
		return nil
	}
}

// Links the given bot to the given user in the user_bot_rel table
func (s *State) GetUserFromId(id int) (User, error) {
	var user_id int
	var username string
	err := s.db.QueryRow("SELECT id, name FROM users WHERE id=?", id).Scan(&user_id, &username)
	if err != nil {
		return User{}, err
	} else {
		return User{user_id, username, nil}, nil
	}
}

func (s *State) GetUserFromUsername(username string) (User, error) {
	var id int
	var name string
	err := s.db.QueryRow("SELECT id, name FROM users WHERE name=?", username).Scan(&id, &name)
	if err != nil {
		return User{}, err
	} else {
		return User{id, name, nil}, nil
	}
}

// Returns the bots belonging to the given user
func (s *State) GetUserBotsUsername(username string) ([]Bot, error) {
	rows, err := s.db.Query("SELECT id, name, source FROM bots b LEFT JOIN user_bot_rel ub ON ub.bot_id = b.id WHERE ub.user_id=(SELECT id FROM users WHERE name=?)", username)
	defer rows.Close()
	if err != nil {
		return nil, err
	}

	var bots []Bot
	for rows.Next() {
		var bot Bot
		if err := rows.Scan(&bot.ID, &bot.Name, &bot.Source); err != nil {
			return bots, err
		}
		bots = append(bots, bot)
	}
	if err = rows.Err(); err != nil {
		return bots, err
	}
	return bots, nil
}

// Returns the bots belonging to the given user
func (s *State) GetUserBotsId(id int) ([]Bot, error) {
	rows, err := s.db.Query("SELECT id, name, source FROM bots b LEFT JOIN user_bot_rel ub ON ub.bot_id = b.id WHERE ub.user_id=?", id)
	defer rows.Close()
	if err != nil {
		return nil, err
	}

	var bots []Bot
	for rows.Next() {
		var bot Bot
		if err := rows.Scan(&bot.ID, &bot.Name, &bot.Source); err != nil {
			return bots, err
		}
		bots = append(bots, bot)
	}
	if err = rows.Err(); err != nil {
		return bots, err
	}
	return bots, nil
}

// Returns the bots belonging to the given user
func (s *State) GetAllUsers() ([]User, error) {
	rows, err := s.db.Query("SELECT id, name FROM users")
	defer rows.Close()
	if err != nil {
		return nil, err
	}

	var users []User
	for rows.Next() {
		var user User
		if err := rows.Scan(&user.ID, &user.Name); err != nil {
			return users, err
		}
		users = append(users, user)
	}
	if err = rows.Err(); err != nil {
		return users, err
	}
	return users, nil
}

//////////////////////////////////////////////////////////////////////////////
// HTTP

func loginHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		log.Println("GET /login")
		// define data
		log.Println("[d] Defining breadcrumbs")
		data := map[string]interface{}{}
		data["version"] = os.Getenv("VERSION")
		data["pagelink1"] = Link{"login", "/login"}
		data["pagelink1options"] = []Link{
			{Name: "register", Target: "/register"},
		}
		data["pagelinkauth"] = []Link{
			{Name: "register/", Target: "/register"},
		}

		// session foo
		log.Println("[d] Getting session")
		session, _ := globalState.sessions.Get(r, "session")
		username := session.Values["username"]

		// get the user
		if username != nil {
			log.Printf("[d] Getting the user %s\n", username.(string))
			user, err := UserGetUserFromUsername(username.(string))
			if user.Name == "" {
				log.Println("no user found")
			} else if err != nil {
				log.Println(err)
				msg := "Error: could not get the user for given username"
				http.Redirect(w, r, fmt.Sprintf("/login?res=%s", msg), http.StatusSeeOther)
				return
			} else {
				data["user"] = user
			}
		}

		// display errors passed via query parameters
		log.Println("[d] Getting previous results")
		queryres := r.URL.Query().Get("res")
		if queryres != "" {
			data["res"] = queryres
		}

		// get the template
		log.Println("[d] Getting the template")
		t, err := template.ParseGlob(fmt.Sprintf("%s/*.html", templatesPath))
		if err != nil {
			log.Printf("Error reading the template Path: %s/*.html", templatesPath)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Error reading template file"))
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// exec!
		log.Println("[d] Executing the template")
		t.ExecuteTemplate(w, "login", data)

	case "POST":
		// parse the post parameters
		r.ParseForm()
		username := r.Form.Get("username")
		password := r.Form.Get("password")

		// if we've got a password, hash it and compare it with the stored one
		if password != "" {
			passwordHash := argon2.IDKey([]byte(password), []byte(os.Getenv("SALT")), 1, 64*1024, 4, 32)

			// check if it's valid
			valid := UserCheckPasswordHash(username, passwordHash)
			if valid {

				// if it's valid, we set a session for the user
				session, _ := globalState.sessions.Get(r, "session")
				session.Values["username"] = username
				err := session.Save(r, w)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}

				http.Redirect(w, r, "/", http.StatusSeeOther)
				return

			} else {
				// invalid password
				http.Redirect(w, r, "/login?err=Invalid+Password", http.StatusSeeOther)
				return
			}
		} else {
			// empty password
			http.Redirect(w, r, "/login?err=Empty+Password", http.StatusSeeOther)
			return
		}
	default:
		http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
	}
}

func registerHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		// define data
		data := map[string]interface{}{}
		data["version"] = os.Getenv("VERSION")

		// get the session
		session, _ := globalState.sessions.Get(r, "session")
		username := session.Values["username"]
		data["pagelink1"] = Link{"register", "/register"}
		data["pagelink1options"] = []Link{
			{Name: "login", Target: "/login"},
		}
		data["pagelinkauth"] = []Link{
			{Name: "login/", Target: "/login"},
		}

		log.Println(username)

		if username != nil {
			data["logged_in"] = true
		}

		// get the template
		t, err := template.ParseGlob(fmt.Sprintf("%s/*.html", templatesPath))
		if err != nil {
			log.Printf("Error reading the template Path: %s/*.html", templatesPath)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Error reading template file"))
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// exec!
		t.ExecuteTemplate(w, "register", data)

	case "POST":
		// parse the post parameters
		r.ParseForm()
		username := r.Form.Get("username")
		password1 := r.Form.Get("password1")
		password2 := r.Form.Get("password2")

		if len(username) >= 64 {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Oi', Backend here! Please enter less than 64 chars!"))
			return
		}

		if len(password1) >= 256 {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Oi', Backend here! Don't overdo with the length please!"))
			return
		}

		if password1 != password2 {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Oi', Backend here! The passwords you entered don't match!"))
			return
		}

		// if we've got a password, hash it and store it and create a User
		if password1 != "" {
			passwordHash := argon2.IDKey([]byte(password1), []byte(os.Getenv("SALT")), 1, 64*1024, 4, 32)

			_, err := UserRegister(username, passwordHash)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte("500 - We had problems inserting you into the DB"))
				return
			}

			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		}
	default:
		http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
	}
}

func logoutHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		session, _ := globalState.sessions.Get(r, "session")
		session.Options.MaxAge = -1
		err := session.Save(r, w)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		http.Redirect(w, r, "/", http.StatusSeeOther)
	default:
		http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
	}
}

func userHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id, err := strconv.Atoi(vars["id"])
	if err != nil {
		http.Redirect(w, r, "/user", http.StatusSeeOther)
	}

	switch r.Method {
	case "GET":
		// define data
		data := map[string]interface{}{}
		data["version"] = os.Getenv("VERSION")
		data["pagelink1"] = Link{"user", "/user"}
		data["pagelink1options"] = []Link{
			{Name: "bot", Target: "/bot"},
			{Name: "battle", Target: "/battle"},
		}

		// session foo
		session, _ := globalState.sessions.Get(r, "session")
		username := session.Values["username"].(string)

		// the the user making the request
		user, err := UserGetUserFromUsername(username)
		if err != nil {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		} else {
			data["user"] = user
		}

		// get the target user using the provided id
		targetUser, err := UserGetUserFromID(id)
		if err != nil {
			data["err"] = "Could not find that user"
		} else {
			data["targetUser"] = targetUser
		}

		// define the breadcrumbs
		data["pagelink2"] = Link{targetUser.Name, fmt.Sprintf("/%s", targetUser.Name)}

		allUserNames, err := UserGetAll()
		var opts []Link
		for _, user := range allUserNames {
			opts = append(opts, Link{Name: user.Name, Target: fmt.Sprintf("/%d", user.ID)})
		}
		data["pagelink2options"] = opts

		// get the bots for the given user
		bots, err := UserGetBotsUsingUserID(id)
		if err != nil {
			http.Redirect(w, r, "/user", http.StatusSeeOther)
		} else {
			data["bots"] = bots
		}

		// get the template
		t, err := template.ParseGlob(fmt.Sprintf("%s/*.html", templatesPath))
		if err != nil {
			log.Printf("Error reading the template Path: %s/*.html", templatesPath)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Error reading template file"))
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// exec!
		t.ExecuteTemplate(w, "user", data)
	default:
		http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
	}
}

func usersHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		// define data
		data := map[string]interface{}{}
		data["version"] = os.Getenv("VERSION")
		data["pagelink1"] = Link{Name: "user", Target: "/user"}
		data["pagelink1options"] = []Link{
			{Name: "bot", Target: "/bot"},
			{Name: "battle", Target: "/battle"},
		}

		// sessions
		session, _ := globalState.sessions.Get(r, "session")
		username := session.Values["username"].(string)

		// get the user
		user, err := UserGetUserFromUsername(username)
		if err != nil {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		} else {
			data["user"] = user
		}

		// get all users
		users, err := UserGetAll()
		data["users"] = users

		// get the template
		t, err := template.ParseGlob(fmt.Sprintf("%s/*.html", templatesPath))
		if err != nil {
			log.Printf("Error reading the template Path: %s/*.html", templatesPath)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Error reading template file"))
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// exec!
		t.ExecuteTemplate(w, "users", data)
	default:
		http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
	}
}

func profileHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id, err := strconv.Atoi(vars["id"])
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("500 - Error reading the profile id"))
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	switch r.Method {
	case "GET":
		// define data
		data := map[string]interface{}{}
		data["version"] = os.Getenv("VERSION")
		data["pagelink1"] = Link{"user", "/user"}
		data["pagelink1options"] = []Link{
			{Name: "bot", Target: "/bot"},
			{Name: "battle", Target: "/battle"},
		}

		session, _ := globalState.sessions.Get(r, "session")
		username := session.Values["username"].(string)

		target_user, err := UserGetUserFromID(id)
		if err != nil {
			// w.WriteHeader(http.StatusUnauthorized)
			// w.Write([]byte("500 - Error reading template file"))
			// http.Error(w, err.Error(), http.StatusInternalServerError)
			data["err"] = "Error getting with the given id"
		}

		if username != target_user.Name {
			// w.WriteHeader(http.StatusInternalServerError)
			// w.Write([]byte("500 - Error reading template file"))
			// http.Error(w, err.Error(), http.StatusInternalServerError)
			data["err"] = "You aren't allowed to edit any user except yourself"
		}

		editing_user, err := UserGetUserFromUsername(username)
		if err != nil {
			data["err"] = "Coulnd't get a user for that id"
		}

		data["user"] = editing_user
		data["target_user"] = target_user

		data["pagelink2"] = Link{target_user.Name, fmt.Sprintf("/%d", id)}
		allUserNames, err := UserGetAll()
		var opts []Link
		for _, user := range allUserNames {
			opts = append(opts, Link{Name: user.Name, Target: fmt.Sprintf("/%d", user.ID)})
		}
		data["pagelink2options"] = opts

		data["pagelink3"] = Link{"profile", "/profile"}

		if username != "" {
			data["username"] = username
		}

		// get the template
		t, err := template.ParseGlob(fmt.Sprintf("%s/*.html", templatesPath))
		if err != nil {
			log.Printf("Error reading the template Path: %s/*.html", templatesPath)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Error reading template file"))
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// exec!
		t.ExecuteTemplate(w, "profile", data)

	case "POST":
		session, _ := globalState.sessions.Get(r, "session")
		orig_username := session.Values["username"].(string)

		// parse the post parameters
		r.ParseForm()
		new_username := r.Form.Get("username")
		password1 := r.Form.Get("password1")
		password2 := r.Form.Get("password2")

		if len(new_username) >= 64 {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Oi', Backend here! Please enter less than 64 chars!"))
			return
		}

		if len(password1) >= 256 {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Oi', Backend here! Don't overdo with the length please!"))
			return
		}

		if password1 != password2 {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("500 - Oi', Backend here! The passwords you entered don't match!"))
			return
		}

		// first update the password, as they might have also changed their
		// username
		if password1 != "" {
			passwordHash := argon2.IDKey([]byte(password1), []byte(os.Getenv("SALT")), 1, 64*1024, 4, 32)

			err := UserUpdatePasswordHash(orig_username, passwordHash)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte("500 - We had problems inserting your new pw into the DB"))
				return
			}
		}

		if new_username != "" {
			err := UserUpdateUsername(id, new_username)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte("500 - We had problems inserting your new uname into the DB"))
				return
			}

			// after changing the username, we also have to update the username
			//  stored in the session
			session.Values["username"] = new_username
			err = session.Save(r, w)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		http.Redirect(w, r, fmt.Sprintf("/user/%d/profile", id), http.StatusSeeOther)
		return
	default:
		http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
	}
}