cerrado @ c6bdde9c63758cb9b61c7a5559dd30d141aee289

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