From 96fad1a4e78c7209e5a0f3496e8b59d591fbe500 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sun, 15 Feb 2026 11:12:50 +0900 Subject: refactor(auth): replace JWT authentication with server-side sessions Migrate from stateless JWT tokens to server-side session management backed by PostgreSQL. Sessions are hashed with SHA-256 before storage, cleaned up periodically, and invalidated on logout. This removes the need for JWT_SECRET/COOKIE_SECRET environment variables and the golang-jwt dependency. Co-Authored-By: Claude Opus 4.6 --- backend/api/auth_middleware.go | 42 +++++++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 15 deletions(-) (limited to 'backend/api/auth_middleware.go') diff --git a/backend/api/auth_middleware.go b/backend/api/auth_middleware.go index 97f8946..d721f1d 100644 --- a/backend/api/auth_middleware.go +++ b/backend/api/auth_middleware.go @@ -6,27 +6,39 @@ import ( "github.com/labstack/echo/v4" "albatross-2026-backend/auth" + "albatross-2026-backend/db" ) -type contextKey struct{} +type sessionIDContextKey struct{} +type userContextKey struct{} -func JWTCookieMiddleware(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - cookie, err := c.Cookie("albatross_token") - if err != nil { +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) } - claims, err := auth.ParseJWT(cookie.Value) - if err != nil { - return next(c) - } - ctx := context.WithValue(c.Request().Context(), contextKey{}, claims) - c.SetRequest(c.Request().WithContext(ctx)) - return next(c) } } -func GetJWTClaimsFromContext(ctx context.Context) (*auth.JWTClaims, bool) { - claims, ok := ctx.Value(contextKey{}).(*auth.JWTClaims) - return claims, ok +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 } -- cgit v1.3.1