58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
// Package middleware Gin 中间件集合。
|
|
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"fashionapi/internal/pkg/jwt"
|
|
"fashionapi/internal/pkg/response"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// gin.Context 中存放身份信息的键。
|
|
const (
|
|
ContextUserID = "userID"
|
|
ContextUsername = "username"
|
|
)
|
|
|
|
// bearerPrefix Authorization 头的令牌前缀。
|
|
const bearerPrefix = "Bearer "
|
|
|
|
// Auth JWT 鉴权中间件:解析 Authorization: Bearer <token>,把身份写入 Context。
|
|
//
|
|
// 令牌签发器由外部注入,避免像原实现那样在每个请求里重新加载一次配置。
|
|
func Auth(manager *jwt.Manager) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
header := c.GetHeader("Authorization")
|
|
if !strings.HasPrefix(header, bearerPrefix) {
|
|
response.AbortError(c, http.StatusUnauthorized, "missing token")
|
|
return
|
|
}
|
|
|
|
claims, err := manager.Parse(strings.TrimPrefix(header, bearerPrefix))
|
|
if err != nil {
|
|
response.AbortError(c, http.StatusUnauthorized, "invalid token")
|
|
return
|
|
}
|
|
|
|
c.Set(ContextUserID, claims.UserID)
|
|
c.Set(ContextUsername, claims.Username)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// UserIDFrom 从 Context 取出当前用户 id。
|
|
func UserIDFrom(c *gin.Context) (uint32, bool) {
|
|
v, exists := c.Get(ContextUserID)
|
|
if !exists {
|
|
return 0, false
|
|
}
|
|
id, ok := v.(uint32)
|
|
if !ok || id == 0 {
|
|
return 0, false
|
|
}
|
|
return id, true
|
|
}
|