-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
108 lines (88 loc) · 2.41 KB
/
middleware.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
package main
import (
"context"
"net/http"
"strconv"
"github.com/jackc/pgx/v4"
)
func (app *application) requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !app.isAuthenticated(r) {
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
return
}
w.Header().Add("Cache-Control", "no-store")
next.ServeHTTP(w, r)
})
}
func (app *application) authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := app.sessionManager.GetString(r.Context(), string(authenticatedUserKey))
if id == "" {
next.ServeHTTP(w, r)
return
}
exists, err := app.users.Exists(id)
if err != nil {
app.serverError(w, err)
return
}
if exists {
ctx := context.WithValue(r.Context(), isAuthenticatedContextKey, true)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
func (app *application) paginate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pageQ := r.URL.Query().Get("page")
page := 0
if pageQ != "" {
var err error
page, err = strconv.Atoi(pageQ)
if err != nil {
app.serverError(w, err)
return
}
}
ctx := context.WithValue(r.Context(), pageContextKey, page)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (app *application) userDailyPlay(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userID := app.sessionManager.GetString(r.Context(), string(authenticatedUserKey))
userPlay, err := app.soundtests.GetPlay(userID)
if err != nil {
switch {
case err == pgx.ErrNoRows:
next.ServeHTTP(w, r)
return
default:
app.serverError(w, err)
return
}
}
ctx := context.WithValue(r.Context(), userPlayContextKey, userPlay)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (app *application) limitPlayOnce(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if app.hasPlayed(r) {
http.Redirect(w, r, "/play/grade", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
func (app *application) verifyPlayed(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !app.hasPlayed(r) {
http.Redirect(w, r, "/play", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}