| | | 1 | | using Syki.Back.Auth.Managers; |
| | | 2 | | using Syki.Back.Domain.Identity; |
| | | 3 | | |
| | | 4 | | namespace Syki.Back.Features.Identity.CreateSsoConfiguration; |
| | | 5 | | |
| | 0 | 6 | | public class CreateSsoConfigurationService(SykiDbContext ctx, SsoEncryptionManager encryption, SsoSchemeManager ssoSchem |
| | | 7 | | { |
| | | 8 | | private class Validator : AbstractValidator<CreateSsoConfigurationIn> |
| | | 9 | | { |
| | 0 | 10 | | public Validator() |
| | | 11 | | { |
| | 0 | 12 | | RuleFor(x => x.ProviderType).IsInEnum().WithError(InvalidSsoProviderType.I); |
| | | 13 | | |
| | 0 | 14 | | RuleFor(x => x.Authority).NotEmpty().WithError(InvalidSsoAuthority.I); |
| | | 15 | | |
| | 0 | 16 | | RuleFor(x => x.ClientId).NotEmpty().WithError(InvalidSsoClientId.I); |
| | 0 | 17 | | RuleFor(x => x.ClientId).MinimumLength(5).WithError(InvalidSsoClientId.I); |
| | | 18 | | |
| | 0 | 19 | | RuleFor(x => x.ClientSecret).NotEmpty().WithError(InvalidSsoClientSecret.I); |
| | 0 | 20 | | RuleFor(x => x.ClientSecret).MinimumLength(10).WithError(InvalidSsoClientSecret.I); |
| | 0 | 21 | | } |
| | | 22 | | } |
| | 0 | 23 | | private static readonly Validator V = new(); |
| | | 24 | | |
| | | 25 | | public async Task<OneOf<CreateSsoConfigurationOut, SykiError>> Create(CreateSsoConfigurationIn data) |
| | | 26 | | { |
| | 0 | 27 | | if (V.Run(data, out var error)) return error; |
| | | 28 | | |
| | 0 | 29 | | var authorityError = data.Authority.ValidateSsoAuthority(); |
| | 0 | 30 | | if (authorityError != null) return authorityError; |
| | | 31 | | |
| | 0 | 32 | | var userEmail = await ctx.Users.Where(x => x.Id == ctx.RequestUser.Id).Select(x => x.Email).FirstAsync(); |
| | | 33 | | |
| | 0 | 34 | | var domain = userEmail!.Split('@').Last().NormalizeSsoDomain(); |
| | 0 | 35 | | if (domain == null) return InvalidSsoAllowedDomains.I; |
| | | 36 | | |
| | 0 | 37 | | var domainExists = await ctx.WebSsoAllowedDomains.AnyAsync(d => d.Domain == domain); |
| | 0 | 38 | | if (domainExists) return SsoDomainAlreadyConfigured.I; |
| | | 39 | | |
| | 0 | 40 | | var config = new SsoConfiguration( |
| | 0 | 41 | | ctx.RequestUser.InstitutionId, |
| | 0 | 42 | | data.ProviderType, |
| | 0 | 43 | | data.Authority.TrimEnd('/'), |
| | 0 | 44 | | data.ClientId.Trim(), |
| | 0 | 45 | | encryption.Encrypt(data.ClientSecret), |
| | 0 | 46 | | [domain]); |
| | | 47 | | |
| | 0 | 48 | | await ctx.SaveChangesAsync(config); |
| | | 49 | | |
| | 0 | 50 | | ssoSchemeManager.RegisterScheme(config); |
| | | 51 | | |
| | 0 | 52 | | return new CreateSsoConfigurationOut { Id = config.PublicId }; |
| | 0 | 53 | | } |
| | | 54 | | } |