| | | 1 | | using Estud.Back.Domain.Identity; |
| | | 2 | | using Estud.Back.Auth.Permissions; |
| | | 3 | | |
| | | 4 | | namespace Estud.Back.Features.Identity.CreateRole; |
| | | 5 | | |
| | 26 | 6 | | public class CreateRoleService(EstudDbContext ctx) : IEstudService |
| | | 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) |
| | 416 | 21 | | .Must(x => x != null && x.IsAllDistinct() && x.IsSubsetOf(EstudPermissions.Permissions.ConvertAll(p => p |
| | 2 | 22 | | .WithError(InvalidPermissionsList.I); |
| | | 23 | | |
| | 2 | 24 | | RuleFor(x => x) |
| | 28 | 25 | | .Must(x => x.Permissions.All(id => EstudPermissions.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, EstudError>> Create(CreateRoleIn data) |
| | | 32 | | { |
| | 34 | 33 | | if (V.Run(data, out var error)) return error; |
| | | 34 | | |
| | 18 | 35 | | var institutionId = ctx.RequestUser.InstitutionId; |
| | 18 | 36 | | var upperCaseName = data.Name.Normalize().ToUpperInvariant(); |
| | 18 | 37 | | var roleAlreadyExists = await ctx.Roles.AnyAsync(x => x.OwnerId == institutionId && x.NormalizedName == upperCas |
| | 20 | 38 | | if (roleAlreadyExists) return RoleNameAlreadyExists.I; |
| | | 39 | | |
| | 16 | 40 | | var role = new EstudRole(institutionId, data.Name, data.Description, data.BaseType, data.Permissions); |
| | 16 | 41 | | var rolePermissionsOk = role.IsSubsetOf(ctx.RequestUser.Permissions); |
| | 16 | 42 | | if (!rolePermissionsOk) return InvalidRolePermissions.I; |
| | | 43 | | |
| | 16 | 44 | | var orgRole = new InstitutionRole(institutionId, role); |
| | 16 | 45 | | ctx.AddRange(role, orgRole); |
| | 16 | 46 | | ctx.RecordSuccess(UserActivityType.CreateRole_Success, metadata: new { role.Id }); |
| | 16 | 47 | | await ctx.SaveChangesAsync(); |
| | | 48 | | |
| | 16 | 49 | | return new CreateRoleOut { Id = role.Id }; |
| | 26 | 50 | | } |
| | | 51 | | } |