feat(middleware): add transaction and error handling support

- Add transaction manager for multi-step database operations
- Add standardized error response middleware
- Add HTTPError type for typed errors
- Add RespondWithError and RespondWithHTTPError helpers
- Support automatic rollback on errors
This commit is contained in:
2026-01-29 09:23:34 -05:00
parent 3b0b18770e
commit 2c560c411e
2 changed files with 160 additions and 0 deletions
+107
View File
@@ -0,0 +1,107 @@
package handlers
import (
"bookmann/internal/database"
"context"
"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"`
}
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()})
}
// Get refresh token from database
tokenInfo, err := h.db.GetRefreshToken(c.Request().Context(), req.RefreshToken)
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"})
}
// Generate new access 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: 3600, // 1 hour in 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 {
// If no refresh token provided, just return success
return c.JSON(http.StatusOK, map[string]string{"message": "logged out successfully"})
}
// Revoke the refresh token if provided
err := h.db.RevokeRefreshToken(c.Request().Context(), req.RefreshToken)
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) {
// Generate refresh token
tokenUUID := uuid.New()
refreshToken := tokenUUID.String()
// Store in database (plain text for simplicity - tokens are already random UUIDs)
expiresAt := time.Now().Add(refreshTokenExpiration)
_, err := h.db.CreateRefreshToken(context.Background(), database.CreateRefreshTokenParams{
UserID: pgtype.UUID{Bytes: [16]byte(userID), Valid: true},
Token: refreshToken,
ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},
})
if err != nil {
return "", "", err
}
// Generate new access token
accessToken, err := h.generateJWT(userID.String())
if err != nil {
return "", "", err
}
return accessToken, refreshToken, nil
}
+53
View File
@@ -0,0 +1,53 @@
package middleware
import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// TransactionManager handles database transactions
type TransactionManager struct {
pool *pgxpool.Pool
}
// NewTransactionManager creates a new transaction manager
func NewTransactionManager(pool *pgxpool.Pool) *TransactionManager {
return &TransactionManager{pool: pool}
}
// WithTx runs a function within a database transaction
// If the function returns an error, the transaction is rolled back
// If the function succeeds, the transaction is committed
func (tm *TransactionManager) WithTx(ctx context.Context, fn func(pgx.Tx) error) error {
tx, err := tm.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
// Ensure the transaction is handled properly
defer func() {
if p := recover(); p != nil {
// A panic occurred, rollback and re-panic
_ = tx.Rollback(ctx)
panic(p)
}
}()
if err := fn(tx); err != nil {
// Function returned error, rollback
if rbErr := tx.Rollback(ctx); rbErr != nil {
return fmt.Errorf("function error: %v, rollback error: %w", err, rbErr)
}
return err
}
// Success, commit
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}