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
|
package user
import (
"log"
"net/http"
"github.com/go-playground/validator/v10"
"gitlab.com/alexkavon/newsstand/src/server"
)
var Routes = server.Routes{
server.Route{
Name: "Create",
Method: "GET",
Path: "/u/create",
HandlerFunc: Create,
},
server.Route{
Name: "Store",
Method: "POST",
Path: "/user",
HandlerFunc: Store,
},
server.Route{
Name: "LoginForm",
Method: "GET",
Path: "/u/auth",
HandlerFunc: LoginForm,
},
server.Route{
Name: "Authenticate",
Method: "POST",
Path: "/u/auth",
HandlerFunc: Authenticate,
},
server.Route{
Name: "Me",
Method: "GET",
Path: "/u/me",
AuthRequired: true,
HandlerFunc: Show,
},
}
func Create(s *server.Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.Ui.Render(w, "user/create", nil)
}
}
func Store(s *server.Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
user := &User{
Db: s.Db,
Username: r.PostFormValue("username"),
Secret: r.PostFormValue("secret"),
Email: r.PostFormValue("email"),
}
// Validate User Input
v := validator.New()
err := v.Struct(user)
if err != nil {
log.Println("Validator failed", err.(validator.ValidationErrors))
}
// Hash secret
err = user.HashSecret()
if err != nil {
log.Println("Hash failure", err)
}
// Store user
err = user.Insert()
if err != nil {
log.Println("Insert Error", err)
}
// Send email validation
// Create cookie session
s.NewSession(w, user.Username)
// Redirect to user profile
http.Redirect(w, r, "/u/me", http.StatusSeeOther)
}
}
func LoginForm(s *server.Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.Ui.Render(w, "user/login", nil)
}
}
func Authenticate(s *server.Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {}
}
func Show(s *server.Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, err := r.Cookie("session_token")
if err != nil {
s.Ui.Render(w, "user/login", &struct{ Message string }{"You are not logged in! Missing Cookie"})
}
session, ok := s.Sessions[token.Value]
if !ok {
s.Ui.Render(w, "user/login", &struct{ Message string }{"You are not logged in! With Session."})
}
s.Ui.Render(w, "user/me", &struct{ Message, Username string }{"Congrats on getting this far!", session.Username()})
}
}
|