Browse Source

feat(auth): 优化用户认证时的权限检查逻辑

1. 添加 IRolePermissionRepository 依赖注入 2. 实现用户角色权限的完整获取 3. 优化权限信息的存储结构 4. 使用权限代码作为权限标识 5. 避免重复权限的存储
web
hyh 3 months ago
parent
commit
83a6cc88ce
  1. 22
      src/CellularManagement.Application/Features/Auth/Commands/AuthenticateUser/AuthenticateUserCommandHandler.cs

22
src/CellularManagement.Application/Features/Auth/Commands/AuthenticateUser/AuthenticateUserCommandHandler.cs

@ -19,6 +19,7 @@ public sealed class AuthenticateUserCommandHandler : IRequestHandler<Authenticat
private readonly IJwtProvider _jwtProvider;
private readonly ILogger<AuthenticateUserCommandHandler> _logger;
private readonly IUserRoleRepository _userRoleRepository;
private readonly IRolePermissionRepository _rolePermissionRepository;
/// <summary>
/// 初始化处理器
@ -27,12 +28,14 @@ public sealed class AuthenticateUserCommandHandler : IRequestHandler<Authenticat
UserManager<AppUser> userManager,
IJwtProvider jwtProvider,
ILogger<AuthenticateUserCommandHandler> logger,
IUserRoleRepository userRoleRepository)
IUserRoleRepository userRoleRepository,
IRolePermissionRepository rolePermissionRepository)
{
_userManager = userManager;
_jwtProvider = jwtProvider;
_logger = logger;
_userRoleRepository = userRoleRepository;
_rolePermissionRepository = rolePermissionRepository;
}
/// <summary>
@ -85,6 +88,20 @@ public sealed class AuthenticateUserCommandHandler : IRequestHandler<Authenticat
// 添加角色声明
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
// 获取所有角色的权限
var permissions = new Dictionary<string, bool>();
foreach (var role in roles)
{
var rolePermissions = await _rolePermissionRepository.GetRolePermissionsWithDetailsAsync(role, cancellationToken);
foreach (var rolePermission in rolePermissions)
{
if (!permissions.ContainsKey(rolePermission.Permission.Code))
{
permissions[rolePermission.Permission.Code] = true;
}
}
}
// 生成访问令牌
var accessToken = _jwtProvider.GenerateAccessToken(claims);
@ -100,7 +117,8 @@ public sealed class AuthenticateUserCommandHandler : IRequestHandler<Authenticat
user.UserName!,
user.Email!,
user.PhoneNumber,
roles);
roles,
permissions);
_logger.LogInformation("用户 {UserName} 认证成功", request.UserName);

Loading…
Cancel
Save