From 466817d6ad5098a7e3d84276315ea188f1ac7ec3 Mon Sep 17 00:00:00 2001 From: Leon <147289645+LeoninCS@users.noreply.github.com> Date: Sun, 7 Dec 2025 17:36:44 +0800 Subject: [PATCH] fix: ensure jwt token matches the currently stored token --- internal/http/router.go | 4 ++-- internal/middleware/jwt.go | 13 ++++++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/internal/http/router.go b/internal/http/router.go index 0acd38d..eea1fe5 100644 --- a/internal/http/router.go +++ b/internal/http/router.go @@ -24,7 +24,7 @@ func SetRouter(db *gorm.DB) *gin.Engine { accountGroup.POST("/findByUsername", accountHandler.FindByUsername) } protectedAccountGroup := accountGroup.Group("") - protectedAccountGroup.Use(middleware.JWTAuth()) + protectedAccountGroup.Use(middleware.JWTAuth(accountRepository)) { protectedAccountGroup.POST("/logout", accountHandler.Logout) protectedAccountGroup.POST("/rename", accountHandler.RenameByID) @@ -40,7 +40,7 @@ func SetRouter(db *gorm.DB) *gin.Engine { videoGroup.POST("/getDetail", videoHandler.GetDetail) } protectedVideoGroup := videoGroup.Group("") - protectedVideoGroup.Use(middleware.JWTAuth()) + protectedVideoGroup.Use(middleware.JWTAuth(accountRepository)) { protectedVideoGroup.POST("/publish", videoHandler.PublishVideo) } diff --git a/internal/middleware/jwt.go b/internal/middleware/jwt.go index c718ac7..255f733 100644 --- a/internal/middleware/jwt.go +++ b/internal/middleware/jwt.go @@ -7,11 +7,12 @@ import ( "github.com/gin-gonic/gin" + "feedsystem_video_go/internal/account" "feedsystem_video_go/internal/auth" ) -// JWTAuth check jwt token -func JWTAuth() gin.HandlerFunc { +// JWTAuth check jwt token and ensure it matches the currently stored token. +func JWTAuth(accountRepo *account.AccountRepository) gin.HandlerFunc { return func(c *gin.Context) { authHeader := c.GetHeader("Authorization") if authHeader == "" { @@ -33,7 +34,13 @@ func JWTAuth() gin.HandlerFunc { return } - c.Set("account_id", claims.AccountID) + accountInfo, err := accountRepo.FindByID(claims.AccountID) + if err != nil || accountInfo.Token == "" || accountInfo.Token != tokenString { + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token has been revoked"}) + return + } + + c.Set("accountID", claims.AccountID) c.Set("username", claims.Username) c.Next()