2025-09-21 18:27:25 +08:00
|
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2026-02-02 14:58:48 +08:00
|
|
|
|
"net/http"
|
|
|
|
|
|
|
2025-09-30 17:44:18 +08:00
|
|
|
|
"tydata-server/app/main/model"
|
|
|
|
|
|
"tydata-server/common/ctxdata"
|
2026-02-02 14:58:48 +08:00
|
|
|
|
"tydata-server/common/result"
|
2025-09-30 17:44:18 +08:00
|
|
|
|
"tydata-server/common/xerr"
|
2025-09-21 18:27:25 +08:00
|
|
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
|
"github.com/zeromicro/go-zero/rest/httpx"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-02-02 14:58:48 +08:00
|
|
|
|
// 用户封禁状态:0 可用,1 禁用
|
|
|
|
|
|
const userDisableStatus = 1
|
|
|
|
|
|
|
2025-09-21 18:27:25 +08:00
|
|
|
|
type UserAuthInterceptorMiddleware struct {
|
2026-02-02 14:58:48 +08:00
|
|
|
|
UserModel model.UserModel
|
2025-09-21 18:27:25 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-02 14:58:48 +08:00
|
|
|
|
func NewUserAuthInterceptorMiddleware(userModel model.UserModel) *UserAuthInterceptorMiddleware {
|
|
|
|
|
|
return &UserAuthInterceptorMiddleware{UserModel: userModel}
|
2025-09-21 18:27:25 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (m *UserAuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
|
claims, err := ctxdata.GetClaimsFromCtx(r.Context())
|
|
|
|
|
|
if err != nil {
|
2026-02-02 14:58:48 +08:00
|
|
|
|
m.writeErrorResponse(w, http.StatusUnauthorized, errors.Wrapf(xerr.NewErrCode(ErrCodeUnauthorized), "token解析失败: %v", err))
|
2025-09-21 18:27:25 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if claims.UserType == model.UserTypeTemp {
|
2026-02-02 14:58:48 +08:00
|
|
|
|
m.writeErrorResponse(w, http.StatusUnauthorized, errors.Wrapf(xerr.NewErrCode(xerr.USER_NEED_BIND_MOBILE), "请先绑定手机号"))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
// 封禁校验:用户已被禁用则直接拒绝
|
|
|
|
|
|
user, err := m.UserModel.FindOne(r.Context(), claims.UserId)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
m.writeErrorResponse(w, http.StatusUnauthorized, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败: %v", err))
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
if user.Disable == userDisableStatus {
|
|
|
|
|
|
m.writeErrorResponse(w, http.StatusForbidden, xerr.NewErrCode(xerr.USER_DISABLED))
|
2025-09-21 18:27:25 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
next(w, r)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-02-02 14:58:48 +08:00
|
|
|
|
|
|
|
|
|
|
// writeErrorResponse 统一返回 code + msg,便于前端展示提示信息
|
|
|
|
|
|
func (m *UserAuthInterceptorMiddleware) writeErrorResponse(w http.ResponseWriter, statusCode int, err error) {
|
|
|
|
|
|
errcode := xerr.SERVER_COMMON_ERROR
|
|
|
|
|
|
errmsg := xerr.MapErrMsg(errcode)
|
|
|
|
|
|
if e, ok := errors.Cause(err).(*xerr.CodeError); ok {
|
|
|
|
|
|
errcode = e.GetErrCode()
|
|
|
|
|
|
errmsg = e.GetErrMsg()
|
|
|
|
|
|
}
|
|
|
|
|
|
httpx.WriteJson(w, statusCode, result.Error(errcode, errmsg))
|
|
|
|
|
|
}
|