fix: enforce content visibility and tenant login

This commit is contained in:
2026-01-13 09:28:45 +08:00
parent ca7c799344
commit 342987334a
4 changed files with 231 additions and 27 deletions

View File

@@ -64,8 +64,12 @@ func (s *user) LoginWithOTP(ctx context.Context, tenantID int64, phone, otp stri
if u.Status == consts.UserStatusBanned {
return nil, errorx.ErrAccountDisabled
}
// 4. 校验租户成员关系(租户上下文下仅允许成员登录)。
if err := s.ensureTenantMember(ctx, tenantID, u.ID); err != nil {
return nil, err
}
// 4. 生成 Token
// 5. 生成 Token
token, err := s.jwt.CreateToken(s.jwt.CreateClaims(jwt.BaseClaims{
UserID: u.ID,
TenantID: tenantID,
@@ -80,6 +84,38 @@ func (s *user) LoginWithOTP(ctx context.Context, tenantID int64, phone, otp stri
}, nil
}
func (s *user) ensureTenantMember(ctx context.Context, tenantID, userID int64) error {
if tenantID <= 0 {
return nil
}
// 校验租户存在避免非法租户ID绕过校验。
tblTenant, tenantQuery := models.TenantQuery.QueryContext(ctx)
tenant, err := tenantQuery.Where(tblTenant.ID.Eq(tenantID)).First()
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errorx.ErrRecordNotFound.WithCause(err).WithMsg("租户不存在")
}
return errorx.ErrDatabaseError.WithCause(err)
}
if tenant.UserID == userID {
return nil
}
tbl, q := models.TenantUserQuery.QueryContext(ctx)
exists, err := q.Where(
tbl.TenantID.Eq(tenantID),
tbl.UserID.Eq(userID),
tbl.Status.Eq(consts.UserStatusVerified),
).Exists()
if err != nil {
return errorx.ErrDatabaseError.WithCause(err)
}
if !exists {
return errorx.ErrForbidden.WithMsg("未加入该租户")
}
return nil
}
// GetModelByID 获取指定 ID 的用户model
func (s *user) GetModelByID(ctx context.Context, userID int64) (*models.User, error) {
tbl, query := models.UserQuery.QueryContext(ctx)