Files
bookhoard/internal/handlers/refresh_token.go
T
john-okeefe 457a38306d feat(auth): make session duration and password rules configurable
Replace the hardcoded 7-day session lifetime and fixed password
complexity rules with registry-backed accessors so they can be tuned
from the admin UI without a code change.

auth.go:
- Drop the SessionDuration const; keep DefaultSessionDuration (7 days)
  as the fallback used when no registry is wired (e.g. in tests).
- AuthHandler gains an optional *database.SettingsRegistry and a
  sessionDuration() helper that reads the registry, falling back to
  DefaultSessionDuration.
- Cookie MaxAge, JWT exp claim, and ExpiresIn responses now derive from
  sessionDuration() instead of the package-level SessionDurationSec, so
  a settings change takes effect on the next login.

refresh_token.go:
- Refresh-token lifetime follows sessionDuration() via a new
  refreshTokenTTL() helper (was a separate refreshTokenExpiration const
  that silently had to be kept in sync with the session duration).

password_validator.go:
- PasswordValidator now reads min length and the upper/lower/number/
  special toggles from the registry at validation time, so rule
  changes apply immediately. The special-character regex is compiled
  once and reused (sync.Once).
- GetPasswordRequirements() and ValidatePassword() reflect the active
  configured rules instead of a static list.
- Add SetDefaultPasswordSettings() so the package-level default
  validator (used by echo's struct-tag validator) follows live config.

All paths degrade gracefully to the historical defaults when no
registry is wired.
2026-08-10 08:01:11 -04:00

119 lines
3.6 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 {
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
}