refactor: 收紧角色与商户跨租户能力

This commit is contained in:
root
2026-01-29 14:52:25 +00:00
parent a0b77d4847
commit 41cfd2e2e8
9 changed files with 120 additions and 75 deletions

View File

@@ -25,10 +25,23 @@ public sealed class CreateRoleCommandHandler(
/// <returns>创建后的角色 DTO。</returns>
public async Task<RoleDto> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
{
// 1. 获取租户上下文
var tenantId = request.TenantId ?? tenantProvider.GetCurrentTenantId();
// 1. 获取租户上下文并校验跨租户
var currentTenantId = tenantProvider.GetCurrentTenantId();
if (currentTenantId <= 0)
{
throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
}
// 2. 归一化输入并校验唯一
// 2. (空行后) 禁止跨租户创建
if (request.TenantId.HasValue && request.TenantId.Value != currentTenantId)
{
throw new BusinessException(ErrorCodes.Forbidden, "禁止跨租户创建角色");
}
// 3. (空行后) 使用当前租户创建角色
var tenantId = currentTenantId;
// 4. (空行后) 归一化输入并校验唯一
var name = request.Name?.Trim() ?? string.Empty;
var code = request.Code?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(code))
@@ -42,7 +55,7 @@ public sealed class CreateRoleCommandHandler(
throw new BusinessException(ErrorCodes.Conflict, "角色编码已存在");
}
// 3. 构建角色实体
// 5. (空行后) 构建角色实体
var role = new Role
{
TenantId = tenantId,
@@ -51,11 +64,11 @@ public sealed class CreateRoleCommandHandler(
Description = request.Description
};
// 4. 持久化
// 6. (空行后) 持久化
await roleRepository.AddAsync(role, cancellationToken);
await roleRepository.SaveChangesAsync(cancellationToken);
// 5. 返回 DTO
// 7. (空行后) 返回 DTO
return new RoleDto
{
Id = role.Id,