| | | 1 | | using Syki.Back.Domain.Identity; |
| | | 2 | | using Syki.Back.Auth.Permissions; |
| | | 3 | | |
| | | 4 | | namespace Syki.Back.Features.Identity.CreateRole; |
| | | 5 | | |
| | 18 | 6 | | public class CreateRoleService(SykiDbContext ctx) : ISykiService |
| | | 7 | | { |
| | | 8 | | private class Validator : AbstractValidator<CreateRoleIn> |
| | | 9 | | { |
| | 2 | 10 | | public Validator() |
| | | 11 | | { |
| | 2 | 12 | | RuleFor(x => x.Name).NotEmpty().WithError(InvalidRoleName.I); |
| | 2 | 13 | | RuleFor(x => x.Name).MaximumLength(50).WithError(InvalidRoleName.I); |
| | | 14 | | |
| | 2 | 15 | | RuleFor(x => x.Description).NotEmpty().WithError(InvalidRoleDescription.I); |
| | 2 | 16 | | RuleFor(x => x.Description).MaximumLength(200).WithError(InvalidRoleDescription.I); |
| | | 17 | | |
| | 2 | 18 | | RuleFor(x => x.BaseType).IsInEnum().WithError(InvalidRoleBaseType.I); |
| | | 19 | | |
| | 2 | 20 | | RuleFor(x => x.Permissions) |
| | 252 | 21 | | .Must(x => x != null && x.IsAllDistinct() && x.IsSubsetOf(SykiPermissions.Permissions.ConvertAll(p => p. |
| | 2 | 22 | | .WithError(InvalidPermissionsList.I); |
| | | 23 | | |
| | 2 | 24 | | RuleFor(x => x) |
| | 20 | 25 | | .Must(x => x.Permissions.All(id => SykiPermissions.IsAllowedFor(id, x.BaseType))) |
| | 2 | 26 | | .WithError(InvalidPermissionsForUserType.I); |
| | 2 | 27 | | } |
| | | 28 | | } |
| | 2 | 29 | | private static readonly Validator V = new(); |
| | | 30 | | |
| | | 31 | | public async Task<OneOf<CreateRoleOut, SykiError>> Create(CreateRoleIn data) |
| | | 32 | | { |
| | 26 | 33 | | if (V.Run(data, out var error)) return error; |
| | | 34 | | |
| | 10 | 35 | | var institutionId = ctx.RequestUser.InstitutionId; |
| | 10 | 36 | | var upperCaseName = data.Name.Normalize().ToUpperInvariant(); |
| | 10 | 37 | | var roleAlreadyExists = await ctx.Roles.AnyAsync(x => x.OwnerId == institutionId && x.NormalizedName == upperCas |
| | 12 | 38 | | if (roleAlreadyExists) return RoleNameAlreadyExists.I; |
| | | 39 | | |
| | 8 | 40 | | var role = new SykiRole(institutionId, data.Name, data.Description, data.BaseType, data.Permissions); |
| | 8 | 41 | | var rolePermissionsOk = role.IsSubsetOf(ctx.RequestUser.Permissions); |
| | 8 | 42 | | if (!rolePermissionsOk) return InvalidRolePermissions.I; |
| | | 43 | | |
| | 8 | 44 | | var orgRole = new InstitutionRole(institutionId, role); |
| | 8 | 45 | | ctx.AddRange(role, orgRole); |
| | 8 | 46 | | ctx.RecordSuccess(UserActivityType.CreateRole_Success, metadata: new { role.Id }); |
| | 8 | 47 | | await ctx.SaveChangesAsync(); |
| | | 48 | | |
| | 8 | 49 | | return new CreateRoleOut { Id = role.Id }; |
| | 18 | 50 | | } |
| | | 51 | | } |