refactor: extract token retrieval logic into GetAPITokenFromContext utility function

This commit is contained in:
Marvin Zhang
2025-06-16 21:49:27 +08:00
parent 6d65cc13a2
commit 24452bff23
2 changed files with 15 additions and 5 deletions

View File

@@ -9,7 +9,6 @@ import (
"github.com/crawlab-team/crawlab/core/utils"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"strings"
)
func AuthorizationMiddleware() gin.HandlerFunc {
@@ -28,10 +27,7 @@ func AuthorizationMiddleware() gin.HandlerFunc {
}
// token string
tokenStr := c.GetHeader("Authorization")
if strings.HasPrefix(tokenStr, "Bearer ") {
tokenStr = strings.Replace(tokenStr, "Bearer ", "", 1)
}
tokenStr := utils.GetAPITokenFromContext(c)
// validate token
u, err := userSvc.CheckToken(tokenStr)

14
core/utils/token.go Normal file
View File

@@ -0,0 +1,14 @@
package utils
import (
"github.com/gin-gonic/gin"
"strings"
)
func GetAPITokenFromContext(c *gin.Context) string {
tokenStr := c.GetHeader("Authorization")
if strings.HasPrefix(tokenStr, "Bearer ") {
tokenStr = strings.Replace(tokenStr, "Bearer ", "", 1)
}
return tokenStr
}