-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.go
217 lines (187 loc) · 6.84 KB
/
http.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
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
package main
import (
"bytes"
"net/http"
"github.com/gorilla/mux"
)
// GetLoginPage renders the login page to the user.
func (k *Kasse) GetLoginPage(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/html")
if err := ExecuteTemplate(res, TemplateInput{Title: "Login", Body: "login.html"}); err != nil {
k.log.Println("Could not render template:", err)
http.Error(res, "Internal error", http.StatusInternalServerError)
return
}
}
// PostLoginPage receives a POST request with username and password and tries
// to authenticate the user. It will redirect to the first Flashvalue in the
// session on success, or to / if none is set and save the authenticated user
// in the session.
func (k *Kasse) PostLoginPage(res http.ResponseWriter, req *http.Request) {
username := req.FormValue("username")
password := []byte(req.FormValue("password"))
if username == "" || len(password) == 0 {
// TODO: Write own Error function, that uses a template for better
// looking error pages. Also, redirect.
http.Error(res, "Neither username nor password can be empty", http.StatusBadRequest)
return
}
user, err := k.Authenticate(username, password)
if err != nil && err != ErrWrongAuth {
k.log.Println("Error authenticating:", err)
// TODO: Write own Error function, that uses a template for better
// looking error pages. Also, redirect.
http.Error(res, "Internal server error", http.StatusInternalServerError)
return
}
if user == nil {
k.log.Println("Wrong username or password")
// TODO: Write own Error function, that uses a template for better
// looking error pages. Also, redirect.
http.Error(res, "Wrong username or password", http.StatusUnauthorized)
return
}
session, _ := k.sessions.Get(req, "nnev-kasse")
redirect := "/"
if v := session.Flashes(); len(v) > 0 {
if s, ok := v[0].(string); ok {
redirect = s
}
}
session.Values["user"] = user
if err := session.Save(req, res); err != nil {
k.log.Printf("Error saving session: %v", err)
}
http.Redirect(res, req, redirect, http.StatusFound)
}
// GetNewUserPage renders the page to create a new user.
func (k *Kasse) GetNewUserPage(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/html")
if err := ExecuteTemplate(res, TemplateInput{Title: "Create new user", Body: "newUser.html"}); err != nil {
k.log.Println("Could not render template:", err)
http.Error(res, "Internal error", http.StatusInternalServerError)
return
}
}
// PostNewUserPage receives a POST request with username and password and tries
// to create a new user. It will redirect to the first Flashvalue in the
// session on success, or to / if none is set and save the authenticated user
// in the session.
func (k *Kasse) PostNewUserPage(res http.ResponseWriter, req *http.Request) {
username := req.FormValue("username")
password := []byte(req.FormValue("password"))
confirm := []byte(req.FormValue("confirm"))
if username == "" || len(password) == 0 || len(confirm) == 0 {
// TODO: Write own Error function, that uses a template for better
// looking error pages. Also, redirect.
http.Error(res, "Neither username nor password can be empty", http.StatusBadRequest)
return
}
if !bytes.Equal(password, confirm) {
// TODO: Write own Error function, that uses a template for better
// looking error pages. Also, redirect.
http.Error(res, "Password and confirmation don't match", http.StatusBadRequest)
return
}
user, err := k.RegisterUser(username, password)
if err != nil && err != ErrUserExists {
k.log.Printf("Registering user %q failed:%v", username, err)
// TODO: Write own Error function, that uses a template for better
// looking error pages. Also, redirect.
http.Error(res, "Internal server error", http.StatusInternalServerError)
return
}
if err == ErrUserExists {
k.log.Println(err)
// TODO: Write own Error function, that uses a template for better
// looking error pages. Also, redirect.
http.Error(res, "User already exists.", http.StatusForbidden)
return
}
session, _ := k.sessions.Get(req, "nnev-kasse")
redirect := "/"
if v := session.Flashes(); len(v) > 0 {
if s, ok := v[0].(string); ok {
redirect = s
}
}
session.Values["user"] = user
if err := session.Save(req, res); err != nil {
k.log.Printf("Error saving session: %v", err)
}
http.Redirect(res, req, redirect, http.StatusFound)
}
// GetDashboard renders a basic dashboard, containing the most important
// information and actions for an account.
func (k *Kasse) GetDashboard(res http.ResponseWriter, req *http.Request) {
session, err := k.sessions.Get(req, "nnev-kasse")
if err != nil {
http.Redirect(res, req, "/login.html", 302)
return
}
ui, ok := session.Values["user"]
if !ok {
http.Redirect(res, req, "/login.html", 302)
return
}
user := ui.(User)
cards, err := k.GetCards(user)
if err != nil {
k.log.Printf("Could not get cards for user %q: %v", user.Name, err)
http.Error(res, "Internal error", 500)
return
}
balance, err := k.GetBalance(user)
if err != nil {
k.log.Printf("Could not get balance for user %q: %v", user.Name, err)
http.Error(res, "Internal error", 500)
return
}
transactions, err := k.GetTransactions(user, 5)
if err != nil {
k.log.Printf("Could not get transactions for user %q: %v", user.Name, err)
http.Error(res, "Internal error", 500)
return
}
res.Header().Set("Content-Type", "text/html")
data := struct {
User User
Balance float32
Cards []Card
Transactions []Transaction
}{
User: user,
Balance: float32(balance) / 100,
Cards: cards,
Transactions: transactions,
}
if err := ExecuteTemplate(res, TemplateInput{Title: "ccchd Kasse", Body: "dashboard.html", Data: data}); err != nil {
k.log.Println("Could not render template:", err)
http.Error(res, "Internal error", 500)
return
}
}
// GetLogout logs out the user immediately and redirect to the login page.
func (k *Kasse) GetLogout(res http.ResponseWriter, req *http.Request) {
defer http.Redirect(res, req, "/login.html", 302)
session, err := k.sessions.Get(req, "nnev-kasse")
if err != nil {
return
}
delete(session.Values, "user")
if err := session.Save(req, res); err != nil {
k.log.Printf("Error saving session: %v", err)
}
}
// Handler returns a http.Handler for the webinterface.
func (k *Kasse) Handler() http.Handler {
r := mux.NewRouter()
r.Methods("GET").Path("/").HandlerFunc(k.GetDashboard)
r.Methods("GET").PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
r.Methods("GET").Path("/login.html").HandlerFunc(k.GetLoginPage)
r.Methods("POST").Path("/login.html").HandlerFunc(k.PostLoginPage)
r.Methods("GET").Path("/logout.html").HandlerFunc(k.GetLogout)
r.Methods("GET").Path("/create_user.html").HandlerFunc(k.GetNewUserPage)
r.Methods("POST").Path("/create_user.html").HandlerFunc(k.PostNewUserPage)
return r
}