Release / build-and-push (push) Successful in 3m9s
Logout wiped localStorage but never cleared the token cookie (HttpOnly — only a server response can) and never called the logout API, leaving the refresh token live for 30 days and every cookie-authenticated SSR page accessible: the fake-signout bug. Reproduced on prod and dev; unrelated to RLS (it sits behind authentication) and long-standing. - /api/auth/logout now ALWAYS clears the session cookie (Set-Cookie empty + Max-Age=-1, HttpOnly/Path/SameSite mirroring login) — even a malformed body must sign the browser out; refresh-token revocation unchanged. - The header logout button (and the rules-page copy) now POST to the API with the stored refresh token BEFORE clearing local state and redirecting — best effort: local cleanup never blocks on API failure. - toast 401 handler fixed: it cleared 'refreshToken' but storage uses 'refresh_token' — the real key. - Regression test TestLogoutClearsSession: real login → logout → response deletes the cookie; logged-out refresh token can't mint access tokens; body-less logout still clears. Also carries regenerated artifacts from the confirm-modal and episode-list work (header_templ/podcast_detail_templ/style.css).
136 lines
4.2 KiB
Go
136 lines
4.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"bookhoard/internal/database"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/labstack/echo/v5"
|
|
)
|
|
|
|
type RefreshTokenRequest struct {
|
|
RefreshToken string `json:"refresh_token" validate:"required"`
|
|
}
|
|
|
|
func parseTokenUUID(tokenStr string) (pgtype.UUID, error) {
|
|
tokenUUID, err := uuid.Parse(tokenStr)
|
|
if err != nil {
|
|
return pgtype.UUID{}, err
|
|
}
|
|
return pgtype.UUID{Bytes: tokenUUID, Valid: true}, nil
|
|
}
|
|
|
|
type RefreshTokenResponse struct {
|
|
AccessToken string `json:"access_token"`
|
|
TokenType string `json:"token_type"`
|
|
ExpiresIn int `json:"expires_in"` // seconds
|
|
}
|
|
|
|
// RefreshAccessToken handles POST /api/auth/refresh
|
|
func (h *AuthHandler) RefreshAccessToken(c *echo.Context) error {
|
|
var req RefreshTokenRequest
|
|
if err := c.Bind(&req); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})
|
|
}
|
|
if err := c.Validate(&req); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
}
|
|
|
|
tokenUUID, err := parseTokenUUID(req.RefreshToken)
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid refresh token format"})
|
|
}
|
|
|
|
tokenInfo, err := h.db.GetRefreshToken(c.Request().Context(), tokenUUID)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "invalid or expired refresh token"})
|
|
}
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to validate refresh token"})
|
|
}
|
|
|
|
accessToken, err := h.generateJWTWithAllClaims(
|
|
uuid.UUID(tokenInfo.UserID.Bytes).String(),
|
|
tokenInfo.Role,
|
|
tokenInfo.Email,
|
|
tokenInfo.Username,
|
|
)
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to generate access token"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, RefreshTokenResponse{
|
|
AccessToken: accessToken,
|
|
TokenType: "Bearer",
|
|
ExpiresIn: int(h.refreshTokenTTL().Seconds()),
|
|
})
|
|
}
|
|
|
|
// Logout handles POST /api/auth/logout
|
|
func (h *AuthHandler) Logout(c *echo.Context) error {
|
|
// Clear the HttpOnly session cookie — the SSR pages authenticate
|
|
// with it, and JavaScript cannot clear an HttpOnly cookie by
|
|
// design. Without this, "logout" wiped localStorage but left the
|
|
// cookie session alive for up to session_duration_seconds (the
|
|
// fake-signout bug: users roamed every cookie-authed page). The
|
|
// cookie is cleared BEFORE anything else — even a malformed body
|
|
// must sign the browser out.
|
|
c.SetCookie(&http.Cookie{
|
|
Name: "token",
|
|
Value: "",
|
|
Path: "/",
|
|
HttpOnly: true,
|
|
Secure: secure == "true",
|
|
SameSite: http.SameSiteLaxMode,
|
|
MaxAge: -1, // delete
|
|
})
|
|
|
|
var req RefreshTokenRequest
|
|
if err := c.Bind(&req); err != nil {
|
|
return c.JSON(http.StatusOK, map[string]string{"message": "logged out successfully"})
|
|
}
|
|
|
|
tokenUUID, err := parseTokenUUID(req.RefreshToken)
|
|
if err != nil {
|
|
return c.JSON(http.StatusOK, map[string]string{"message": "logged out successfully"})
|
|
}
|
|
|
|
err = h.db.RevokeRefreshToken(c.Request().Context(), tokenUUID)
|
|
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to revoke refresh token"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, map[string]string{"message": "logged out successfully"})
|
|
}
|
|
|
|
// CreateRefreshToken creates a new refresh token for a user
|
|
func (h *AuthHandler) CreateRefreshToken(userID uuid.UUID) (string, string, error) {
|
|
tokenUUID := uuid.New()
|
|
refreshToken := tokenUUID.String()
|
|
|
|
expiresAt := time.Now().Add(h.refreshTokenTTL())
|
|
_, err := h.db.CreateRefreshToken(context.Background(), database.CreateRefreshTokenParams{
|
|
UserID: pgtype.UUID{Bytes: userID, Valid: true},
|
|
Token: pgtype.UUID{Bytes: tokenUUID, Valid: true},
|
|
ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},
|
|
})
|
|
if err != nil {
|
|
fmt.Printf("ERROR storing refresh token: %v\n", err)
|
|
return "", "", err
|
|
}
|
|
fmt.Printf("DEBUG: refreshToken generated: '%s'\n", refreshToken)
|
|
|
|
accessToken, err := h.generateJWT(userID.String())
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
return accessToken, refreshToken, nil
|
|
}
|