You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.4 KiB
53 lines
1.4 KiB
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/youruser/base/internal/util/jwt"
|
|
)
|
|
|
|
type AuthMiddleware struct{}
|
|
|
|
func NewAuthMiddleware() *AuthMiddleware {
|
|
return &AuthMiddleware{}
|
|
}
|
|
|
|
func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// 从 Header 中获取 Token
|
|
authHeader := r.Header.Get("Authorization")
|
|
var tokenString string
|
|
if authHeader != "" {
|
|
// Token 格式: "Bearer <token>"
|
|
tokenString = strings.TrimPrefix(authHeader, "Bearer ")
|
|
}
|
|
|
|
// 回退: 从 query 参数获取 token(用于 img/video/iframe 等无法设置 Header 的场景)
|
|
if tokenString == "" {
|
|
tokenString = r.URL.Query().Get("token")
|
|
}
|
|
|
|
if tokenString == "" {
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// 解析并验证 Token
|
|
claims, err := jwt.ParseToken(tokenString)
|
|
if err != nil {
|
|
http.Error(w, "Invalid token: "+err.Error(), http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// 将 userId 存入上下文,供后续 logic 使用
|
|
ctx := context.WithValue(r.Context(), "userId", claims.UserID)
|
|
ctx = context.WithValue(ctx, "username", claims.Username)
|
|
ctx = context.WithValue(ctx, "role", claims.Role)
|
|
ctx = context.WithValue(ctx, "currentOrgId", claims.CurrentOrgId)
|
|
|
|
// 传递给下一个处理器
|
|
next(w, r.WithContext(ctx))
|
|
}
|
|
}
|
|
|