2025-05-11 19:39:56 +08:00
|
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2025-05-26 17:19:07 +08:00
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
2025-05-11 19:39:56 +08:00
|
|
|
|
"net/http"
|
|
|
|
|
"qnc-server/app/user/cmd/api/internal/config"
|
|
|
|
|
"qnc-server/common/ctxdata"
|
|
|
|
|
jwtx "qnc-server/common/jwt"
|
|
|
|
|
"qnc-server/common/xerr"
|
|
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
"github.com/zeromicro/go-zero/rest/httpx"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
// 定义错误码
|
|
|
|
|
ErrCodeUnauthorized = 401
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type AuthInterceptorMiddleware struct {
|
|
|
|
|
Config config.Config
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewAuthInterceptorMiddleware(c config.Config) *AuthInterceptorMiddleware {
|
|
|
|
|
return &AuthInterceptorMiddleware{
|
|
|
|
|
Config: c,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (m *AuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
// 从请求头中获取Authorization字段
|
|
|
|
|
authHeader := r.Header.Get("Authorization")
|
|
|
|
|
|
|
|
|
|
// 如果没有Authorization头,直接放行
|
|
|
|
|
if authHeader == "" {
|
|
|
|
|
next(w, r)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 解析JWT令牌
|
|
|
|
|
userId, err := jwtx.ParseJwtToken(authHeader, m.Config.JwtAuth.AccessSecret)
|
|
|
|
|
if err != nil {
|
|
|
|
|
// JWT解析失败,返回401错误
|
|
|
|
|
httpx.Error(w, errors.Wrapf(xerr.NewErrCode(ErrCodeUnauthorized), "token解析失败: %v", err))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-26 17:19:07 +08:00
|
|
|
|
// 将用户ID转换为json.Number类型后添加到请求上下文
|
|
|
|
|
userIdStr := fmt.Sprintf("%d", userId)
|
|
|
|
|
userIdJsonNum := json.Number(userIdStr)
|
|
|
|
|
ctx := context.WithValue(r.Context(), ctxdata.CtxKeyJwtUserId, userIdJsonNum)
|
2025-05-11 19:39:56 +08:00
|
|
|
|
|
|
|
|
|
// 使用新的上下文继续处理请求
|
|
|
|
|
next(w, r.WithContext(ctx))
|
|
|
|
|
}
|
|
|
|
|
}
|