| | | 1 | | using Elsa.Identity.Contracts; |
| | | 2 | | using Elsa.Identity.Entities; |
| | | 3 | | using Elsa.Identity.Models; |
| | | 4 | | using Humanizer; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Identity.Services; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Default implementation of <see cref="IRoleManager"/>. |
| | | 10 | | /// </summary> |
| | | 11 | | public class RoleManager : IRoleManager |
| | | 12 | | { |
| | | 13 | | private readonly IRoleStore _roleStore; |
| | | 14 | | private readonly IRoleProvider _roleProvider; |
| | | 15 | | |
| | 6 | 16 | | public RoleManager(IRoleStore roleStore, IRoleProvider roleProvider) |
| | | 17 | | { |
| | 6 | 18 | | _roleStore = roleStore; |
| | 6 | 19 | | _roleProvider = roleProvider; |
| | 6 | 20 | | } |
| | | 21 | | |
| | | 22 | | /// <inheritdoc /> |
| | | 23 | | public async Task<CreateRoleResult> CreateRoleAsync( |
| | | 24 | | string name, |
| | | 25 | | ICollection<string>? permissions = null, |
| | | 26 | | string? id = null, |
| | | 27 | | CancellationToken cancellationToken = default) |
| | | 28 | | { |
| | 2 | 29 | | var roleId = id ?? name.Kebaberize(); |
| | | 30 | | |
| | 2 | 31 | | if (await RoleExistsAsync(roleId, cancellationToken)) |
| | 2 | 32 | | throw new InvalidOperationException($"A role with ID '{roleId}' already exists."); |
| | | 33 | | |
| | 0 | 34 | | var role = new Role |
| | 0 | 35 | | { |
| | 0 | 36 | | Id = roleId, |
| | 0 | 37 | | Name = name, |
| | 0 | 38 | | Permissions = permissions ?? new List<string>() |
| | 0 | 39 | | }; |
| | | 40 | | |
| | 0 | 41 | | await _roleStore.SaveAsync(role, cancellationToken); |
| | | 42 | | |
| | 0 | 43 | | return new CreateRoleResult(role); |
| | 0 | 44 | | } |
| | | 45 | | |
| | | 46 | | private async Task<bool> RoleExistsAsync(string roleId, CancellationToken cancellationToken) |
| | | 47 | | { |
| | 2 | 48 | | var storedRole = await _roleStore.FindAsync(new() { Id = roleId }, cancellationToken); |
| | 2 | 49 | | if (storedRole != null) |
| | 1 | 50 | | return true; |
| | | 51 | | |
| | 1 | 52 | | var providedRoles = await _roleProvider.FindManyAsync(new() { Id = roleId }, cancellationToken); |
| | 2 | 53 | | return providedRoles.Any(x => x.Id == roleId); |
| | 2 | 54 | | } |
| | | 55 | | } |