This commit is contained in:
Mrx
2026-02-04 13:33:21 +08:00
parent e7c2ddbd93
commit e1fbf72437
23 changed files with 190 additions and 65 deletions

View File

@@ -1,10 +1,10 @@
package middleware
import (
"net/http"
"tydata-server/app/main/model"
"tydata-server/common/ctxdata"
"tydata-server/common/xerr"
"net/http"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/rest/httpx"

View File

@@ -0,0 +1,69 @@
package middleware
import (
"net/http"
"strings"
"tydata-server/app/main/api/internal/config"
"tydata-server/app/main/model"
jwtx "tydata-server/common/jwt"
"tydata-server/common/result"
"tydata-server/common/xerr"
"github.com/zeromicro/go-zero/rest/httpx"
)
// UserDisableCheckMiddleware 全局中间件:若当前用户已被封禁(disable=1),则拒绝请求并返回封禁原因
type UserDisableCheckMiddleware struct {
Config config.Config
UserModel model.UserModel
}
// NewUserDisableCheckMiddleware 创建封禁检查中间件
func NewUserDisableCheckMiddleware(c config.Config, userModel model.UserModel) *UserDisableCheckMiddleware {
return &UserDisableCheckMiddleware{
Config: c,
UserModel: userModel,
}
}
// Handle 仅对携带用户 JWT 的请求做封禁校验;无 token 或 admin token 直接放行
func (m *UserDisableCheckMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
next(w, r)
return
}
token := strings.TrimPrefix(authHeader, "Bearer ")
if token == authHeader {
next(w, r)
return
}
// 仅使用用户端 JWT 密钥解析;管理员 token 会解析失败,直接放行由后续中间件处理
claims, err := jwtx.ParseJwtToken(token, m.Config.JwtAuth.AccessSecret)
if err != nil {
next(w, r)
return
}
// 查封禁状态不走缓存,封禁后立即生效,已登录用户下次请求即被拒绝
disable, err := m.UserModel.FindDisableByUserId(r.Context(), claims.UserId)
if err != nil {
next(w, r)
return
}
// disable: 0 可用1 封禁
if disable == 1 {
errcode := xerr.USER_DISABLED
errmsg := xerr.MapErrMsg(errcode)
httpx.WriteJson(w, http.StatusForbidden, result.Error(errcode, errmsg))
return
}
next(w, r)
}
}