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.
48 lines
1.2 KiB
48 lines
1.2 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")
|
|
if authHeader == "" {
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Token 格式: "Bearer <token>"
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
|
if tokenString == "" {
|
|
http.Error(w, "Invalid token format", 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)
|
|
|
|
// 传递给下一个处理器
|
|
next(w, r.WithContext(ctx))
|
|
}
|
|
}
|
|
|