Files
bookhoard/internal/handlers/refresh_token.go
T
john-okeefe 2e1af8d20b feat(auth): extend session duration to 7 days using constants
- Add SessionDuration constant (7 days) and SessionDurationSec computed value
- Update JWT token expiration to use SessionDuration instead of 1 hour
- Update register/login cookie MaxAge to use SessionDurationSec (604800)
- Update register/login API response ExpiresIn to use SessionDurationSec
- Update refresh token endpoint ExpiresIn to use SessionDurationSec
- Remove redundant client-side document.cookie lines from login/register
- Add TODO comment for HTTPS cookie Secure flag

This provides Google-like persistent sessions with a single source of truth
for session duration, eliminating hardcoded values throughout the codebase.
2026-02-16 16:49:43 -05:00

122 lines
3.6 KiB
Go

package handlers
import (
"bookhoard/internal/database"
"context"
"fmt"
"net/http"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/labstack/echo/v4"
)
const (
refreshTokenExpiration = 7 * 24 * time.Hour // 7 days
)
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: [16]byte(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 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: SessionDurationSec,
})
}
// Logout handles POST /api/auth/logout
func (h *AuthHandler) Logout(c echo.Context) error {
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 && 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(refreshTokenExpiration)
_, err := h.db.CreateRefreshToken(context.Background(), database.CreateRefreshTokenParams{
UserID: pgtype.UUID{Bytes: [16]byte(userID), Valid: true},
Token: pgtype.UUID{Bytes: [16]byte(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
}