29 lines
631 B
Go
29 lines
631 B
Go
package middleware
|
|
|
|
import (
|
|
"backend/store"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func ValidateToken() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token := c.GetHeader("Authorization")
|
|
if len(token) > 7 && token[:7] == "Bearer " {
|
|
token = token[7:]
|
|
}
|
|
if token == "" || !store.IsTokenValid(token) {
|
|
c.JSON(401, gin.H{"error": "Authorization header is required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
tokenInfo, _ := store.GetTokenInfo(token)
|
|
if tokenInfo != nil {
|
|
c.Set("admin", tokenInfo.UserName)
|
|
}
|
|
// 这里可以添加逻辑来验证token的有效性
|
|
// 假设验证通过,继续处理请求
|
|
c.Next()
|
|
}
|
|
}
|