aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/api/auth_middleware.go
blob: d721f1d2bfcb27c110591d757df93ec5e01b48d1 (plain)
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
package api

import (
	"context"

	"github.com/labstack/echo/v4"

	"albatross-2026-backend/auth"
	"albatross-2026-backend/db"
)

type sessionIDContextKey struct{}
type userContextKey struct{}

func SessionCookieMiddleware(q *db.Queries) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			cookie, err := c.Cookie("albatross_session")
			if err != nil {
				return next(c)
			}
			hashedID := auth.HashSessionID(cookie.Value)
			user, err := q.GetUserBySession(c.Request().Context(), hashedID)
			if err != nil {
				return next(c)
			}
			ctx := c.Request().Context()
			ctx = context.WithValue(ctx, sessionIDContextKey{}, hashedID)
			ctx = context.WithValue(ctx, userContextKey{}, &user)
			c.SetRequest(c.Request().WithContext(ctx))
			return next(c)
		}
	}
}

func GetSessionIDFromContext(ctx context.Context) (string, bool) {
	sessionID, ok := ctx.Value(sessionIDContextKey{}).(string)
	return sessionID, ok
}

func GetUserFromContext(ctx context.Context) (*db.User, bool) {
	user, ok := ctx.Value(userContextKey{}).(*db.User)
	return user, ok
}