/
handler.go
534 lines (428 loc) · 14.1 KB
/
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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package web
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"github.com/BoilerMake/bm-app/internal/http/middleware"
"github.com/BoilerMake/bm-app/internal/mail"
"github.com/BoilerMake/bm-app/internal/models"
"github.com/BoilerMake/bm-app/internal/s3"
"github.com/BoilerMake/bm-app/internal/status"
"github.com/BoilerMake/bm-app/pkg/flash"
"github.com/BoilerMake/bm-app/pkg/template"
"github.com/go-chi/chi"
"github.com/gorilla/sessions"
"github.com/rollbar/rollbar-go"
)
type ErrorReporter func(interfaces ...interface{})
// A Page is all the data needed to render a page.
type Page struct {
Title string
// Current status of app
Status status.Status
// A generic place to put unstructured data
Data interface{}
// An array of messages to show the user
Flashes []flash.Flash
// Values to be put back into a form when shown to a user again
// For example, when they log in with the wrong password we want
// the email they tried to log in with to persist
FormRefill interface{}
// The user's email, blank if user not logged in
Email string
IsAuthenticated bool
}
func (h *Handler) NewPage(w http.ResponseWriter, r *http.Request, title string) (*Page, bool) {
session := h.getSession(r)
email, ok := session.Values["EMAIL"].(string)
if !ok {
// It's ok to ignore if this errors (for example when a user doesn't have a
// session) because email will just default to the empty string.
}
var flashes []flash.Flash
flashesInterface := session.Flashes()
session.Save(r, w)
for _, e := range flashesInterface {
f, ok := e.(flash.Flash)
if ok {
flashes = append(flashes, f)
}
}
return &Page{
Title: title,
Status: h.Status,
Email: email,
IsAuthenticated: email != "",
Flashes: flashes,
}, true
}
// A Handler will route requests to their appropriate HandlerFunc.
type Handler struct {
// A Mux handles all routing and middleware.
*chi.Mux
// A UserService is the interface with the database for users
UserService models.UserService
// An ApplicationService is the interface with the database for applications
ApplicationService models.ApplicationService
// An RSVPService is the interface with the databsae for RSVPs
RSVPService models.RSVPService
// An AnnouncementService is the interface with the database for announcements
AnnouncementService models.AnnouncementService
// A RaffleService is the interface with the databse for raffles
RaffleService models.RaffleService
// A Mailer is used to send emails
Mailer mail.Mailer
// An S3 handles uploading files to S3
S3 s3.S3
// HTML templates to render
Templates *template.Template
// An ErrorReport reports errors to something like rollbar
ErrReporter ErrorReporter
// Stores session cookies
SessionStore *sessions.CookieStore
// Name cookie that stores sessions
SessionCookieName string
// Holds the current application status
Status status.Status
}
// NewHandler creates a handler for web requests.
func NewHandler(us models.UserService, as models.ApplicationService, rs models.RSVPService, anns models.AnnouncementService, ras models.RaffleService, mailer mail.Mailer, S3 s3.S3) *Handler {
h := Handler{
UserService: us,
ApplicationService: as,
RSVPService: rs,
RaffleService: ras,
AnnouncementService: anns,
Mailer: mailer,
S3: S3,
}
r := chi.NewRouter()
// Set up templates
mode := mustGetEnv("ENV_MODE")
tmplPath := mustGetEnv("TEMPLATES_PATH")
tmplFuncs := map[string]interface{}{
"static_path": staticFileReplace(mode),
}
tmpls, err := template.NewTemplate(tmplPath, tmplFuncs)
if err != nil {
log.Fatalf("failed to load templates: %s", err)
}
h.Templates = tmpls
if mode == "development" {
// In development mode, reload templates on every request
r.Use(h.Templates.ReloadTemplates)
}
// On and off season routes
r.Get("/", h.getRoot())
r.Get("/hackers", h.getHackers())
r.Get("/sponsors", h.getSponsors())
r.Get("/about", h.getAbout())
r.Get("/faq", h.getFaq())
r.Get("/meet_team", h.getMeetTeam())
// Live routes only
r.Group(func(r chi.Router) {
r.Use(middleware.LiveOnly)
r.Get("/live", h.getLive())
r.Post("/checkin", h.postCheckIn())
r.Post("/raffle", h.postRaffle()) // only allow claiming a raffle during live event
})
// Exec routes
r.Group(func(r chi.Router) {
r.Use(middleware.MustBeAuthenticated)
r.Use(middleware.MustBeExec)
r.Get("/exec", h.getExec())
r.Post("/announcement", h.postAnnouncement())
r.Delete("/announcement", h.deleteAnnouncement())
r.Post("/createraffle", h.createRaffle())
r.Post("/addtickets", h.addTickets())
})
// On season only routes
r.Group(func(r chi.Router) {
r.Use(middleware.OnSeasonOnly)
// User routes
r.Group(func(r chi.Router) {
r.Use(middleware.MustNotBeAuthenticated)
r.Get("/signup", h.getSignup())
r.Post("/signup", h.postSignup())
r.Get("/login", h.getLogin())
r.Post("/login", h.postLogin())
})
r.Get("/activate/{code}", h.getActivate())
// Password Reset Routes
r.Get("/forgot", h.getForgotPassword())
r.Post("/forgot", h.postForgotPassword())
r.Get("/reset", h.getResetPassword())
r.Get("/reset/{token}", h.getResetPasswordWithToken())
r.Post("/reset/{token}", h.postResetPassword())
// Public Annnouncement Route
r.Get("/announcement", h.getAnnouncement())
r.Get("/announcement/{id}", h.getAnnouncementWithID())
r.Get("/allannouncements", h.getAnnouncements())
r.Get("/logout", h.getLogout())
// Must have auth
r.Group(func(r chi.Router) {
r.Use(middleware.MustBeAuthenticated)
// allow user to access raffle page as it is on the navbar
r.Get("/raffle", h.getRaffle())
r.Get("/dashboard", h.getDashboard())
r.Group(func(r chi.Router) {
r.Use(middleware.AppsOpenOnly)
r.Get("/apply", h.getApply())
r.Post("/apply", h.postApply())
})
r.Get("/rsvp", h.getRSVP())
r.Post("/rsvp", h.postRSVP())
})
})
r.NotFound(h.get404())
if mode == "development" {
// In prod we serve static items through a CDN, in development just serve
// out of web/static/ at /static/
fs := http.StripPrefix("/static", http.FileServer(http.Dir("web/static")))
r.Get("/static/*", fs.ServeHTTP)
}
// Only log to rollbar in production
rollbarEnv := mustGetEnv("ROLLBAR_ENVIRONMENT")
if rollbarEnv == "production" {
h.ErrReporter = rollbarReportError
} else {
// If we're not in production just print out the errors
h.ErrReporter = logReportError
}
// Set up session store
sessionSecret := mustGetEnv("SESSION_SECRET")
sessionKey := []byte(sessionSecret)
store := sessions.NewCookieStore(sessionKey)
// Prevents CSRF attacks (on browsers that support SameSite)
store.Options.SameSite = http.SameSiteStrictMode
// Prevents XSS attacks (JS isn't allowed to access cookie)
store.Options.HttpOnly = true
if mode != "development" {
// Only transfer cookie over https
store.Options.Secure = true
}
h.SessionStore = store
h.SessionCookieName = mustGetEnv("SESSION_COOKIE_NAME")
// Set up status to feed to pages
statusString := mustGetEnv("APP_STATUS")
statusInt, err := strconv.Atoi(statusString)
if err != nil {
log.Fatalf("Failed to convert status to int: %v", err)
}
h.Status = status.Status(statusInt)
h.Mux = r
return &h
}
// getRoot renders the index template.
func (h *Handler) getRoot() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := h.NewPage(w, r, "BoilerMake")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
h.Templates.RenderTemplate(w, "home", p)
}
}
// getHackers renders the hackers template.
func (h *Handler) getHackers() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := h.NewPage(w, r, "BoilerMake - Hackers")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
h.Templates.RenderTemplate(w, "hackers", p)
}
}
// getSponsors renders the sponsors template.
func (h *Handler) getSponsors() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := h.NewPage(w, r, "BoilerMake - Sponsors")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
h.Templates.RenderTemplate(w, "sponsors", p)
}
}
// getAbout renders the about template.
func (h *Handler) getAbout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := h.NewPage(w, r, "BoilerMake - About")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
if h.Status < 2 || h.Status > 4 {
h.Templates.RenderTemplate(w, "about", p)
} else {
h.Templates.RenderTemplate(w, "bmix_about", p)
}
}
}
// getFaq renders the faq template.
func (h *Handler) getFaq() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := h.NewPage(w, r, "BoilerMake - FAQ")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
if h.Status < 2 || h.Status > 4 {
h.Templates.RenderTemplate(w, "faq", p)
} else {
h.Templates.RenderTemplate(w, "bmix_faq", p)
}
}
}
// getMeetTeam renders the meet the team template.
func (h *Handler) getMeetTeam() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := h.NewPage(w, r, "BoilerMake - Meet The Team")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
h.Templates.RenderTemplate(w, "bmix_meet_team", p)
}
}
// getHackers renders the day of template.
func (h *Handler) getLive() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := h.NewPage(w, r, "BoilerMake - Live")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
h.Templates.RenderTemplate(w, "bmix day of", p)
}
}
// get404 handles requests that couldn't find a valid route by rendering the
// 404 template.
func (h *Handler) get404() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := h.NewPage(w, r, "BoilerMake - 404")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
h.Templates.RenderTemplate(w, "404", p)
}
}
// mustGetEnv looks up and sets an environment variable. If the environment
// variable is not found, it panics.
func mustGetEnv(varName string) (value string) {
value, ok := os.LookupEnv(varName)
if !ok {
log.Fatalf("environment variable not set: %v", varName)
}
return value
}
// staticFileReplace is a template helper that reads in a manifest file and
// reroutes requests accordingly. It's useful when you upload versioned files
// to a CDN for cache invalidation. The manifest file used is made by gulp
// when running the prod config.
func staticFileReplace(mode string) func(path string) string {
if mode == "development" {
// No need to change path in development
return func(path string) string {
return "/static/" + path
}
}
// In prod change path to cloudfront
cloudfrontURL := mustGetEnv("CLOUDFRONT_URL")
file, err := ioutil.ReadFile("web/static/rev-manifest.json")
if err != nil {
log.Fatalf("failed to read static manifest file: %v", err)
}
var manifest map[string]interface{}
err = json.Unmarshal(file, &manifest)
if err != nil {
log.Fatalf("failed to parse static manifest file: %v", err)
}
return func(path string) string {
if manifest[path] != nil {
fullPath, ok := manifest[path].(string)
if !ok {
return "/404"
}
return cloudfrontURL + "/" + fullPath
}
return "/404"
}
}
// onSeasonOnly checks to make sure status is between 2 and 4, meaning
// that the event is either happening right now or is upcoming. If it is not
// then the route is redirected to a 404. If the application status is not on
// season then this will return an error.
func onSeasonOnly(status string) error {
statusInt, err := strconv.Atoi(status)
if err != nil {
return err
}
if statusInt < 2 || statusInt > 4 {
return fmt.Errorf("application is currently not in season")
}
return nil
}
// getSession returns the session associated with a request's cookies.
func (h *Handler) getSession(r *http.Request) *sessions.Session {
session, _ := h.SessionStore.Get(r, h.SessionCookieName)
return session
}
// rollbarReportError reports an error to rollbar and logs it locally. It
// should only be reporting errors in production. You should not call this
// function directly, instead call h.Error(...) and let that handle it.
func rollbarReportError(interfaces ...interface{}) {
rollbar.Error(interfaces...)
rollbar.Wait()
// Also log the error locally
log.Println("ERROR:", interfaces)
}
// logReportError logs an error locally. In production rollbarReportError
// should be used instead. You should not call this function directly, instead
// call h.Error(...) and let that handle it.
func logReportError(interfaces ...interface{}) {
// Also log the error locally
log.Println("ERROR:", interfaces)
}
// Error checks an error given to it. If it's a known error that we've made
// we can show it to the user as a flash. If it's unknown then we should tell
// the user that something went wrong and report the error to rollbar.
func (h *Handler) Error(w http.ResponseWriter, r *http.Request, err error, redirectPath string, interfaces ...interface{}) {
switch err.(type) {
case *models.ModelError:
// This is an error we know about and should let the user know what happened
modelError := err.(*models.ModelError)
session := h.getSession(r)
session.AddFlash(flash.Flash{
Type: modelError.GetType(),
Message: modelError.Error(),
})
session.Save(r, w)
// Redirect to previous page
if redirectPath != "" {
http.Redirect(w, r, redirectPath, http.StatusSeeOther)
} else {
http.Redirect(w, r, r.URL.RequestURI(), http.StatusSeeOther)
}
default:
// Because we don't know how this error happened, we should report it on rollbar.
h.ErrReporter(append([]interface{}{err}, interfaces...)...)
// This error could have come from anywhere, so we should just tell the user
// something went wrong so that we don't accidently expose something
// sensitive
p, ok := h.NewPage(w, r, "500")
if !ok {
h.Error(w, r, errors.New("creating page failed"), "")
return
}
h.Templates.RenderTemplate(w, "500", p)
}
}