76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"photography-backend/pkg/utils/jwt"
|
|
|
|
"github.com/zeromicro/go-zero/rest/httpx"
|
|
)
|
|
|
|
// AuthMiddleware JWT 认证中间件
|
|
type AuthMiddleware struct {
|
|
secret string
|
|
}
|
|
|
|
// NewAuthMiddleware 创建认证中间件
|
|
func NewAuthMiddleware(secret string) *AuthMiddleware {
|
|
return &AuthMiddleware{
|
|
secret: secret,
|
|
}
|
|
}
|
|
|
|
// Handle 处理认证
|
|
func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// 获取 Authorization header
|
|
authHeader := r.Header.Get("Authorization")
|
|
if authHeader == "" {
|
|
httpx.ErrorCtx(r.Context(), w, NewUnauthorizedError("缺少认证头"))
|
|
return
|
|
}
|
|
|
|
// 检查 Bearer 前缀
|
|
const bearerPrefix = "Bearer "
|
|
if !strings.HasPrefix(authHeader, bearerPrefix) {
|
|
httpx.ErrorCtx(r.Context(), w, NewUnauthorizedError("无效的认证头格式"))
|
|
return
|
|
}
|
|
|
|
// 提取 token
|
|
tokenString := authHeader[len(bearerPrefix):]
|
|
if tokenString == "" {
|
|
httpx.ErrorCtx(r.Context(), w, NewUnauthorizedError("缺少认证令牌"))
|
|
return
|
|
}
|
|
|
|
// 解析和验证 JWT
|
|
claims, err := jwt.ParseToken(tokenString, m.secret)
|
|
if err != nil {
|
|
httpx.ErrorCtx(r.Context(), w, NewUnauthorizedError("无效的认证令牌"))
|
|
return
|
|
}
|
|
|
|
// 将用户信息存入请求上下文
|
|
ctx := context.WithValue(r.Context(), "userId", claims.UserId)
|
|
ctx = context.WithValue(ctx, "username", claims.Username)
|
|
|
|
// 继续执行下一个处理器
|
|
next(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// UnauthorizedError 未授权错误
|
|
type UnauthorizedError struct {
|
|
Message string
|
|
}
|
|
|
|
func (e UnauthorizedError) Error() string {
|
|
return e.Message
|
|
}
|
|
|
|
func NewUnauthorizedError(message string) UnauthorizedError {
|
|
return UnauthorizedError{Message: message}
|
|
} |