package middleware import ( "context" "net/http" "xingfucha-server/app/main/api/internal/config" "xingfucha-server/app/main/model" jwtx "xingfucha-server/common/jwt" "xingfucha-server/common/xerr" "github.com/pkg/errors" "github.com/zeromicro/go-zero/rest/httpx" ) const ( // 定义错误码 ErrCodeUnauthorized = 401 ) type AuthInterceptorMiddleware struct { Config config.Config UserModel model.UserModel } func NewAuthInterceptorMiddleware(c config.Config, userModel model.UserModel) *AuthInterceptorMiddleware { return &AuthInterceptorMiddleware{ Config: c, UserModel: userModel, } } 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令牌 claims, 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 } // 携带token的请求:校验用户是否被封禁(保证封禁即时生效) if m.UserModel != nil && claims.UserId > 0 { user, err := m.UserModel.FindOne(r.Context(), claims.UserId) if err == nil && user.Disable == model.UserDisableBanned { httpx.Error(w, xerr.NewErrCode(xerr.USER_DISABLED)) return } } ctx := context.WithValue(r.Context(), jwtx.ExtraKey, claims) // 使用新的上下文继续处理请求 next(w, r.WithContext(ctx)) } }