Files
hm-server/app/main/api/internal/middleware/userauthinterceptormiddleware.go
2026-02-02 14:58:48 +08:00

61 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"net/http"
"tydata-server/app/main/model"
"tydata-server/common/ctxdata"
"tydata-server/common/result"
"tydata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/rest/httpx"
)
// 用户封禁状态0 可用1 禁用
const userDisableStatus = 1
type UserAuthInterceptorMiddleware struct {
UserModel model.UserModel
}
func NewUserAuthInterceptorMiddleware(userModel model.UserModel) *UserAuthInterceptorMiddleware {
return &UserAuthInterceptorMiddleware{UserModel: userModel}
}
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 {
m.writeErrorResponse(w, http.StatusUnauthorized, errors.Wrapf(xerr.NewErrCode(ErrCodeUnauthorized), "token解析失败: %v", err))
return
}
if claims.UserType == model.UserTypeTemp {
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))
return
}
next(w, r)
}
}
// 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))
}