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:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user