|
|
@ -18,15 +18,19 @@ func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc { |
|
|
return func(w http.ResponseWriter, r *http.Request) { |
|
|
return func(w http.ResponseWriter, r *http.Request) { |
|
|
// 从 Header 中获取 Token
|
|
|
// 从 Header 中获取 Token
|
|
|
authHeader := r.Header.Get("Authorization") |
|
|
authHeader := r.Header.Get("Authorization") |
|
|
if authHeader == "" { |
|
|
var tokenString string |
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized) |
|
|
if authHeader != "" { |
|
|
return |
|
|
// Token 格式: "Bearer <token>"
|
|
|
|
|
|
tokenString = strings.TrimPrefix(authHeader, "Bearer ") |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
// 回退: 从 query 参数获取 token(用于 img/video/iframe 等无法设置 Header 的场景)
|
|
|
|
|
|
if tokenString == "" { |
|
|
|
|
|
tokenString = r.URL.Query().Get("token") |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
// Token 格式: "Bearer <token>"
|
|
|
|
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ") |
|
|
|
|
|
if tokenString == "" { |
|
|
if tokenString == "" { |
|
|
http.Error(w, "Invalid token format", http.StatusUnauthorized) |
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized) |
|
|
return |
|
|
return |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
@ -41,6 +45,7 @@ func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc { |
|
|
ctx := context.WithValue(r.Context(), "userId", claims.UserID) |
|
|
ctx := context.WithValue(r.Context(), "userId", claims.UserID) |
|
|
ctx = context.WithValue(ctx, "username", claims.Username) |
|
|
ctx = context.WithValue(ctx, "username", claims.Username) |
|
|
ctx = context.WithValue(ctx, "role", claims.Role) |
|
|
ctx = context.WithValue(ctx, "role", claims.Role) |
|
|
|
|
|
ctx = context.WithValue(ctx, "currentOrgId", claims.CurrentOrgId) |
|
|
|
|
|
|
|
|
// 传递给下一个处理器
|
|
|
// 传递给下一个处理器
|
|
|
next(w, r.WithContext(ctx)) |
|
|
next(w, r.WithContext(ctx)) |
|
|
|