-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
67 lines (53 loc) · 1.33 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
package auth
import (
"context"
"net/http"
"github.com/viddrobnic/sparovec/models"
)
type contextKey string
const contextKeyUser = contextKey("user")
type Service interface {
ValidateSession(session *models.Session) error
}
func CreateMiddleware(service Service) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(models.SessionCookieName)
if err != nil {
next.ServeHTTP(w, r)
return
}
session, err := models.SessionFromCookie(cookie.Value)
if err != nil {
next.ServeHTTP(w, r)
return
}
if err := service.ValidateSession(session); err != nil {
next.ServeHTTP(w, r)
return
}
ctx := context.WithValue(r.Context(), contextKeyUser, session.User)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func RequiredMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := GetUser(r)
if user == nil {
http.Redirect(w, r, "/auth/sign-in", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
func GetUser(r *http.Request) *models.User {
user := r.Context().Value(contextKeyUser)
if user == nil {
return nil
}
if user, ok := user.(*models.User); ok {
return user
}
return nil
}