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
|
package ext
import (
"context"
"encoding/base64"
"log/slog"
"net/http"
)
type authService interface {
ValidateToken(token []byte) (bool, error)
}
func DisableAuthentication(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(ctx, "disableAuthentication", true)
next(w, r.WithContext(ctx))
}
}
func Authenticate(auth authService) func(next http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("auth")
if err != nil {
slog.Error("Error loading cookie", "error", err)
next(w, r)
return
}
value, err := base64.StdEncoding.DecodeString(cookie.Value)
if err != nil {
slog.Error("Error decoding", "error", err)
next(w, r)
return
}
valid, err := auth.ValidateToken(value)
if err != nil {
slog.Error("Error validating token", "error", err, "cookie", cookie.Value)
next(w, r)
return
}
ctx := r.Context()
ctx = context.WithValue(ctx, "logged", true)
slog.Info("Validated token", "valid?", valid)
next(w, r.WithContext(ctx))
}
}
}
|