cerrado @ f5c307668c7fa3c367defc6e924d7c1e00303c16

 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 Authenticate(auth authService) func(next http.HandlerFunc) http.HandlerFunc {
15	return func(next http.HandlerFunc) http.HandlerFunc {
16		return func(w http.ResponseWriter, r *http.Request) {
17			cookie, err := r.Cookie("auth")
18			if err != nil {
19				slog.Error("Error loading cookie", "error", err)
20				next(w, r)
21				return
22			}
23
24			value, err := base64.StdEncoding.DecodeString(cookie.Value)
25			if err != nil {
26				slog.Error("Error decoding", "error", err)
27				next(w, r)
28				return
29			}
30
31			valid, err := auth.ValidateToken(value)
32			if err != nil {
33				slog.Error("Error validating token", "error", err, "cookie", cookie.Value)
34				next(w, r)
35				return
36			}
37
38			ctx := r.Context()
39			ctx = context.WithValue(ctx, "logged", true)
40
41			slog.Info("Validated token", "valid?", valid)
42			next(w, r.WithContext(ctx))
43		}
44	}
45}