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:
+2
-15
@@ -3,8 +3,6 @@ package router
|
||||
import (
|
||||
"bookhoard/internal/handlers"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/labstack/echo-jwt/v4"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
@@ -16,18 +14,7 @@ func registerAuthRoutes(cfg *Config, rateLimitMiddleware echo.MiddlewareFunc) {
|
||||
e.POST("/api/auth/login", rateLimitMiddleware(cfg.AuthHandler.Login))
|
||||
|
||||
// JWT middleware for protected routes
|
||||
jwtMiddleware := 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"])
|
||||
},
|
||||
})
|
||||
jwtMiddleware := createJWTMiddleware(cfg)
|
||||
|
||||
// Create protected route group
|
||||
protected := e.Group("/api", jwtMiddleware)
|
||||
@@ -43,7 +30,7 @@ func registerAuthRoutes(cfg *Config, rateLimitMiddleware echo.MiddlewareFunc) {
|
||||
e.POST("/api/auth/logout", cfg.AuthHandler.Logout)
|
||||
|
||||
// Auth update routes
|
||||
authGroup := e.Group("/api/auth", jwtMiddleware)
|
||||
authGroup := e.Group("/api/auth", createJWTMiddleware(cfg))
|
||||
authGroup.PUT("/email", cfg.AuthHandler.UpdateEmail)
|
||||
authGroup.PUT("/username", cfg.AuthHandler.UpdateUsername)
|
||||
authGroup.PUT("/password", cfg.AuthHandler.UpdatePassword)
|
||||
|
||||
Reference in New Issue
Block a user