-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
450 lines (420 loc) · 12 KB
/
handlers.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package main
import (
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
// aboutHandler handles GET requests to "/about"
func aboutHandler(w http.ResponseWriter, r *http.Request) {
renderContent("tmpl/about.html", r, w, nil)
}
// categoryHandler handles GET requests to "/category*"
func categoryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
cat, err := getCategoryByAbbr(vars["categoryName"])
if err != nil {
http.NotFound(w, r)
return
}
runs, err := getRunsByCategory(cat, 0)
if err != nil {
log.Println("Could not get runs: ", err)
http.Error(w, "Internal server error", 500)
return
}
highlightedRunner := vars["runner"]
type categoryData struct {
Category category
Runs []run
HighlightedRunner string
}
data := categoryData{cat, runs, highlightedRunner}
renderContent("tmpl/category.html", r, w, data)
}
// contactHandler handles GET and POST requests to "/contact"
func contactHandler(w http.ResponseWriter, r *http.Request) {
// We keep track of user input in the template data to provide
// a partially filled form in case the user messes up the inputs
type contactData struct {
MailSent bool
Error string
NameInput string
EmailInput string
SubjectInput string
MessageInput string
}
var mailSent = false
var errorString string
var name string
var email string
var subject string
var message string
var err error
if r.Method == "POST" {
name, email, subject, message, err = contactFormParser(r)
if err != nil {
errorString = err.Error()
} else {
mailSubject := "Moss Tier contact form message: " + subject
mailBody := "From: " + name + "\r\n"
if email != "" {
mailBody += "Email: " + email + "\r\n"
}
mailBody += "\r\n\r\n" + message
err = sendMail(config.AdminEmail, mailSubject, mailBody)
if err != nil {
errorString = "Mail delivery failed."
} else {
mailSent = true
}
}
}
data := contactData{mailSent, errorString, name, email, subject, message}
renderContent("tmpl/contact.html", r, w, data)
}
// editProfileHandler handles GET requests to "/edit-profile"
func editProfileHandler(w http.ResponseWriter, r *http.Request) {
// First, let's make sure that the user is logged in
if _, err := getActiveUser(r); err != nil {
http.NotFound(w, r)
return
}
type editProfileData struct {
Success bool
Error string
Countries map[string]string
Spelunkers []spelunker
}
success := false
var errorString string
data := editProfileData{success, errorString, countries, spelunkers}
renderContent("tmpl/editprofile.html", r, w, data)
}
// flagRunHandler handles GET and POST requests to /flag-run*
func flagRunHandler(w http.ResponseWriter, r *http.Request) {
// Before doing anything, let us ensure that the current user
// is allowed to flag runs.
if activeUser, err := getActiveUser(r); !activeUser.IsModerator() || err != nil {
http.Error(w, "Internal server error", 500)
return
}
type flagRunData struct {
Run run
Flagged bool
Error string
}
flagged := false
var errorString string
vars := mux.Vars(r)
runID, err := strconv.Atoi(vars["runID"])
if err != nil {
log.Println("Could not parse run ID: ", err)
http.NotFound(w, r)
return
}
run, err := getRunByID(runID)
if err != nil {
log.Println("Could not find run with given ID: ", err)
http.NotFound(w, r)
return
}
if r.Method == "POST" {
explanation, err := reportFormParser(r) // This is a /bit/ lazy.
if err != nil {
errorString = err.Error()
} else {
err = run.flag(explanation)
if err != nil {
errorString += "Could not flag the run:" + err.Error()
} else {
flagged = true
}
}
}
data := flagRunData{run, flagged, errorString}
renderContent("tmpl/flagrun.html", r, w, data)
}
// frontPageHandler handles GET requests to "/"
func frontPageHandler(w http.ResponseWriter, r *http.Request) {
// We split the world records into t heir two classes. Rather
// than just using map to do this, we make our own struct to
// be able to control ordering more explicitly.
type classWithRecords struct {
Description string
Records []run
}
type frontPageData struct {
News []newsEntry
WorldRecords []classWithRecords
}
allWorldRecords, err := getAllWorldRecords()
var mainWRs []run
var challengeWRs []run
if err != nil {
log.Println("Could not get world records: ", err)
http.Error(w, "Internal server error", 500)
return
}
// Now actually split split the world records
for _, wr := range allWorldRecords {
if wr.Category.isMain() {
mainWRs = append(mainWRs, wr)
} else {
challengeWRs = append(challengeWRs, wr)
}
}
worldRecords := []classWithRecords{
classWithRecords{"Main categories", mainWRs},
classWithRecords{"Challenge categories", challengeWRs},
}
data := frontPageData{readNews(), worldRecords}
renderContent("tmpl/frontpage.html", r, w, data)
}
// loginHandler handles GET and POST requests to "/login"
func loginHandler(w http.ResponseWriter, r *http.Request) {
type loginData struct {
Success bool
Error string
UsernameInput string
PasswordInput string
}
success := false
var errorString string
var username string
var password string
var user runner
var err error
if r.Method == "POST" {
username, password, user, err = loginFormParser(r)
if err != nil {
errorString = err.Error()
} else {
err = setActiveUser(r, w, user)
if err != nil {
log.Println(err)
http.Error(w, "Internal server error", 500)
return
}
success = true
}
}
data := loginData{success, errorString, username, password}
renderContent("tmpl/login.html", r, w, data)
}
// logOutHandler handles GET requests to "/log-out"
func logOutHandler(w http.ResponseWriter, r *http.Request) {
// A natural way to log out would be to set the session
// cookie max-age to -1, but that adds an unnecessary layer
// of complexity for when the user wants to log back in.
// Instead we just change the user to one that doesn't exist.
session, err := cookieStore.Get(r, "login")
if err != nil {
log.Println(err)
http.Error(w, "Internal server error", 500)
return
}
session.Values["userID"] = 0
session.Save(r, w)
renderContent("tmpl/logout.html", r, w, nil)
}
// notFoundHandler handles all 404s
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
renderContent("tmpl/404.html", r, w, nil)
}
// passwordResetHandler handles GET and POST requests to "/password-reset"
func passwordResetHandler(w http.ResponseWriter, r *http.Request) {
type passwordResetData struct {
PasswordReset bool
Error string
}
passwordReset := false
var errorString string
if r.Method == "POST" {
user, err := passwordResetFormParser(r)
if err != nil {
errorString = err.Error()
} else {
newPassword, err := generatePassword()
if err != nil {
log.Println(err)
http.Error(w, "Internal server error", 500)
return
}
// Send a mail to the user with the password, before attempting to update it
err = user.sendMail("Password reset", "Hi "+user.Username+". Someone (hopefully you) requested "+
"a new password for you on Moss Tier. Here's your new one: "+newPassword)
if err != nil {
errorString += "Could not send you an email with your new password."
log.Println(err)
} else {
err = user.updatePassword(newPassword)
if err != nil {
errorString += "Could not update your password due to an unexpected error. "
log.Println(err)
} else {
passwordReset = true
}
}
}
}
renderContent("tmpl/passwordreset.html", r, w, passwordResetData{passwordReset, errorString})
}
// profileHandler handles GET requests to "/profile*"
func profileHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
profileID, err := strconv.Atoi(vars["profileID"])
if err != nil {
log.Println("Could not parse profile id: ", err)
http.NotFound(w, r)
return
}
thisRunner, err := getRunnerByID(profileID)
if err != nil {
log.Println("Could not find runner: ", err)
http.NotFound(w, r)
return
}
allRuns, err := getRunsByRunnerID(profileID)
if err != nil {
log.Println("Could not get runs: ", err)
http.Error(w, "Internal server error", 500)
return
}
type profileData struct {
Runner *runner
Runs []run
FlaggedRuns []run
}
unflaggedRuns := []run{}
flaggedRuns := []run{}
for _, run := range allRuns {
if run.Flag != "" {
flaggedRuns = append(flaggedRuns, run)
} else {
unflaggedRuns = append(unflaggedRuns, run)
}
}
data := profileData{&thisRunner, unflaggedRuns, flaggedRuns}
renderContent("tmpl/profile.html", r, w, data)
}
// registerHandler handles GET and POST requests to "/register"
func registerHandler(w http.ResponseWriter, r *http.Request) {
type registerData struct {
Success bool
Error string
UsernameInput string
EmailInput string
PasswordInput string
Password2Input string
}
success := false
var errorString string
var username string
var email string
var password string
var password2 string
var err error
if r.Method == "POST" {
username, email, password, password2, err = registerFormParser(r)
if err != nil {
errorString = err.Error()
} else {
err = makeUser(username, email, password)
if err != nil {
errorString += "Could not create user. Please try again later. "
log.Println(err)
} else {
// Everything is good; now, log in as the newly
// created user
user, err := getRunnerByUsername(username)
if err != nil {
log.Println(err)
http.Error(w, "Internal server error", 500)
return
}
err = setActiveUser(r, w, user)
if err != nil {
log.Println(err)
http.Error(w, "Internal server error", 500)
return
}
success = true
}
}
}
data := registerData{success, errorString, username,
email, password, password2}
renderContent("tmpl/register.html", r, w, data)
}
// reportHandler handles GET and POST requests to /report*
func reportHandler(w http.ResponseWriter, r *http.Request) {
type reportData struct {
Run run
Success bool
Error string
}
success := false
var errorString string
vars := mux.Vars(r)
runID, err := strconv.Atoi(vars["runID"])
if err != nil {
log.Println("Could not parse run ID: ", err)
http.NotFound(w, r)
return
}
run, err := getRunByID(runID)
if err != nil {
log.Println("Could not find run with given ID: ", err)
http.NotFound(w, r)
return
}
if r.Method == "POST" {
explanation, err := reportFormParser(r)
if err != nil {
errorString = err.Error()
} else {
moderatorEmails := []string{}
for _, moderatorID := range config.Moderators {
moderator, _ := getRunnerByID(moderatorID)
moderatorEmails = append(moderatorEmails, moderator.Email)
}
err = sendMails(moderatorEmails, "Moss Tier run reported",
"Hi Moss Tier moderator. The run by "+run.Runner.Username+" in the "+
"category "+run.Category.Name+" (id "+strconv.Itoa(runID)+") "+
"has been reported as violating the rules. Could you check it "+
"out and flag the run if needed? The explanation they gave was "+
"\""+explanation+"\"")
if err != nil {
errorString += "Could not send mail to moderators. Please try again later. "
} else {
success = true
}
}
}
data := reportData{run, success, errorString}
renderContent("tmpl/report.html", r, w, data)
}
// rulesHandler handles GET requests to "/rules"
func rulesHandler(w http.ResponseWriter, r *http.Request) {
renderContent("tmpl/rules.html", r, w, getAllCategories())
}
// submitRunHandler handles GET requests to "/submit-run/*". If a
// runID is given in the request, pre-fill the form with the info
// of that run.
func submitRunHandler(w http.ResponseWriter, r *http.Request) {
type submitRunData struct {
Categories []category
Spelunkers []spelunker
OldRun *run
PossibleWorlds []int
PossibleLevels []int
}
vars := mux.Vars(r)
oldRunID, _ := strconv.Atoi(vars["runID"])
oldRun, _ := getRunByID(oldRunID)
data := submitRunData{getAllCategories(), spelunkers, &oldRun,
[]int{1, 2, 3, 4, 5}, []int{1, 2, 3, 4}}
renderContent("tmpl/submitrun.html", r, w, data)
}