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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
package auth
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"time"
"github.com/martinlehoux/kagamigo/core"
"golang.org/x/exp/slog"
)
var (
ErrUserNotLoggedIn = errors.New("user not logged in")
ErrCookieExpired = errors.New("cookie expired")
ErrBadCookie = errors.New("invalid cookie")
)
type userContext struct{}
func Unauthorized(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusUnauthorized)
if err != nil {
_, err = w.Write([]byte(err.Error()))
core.Expect(err, "error writing response")
}
}
func CookieAuthMiddleware(loadUser func(context.Context, core.ID) (any, error), config AuthConfig) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
cookie, err := r.Cookie("authentication")
if errors.Is(err, http.ErrNoCookie) {
next.ServeHTTP(w, r)
return
}
core.Expect(err, "error reading cookie")
authentication, err := decrypt(config.CookieSecret, cookie.Value)
if err != nil {
err = core.Wrap(err, "error decrypting cookie")
slog.Warn(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
parts := strings.Split(authentication, ":")
if len(parts) != 2 {
slog.Warn(ErrBadCookie.Error())
http.Error(w, ErrBadCookie.Error(), http.StatusBadRequest)
return
}
userId, err := core.ParseID(parts[0])
if err != nil {
err = core.Wrap(err, "error parsing user id")
slog.Warn(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
expiresAtSeconds, err := strconv.Atoi(parts[1])
if err != nil {
err = core.Wrap(err, "error parsing expires at")
slog.Warn(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
expiresAt := time.Unix(int64(expiresAtSeconds), 0)
if time.Now().After(expiresAt) {
slog.Warn(ErrCookieExpired.Error())
http.Error(w, ErrCookieExpired.Error(), http.StatusUnauthorized)
return
}
user, err := loadUser(ctx, userId)
core.Expect(err, "error loading user")
ctx = context.WithValue(ctx, userContext{}, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
|