-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute_auth.go
75 lines (68 loc) · 1.9 KB
/
route_auth.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
package main
import (
"chitchat/data"
"net/http"
)
// GET /login
// Show the login page
func login(writer http.ResponseWriter, request *http.Request) {
t := parseTemplateFiles("login.layout", "public.navbar", "login")
t.Execute(writer, nil)
}
// GET /signup
// Show the signup page
func signup(writer http.ResponseWriter, request *http.Request) {
generateHTML(writer, nil, "login.layout", "public.navbar", "signup")
}
// POST /signup
// Create the user account
func signupAccount(writer http.ResponseWriter, request *http.Request) {
err := request.ParseForm()
if err != nil {
danger(err, "Cannot parse form")
}
user := data.User{
Name: request.PostFormValue("name"),
Email: request.PostFormValue("email"),
Password: request.PostFormValue("password"),
}
if err := user.Create(); err != nil {
danger(err, "Cannot create user")
}
http.Redirect(writer, request, "/login", 302)
}
// POST /authenticate
// Authenticate the user given the email and password
func authenticate(writer http.ResponseWriter, request *http.Request) {
err := request.ParseForm()
user, err := data.UserByEmail(request.PostFormValue("email"))
if err != nil {
danger(err, "Cannot find user")
}
if user.Password == data.Encrypt(request.PostFormValue("password")) {
session, err := user.CreateSession()
if err != nil {
danger(err, "Cannot create session")
}
cookie := http.Cookie{
Name: "_cookie",
Value: session.Uuid,
HttpOnly: true,
}
http.SetCookie(writer, &cookie)
http.Redirect(writer, request, "/", 302)
} else {
http.Redirect(writer, request, "/login", 302)
}
}
// GET /logout
// Logs the user out
func logout(writer http.ResponseWriter, request *http.Request) {
cookie, err := request.Cookie("_cookie")
if err != http.ErrNoCookie {
warning(err, "Failed to get cookie")
session := data.Session{Uuid: cookie.Value}
session.DeleteByUUID()
}
http.Redirect(writer, request, "/", 302)
}