1package ext
2
3import (
4 "context"
5 "encoding/base64"
6 "errors"
7 "log/slog"
8 "net/http"
9)
10
11type authService interface {
12 ValidateToken(token []byte) (bool, error)
13}
14
15func DisableAuthentication(next http.HandlerFunc) http.HandlerFunc {
16 return func(w http.ResponseWriter, r *http.Request) {
17 ctx := r.Context()
18 ctx = context.WithValue(ctx, "disableAuthentication", true)
19 next(w, r.WithContext(ctx))
20 }
21}
22
23func Authenticate(auth authService) func(next http.HandlerFunc) http.HandlerFunc {
24 return func(next http.HandlerFunc) http.HandlerFunc {
25 return func(w http.ResponseWriter, r *http.Request) {
26 cookie, err := r.Cookie("auth")
27 if err != nil {
28 if !errors.Is(err, http.ErrNoCookie) {
29 slog.Error("Error loading cookie", "error", err)
30 }
31 next(w, r)
32 return
33 }
34
35 value, err := base64.StdEncoding.DecodeString(cookie.Value)
36 if err != nil {
37 slog.Error("Error decoding", "error", err)
38 next(w, r)
39 return
40 }
41
42 valid, err := auth.ValidateToken(value)
43 if err != nil {
44 slog.Error("Error validating token", "error", err, "cookie", cookie.Value)
45 next(w, r)
46 return
47 }
48
49 ctx := r.Context()
50 ctx = context.WithValue(ctx, "logged", true)
51
52 slog.Info("Validated token", "valid?", valid)
53 next(w, r.WithContext(ctx))
54 }
55 }
56}