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