-
Notifications
You must be signed in to change notification settings - Fork 0
/
users_handler.go
89 lines (81 loc) · 2.57 KB
/
users_handler.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
package web
import (
"html/template"
"net/http"
"github.com/alexedwards/scs/v2"
"github.com/gorilla/csrf"
"github.com/noloman/goreddit"
"golang.org/x/crypto/bcrypt"
)
type UserHandler struct {
store goreddit.Store
sessions *scs.SessionManager
}
func (h *UserHandler) Register() http.HandlerFunc {
type data struct {
SessionData
CSRF template.HTML
}
tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/user_register.html"))
return func(w http.ResponseWriter, r *http.Request) {
tmpl.Execute(w, data{CSRF: csrf.TemplateField(r), SessionData: GetSessionData(h.sessions, r.Context())})
}
}
func (h *UserHandler) RegisterSubmit() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
form := RegisterForm{
Username: r.FormValue("username"),
Password: r.FormValue("password"),
UsernameTaken: false,
}
if _, err := h.store.UserByUsername(form.Username); err == nil {
form.UsernameTaken = true
}
if !form.Validate() {
h.sessions.Put(r.Context(), "form", form)
http.Redirect(w, r, "/register", http.StatusFound)
return
}
}
}
func (h *UserHandler) Login() http.HandlerFunc {
type data struct {
SessionData
CSRF template.HTML
}
tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/user_login.html"))
return func(w http.ResponseWriter, r *http.Request) {
tmpl.Execute(w, data{CSRF: csrf.TemplateField(r), SessionData: GetSessionData(h.sessions, r.Context())})
}
}
func (h *UserHandler) LoginSubmit() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
form := LoginForm{
Username: r.FormValue("username"),
Password: r.FormValue("password"),
IncorrectCredentials: false,
}
user, err := h.store.UserByUsername(form.Username)
if err != nil {
form.IncorrectCredentials = true
} else {
compareError := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(form.Password))
form.IncorrectCredentials = compareError != nil
}
if !form.Validate() {
h.sessions.Put(r.Context(), "form", form)
http.Redirect(w, r, "/login", http.StatusFound)
return
}
h.sessions.Put(r.Context(), "user_id", user.ID)
h.sessions.Put(r.Context(), "flash", "You have been logged in successfully")
http.Redirect(w, r, "/", http.StatusFound)
}
}
func (h *UserHandler) Logout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
h.sessions.Remove(r.Context(), "user_id")
h.sessions.Put(r.Context(), "flash", "You have been logged out successfully")
http.Redirect(w, r, "/", http.StatusFound)
}
}