IdentityRoleReader.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using Application.Abstractions.Identity;
  2. using Application.Abstractions.Identity.Models;
  3. using Microsoft.AspNetCore.Identity;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Infrastructure.Persistence.Identity;
  6. public sealed class IdentityRoleReader(RoleManager<IdentityRole> roleManager) : IIdentityRoleReader
  7. {
  8. public async Task<List<RoleDto>> GetRolesAsync(CancellationToken ct)
  9. {
  10. var roles = await roleManager.Roles.AsNoTracking().ToListAsync(ct);
  11. var list = new List<RoleDto>(roles.Count);
  12. foreach (var role in roles)
  13. {
  14. var claims = await roleManager.GetClaimsAsync(role);
  15. list.Add(new RoleDto
  16. {
  17. ID = role.Id,
  18. Name = role.Name,
  19. Claims = [..claims.Select(c => c.Value)]
  20. });
  21. }
  22. return list;
  23. }
  24. public async Task<RoleDto> GetRoleAsync(string roleID, CancellationToken ct)
  25. {
  26. if (string.IsNullOrWhiteSpace(roleID))
  27. {
  28. throw new InvalidOperationException("RoleID는 필수입니다.");
  29. }
  30. var role = await roleManager.FindByIdAsync(roleID);
  31. if (role is null)
  32. {
  33. throw new InvalidOperationException($"{roleID} 권한은 존재하지 않습니다.");
  34. }
  35. var claims = await roleManager.GetClaimsAsync(role);
  36. var values = claims.Select(c => c.Value).ToList();
  37. return new RoleDto{
  38. ID = role.Id,
  39. Name = role.Name ?? string.Empty,
  40. Claims = values
  41. };
  42. }
  43. }