-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller_signup.go
74 lines (63 loc) · 1.84 KB
/
controller_signup.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
package main
import (
"errors"
"net/http"
"strings"
"github.com/asymmetricia/vator/models"
"go.etcd.io/bbolt"
)
func SignupHandler(db *bbolt.DB) func(http.ResponseWriter, *http.Request) {
return func(rw http.ResponseWriter, req *http.Request) {
switch req.Method {
case "POST":
RequireForm([]string{"username", "password", "confirm"}, SignupHandlerPost(db))(rw, req)
default:
SignupHandlerGet(db, rw, req)
}
}
}
func SignupHandlerGet(db *bbolt.DB, rw http.ResponseWriter, req *http.Request) {
notif, err := notifications(db, req)
if err != nil {
Bail(rw, req, err, http.StatusInternalServerError)
return
}
notif.Page = "signup"
TemplateGet(rw, req, "signup.tmpl", notif)
}
func SignupHandlerPost(db *bbolt.DB) func(w http.ResponseWriter, r *http.Request) {
return func(rw http.ResponseWriter, req *http.Request) {
username := strings.ToLower(req.Form.Get("username"))
password := req.Form.Get("password")
confirm := req.Form.Get("confirm")
_, err := models.LoadUser(db, username)
if !errors.Is(err, models.UserNotFound) {
err = errors.New("that username is taken; try again?")
} else {
err = nil
}
if err == nil && password != confirm {
err = errors.New("your passwords did not match; give it another shot?")
}
if err != nil {
models.SessionSet(db, req, "error", err.Error())
http.Redirect(rw, req, "/signup", http.StatusFound)
return
}
u := &models.User{Username: username}
if err := u.SetPassword(password); err != nil {
Bail(rw, req, err, http.StatusInternalServerError)
return
}
if err := u.Save(db); err != nil {
Bail(rw, req, err, http.StatusInternalServerError)
return
}
if err := models.SessionSet(db, req, "user", username); err != nil {
Bail(rw, req, err, http.StatusInternalServerError)
return
}
http.Redirect(rw, req, "/", http.StatusFound)
return
}
}