fix: ensure jwt token matches the currently stored token

This commit is contained in:
Leon
2025-12-07 17:36:44 +08:00
parent 86e817458c
commit 466817d6ad
2 changed files with 12 additions and 5 deletions

View File

@@ -24,7 +24,7 @@ func SetRouter(db *gorm.DB) *gin.Engine {
accountGroup.POST("/findByUsername", accountHandler.FindByUsername) accountGroup.POST("/findByUsername", accountHandler.FindByUsername)
} }
protectedAccountGroup := accountGroup.Group("") protectedAccountGroup := accountGroup.Group("")
protectedAccountGroup.Use(middleware.JWTAuth()) protectedAccountGroup.Use(middleware.JWTAuth(accountRepository))
{ {
protectedAccountGroup.POST("/logout", accountHandler.Logout) protectedAccountGroup.POST("/logout", accountHandler.Logout)
protectedAccountGroup.POST("/rename", accountHandler.RenameByID) protectedAccountGroup.POST("/rename", accountHandler.RenameByID)
@@ -40,7 +40,7 @@ func SetRouter(db *gorm.DB) *gin.Engine {
videoGroup.POST("/getDetail", videoHandler.GetDetail) videoGroup.POST("/getDetail", videoHandler.GetDetail)
} }
protectedVideoGroup := videoGroup.Group("") protectedVideoGroup := videoGroup.Group("")
protectedVideoGroup.Use(middleware.JWTAuth()) protectedVideoGroup.Use(middleware.JWTAuth(accountRepository))
{ {
protectedVideoGroup.POST("/publish", videoHandler.PublishVideo) protectedVideoGroup.POST("/publish", videoHandler.PublishVideo)
} }

View File

@@ -7,11 +7,12 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"feedsystem_video_go/internal/account"
"feedsystem_video_go/internal/auth" "feedsystem_video_go/internal/auth"
) )
// JWTAuth check jwt token // JWTAuth check jwt token and ensure it matches the currently stored token.
func JWTAuth() gin.HandlerFunc { func JWTAuth(accountRepo *account.AccountRepository) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization") authHeader := c.GetHeader("Authorization")
if authHeader == "" { if authHeader == "" {
@@ -33,7 +34,13 @@ func JWTAuth() gin.HandlerFunc {
return 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.Set("username", claims.Username)
c.Next() c.Next()