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:
1 parent
6784c25b2e
commit
b948d29b5e
8 files changed
+44
-76
No files matched your search
+1
-16
@@ -2,28 +2,13 @@ package router
|
||||
|
||||
import (
|
||||
"bookhoard/internal/handlers"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/labstack/echo-jwt/v4"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func registerSyncRoutes(cfg *Config) {
|
||||
e := cfg.Echo
|
||||
|
||||
// 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)
|
||||
|
||||
protected := e.Group("/api", jwtMiddleware)
|
||||
|
||||
|
||||
Reference in new issue
Block a user