fix: add proper JWT user context to router middleware
Add createJWTMiddleware helper that sets database.Users object in context, matching the original main.go JWT middleware behavior. This fixes 'authentication context error' panics in handlers that call MustGetAuthenticatedUser. Changes: - Add createJWTMiddleware() in router.go - Update all route files to use the helper - Set user claims AND database.Users object in context
This commit is contained in:
@@ -8,9 +8,14 @@ import (
|
||||
ratelimit "bookhoard/internal/middleware"
|
||||
"bookhoard/internal/sync"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/labstack/echo-jwt/v4"
|
||||
"github.com/labstack/echo/v4"
|
||||
echomiddleware "github.com/labstack/echo/v4/middleware"
|
||||
)
|
||||
@@ -46,6 +51,37 @@ type Config struct {
|
||||
LoginTracker *ratelimit.LoginAttemptTracker
|
||||
}
|
||||
|
||||
// createJWTMiddleware creates a JWT middleware with proper user context setup
|
||||
func createJWTMiddleware(cfg *Config) echo.MiddlewareFunc {
|
||||
return echojwt.WithConfig(echojwt.Config{
|
||||
SigningKey: []byte(cfg.Cfg.JWTSecret),
|
||||
ContextKey: "user",
|
||||
SuccessHandler: func(c echo.Context) {
|
||||
token := c.Get("user").(*jwt.Token)
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
c.Set("user_id", claims["user_id"])
|
||||
c.Set("user_role", claims["user_role"])
|
||||
c.Set("user_email", claims["user_email"])
|
||||
c.Set("user_username", claims["user_username"])
|
||||
|
||||
// Parse UUID from string claims
|
||||
userIDStr, _ := claims["user_id"].(string)
|
||||
userUUID, err := uuid.Parse(userIDStr)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid user ID in token"})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user", database.Users{
|
||||
ID: pgtype.UUID{Bytes: [16]byte(userUUID), Valid: true},
|
||||
Email: claims["user_email"].(string),
|
||||
Username: claims["user_username"].(string),
|
||||
Role: claims["user_role"].(string),
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// RegisterRoutes registers all application routes
|
||||
func RegisterRoutes(cfg *Config) {
|
||||
e := cfg.Echo
|
||||
|
||||
Reference in New Issue
Block a user