using DigitalOps.Authority.Services; using DigitalOps.Dal; using DigitalOps.Dal.DbEntity; using DigitalOps.Dal.Validators; using FluentValidation; using Microsoft.EntityFrameworkCore; namespace DigitalOps.Authority.Validators; public class HasAccessToClientValidator : AbstractValidator { private readonly OrganizationRole _role; private readonly MainDbContext _dbContext; private readonly UserIdentityService _userIdentityService; public HasAccessToClientValidator(OrganizationRole role, MainDbContext dbContext, UserIdentityService userIdentityService) { _role = role; _userIdentityService = userIdentityService; _dbContext = dbContext; RuleFor(clientId => clientId) .Cascade(CascadeMode.Stop) .SetValidator(new DbEntityExistValidator(dbContext)) .CustomAsync(async (clientId, validationContext, cancellationToken) => { var client = await _dbContext.Clients .AsNoTracking() .FirstOrDefaultAsync(client => client.Id == clientId, cancellationToken); if (client is null) return; var validation = new HasAccessToOrganizationValidator(_role, _dbContext, _userIdentityService); var validationResult = validation.Validate(client.OrganizationId); if (!validationResult.IsValid) foreach (var error in validationResult.Errors) validationContext.AddFailure(error); }); } }