private async Task SecurityTokenValidated(SecurityTokenValidatedNotification <WsFederationMessage, WsFederationAuthenticationOptions> notification, IProviderCommitmentsLogger logger, AuthenticationOrchestrator orchestrator, AccountOrchestrator accountOrchestrator) { logger.Info("SecurityTokenValidated notification called"); var identity = notification.AuthenticationTicket.Identity; var id = identity.Claims.FirstOrDefault(claim => claim.Type == (DasClaimTypes.Upn))?.Value; var displayName = identity.Claims.FirstOrDefault(claim => claim.Type == (DasClaimTypes.DisplayName))?.Value; var ukprn = identity.Claims.FirstOrDefault(claim => claim.Type == (DasClaimTypes.Ukprn))?.Value; var email = identity.Claims.FirstOrDefault(claim => claim.Type == (DasClaimTypes.Email))?.Value; long parsedUkprn; if (!long.TryParse(ukprn, out parsedUkprn)) { logger.Info($"Unable to parse Ukprn \"{ukprn}\" from claims for user \"{id}\""); return; } var showReservations = await accountOrchestrator.ProviderHasPermission(parsedUkprn, Operation.CreateCohort); identity.AddClaim(new Claim(DasClaimTypes.ShowReservations, showReservations.ToString(), "bool")); identity.MapClaimToRoles(); await orchestrator.SaveIdentityAttributes(id, parsedUkprn, displayName, email); }
public async Task SendEmailToAllProviderRecipients(long providerId, ProviderEmailRequest message) { List <string> recipients; var accountUsers = (await _accountOrchestrator.GetAccountUsers(providerId)).ToList(); if (message.ExplicitEmailAddresses != null && message.ExplicitEmailAddresses.Any()) { _logger.Info("Explicit recipients requested for email"); recipients = message.ExplicitEmailAddresses.ToList(); } else { recipients = accountUsers.Any(u => !u.IsSuperUser) ? accountUsers.Where(x => !x.IsSuperUser).Select(x => x.EmailAddress).ToList() : accountUsers.Select(x => x.EmailAddress).ToList(); } var optedOutList = accountUsers.Where(x => !x.ReceiveNotifications).Select(x => x.EmailAddress).ToList(); var finalRecipients = recipients.Where(x => !optedOutList.Any(y => x.Equals(y, StringComparison.CurrentCultureIgnoreCase))) .ToList(); var commands = finalRecipients.Select(x => new SendNotificationCommand { Email = CreateEmailForRecipient(x, message) }); await Task.WhenAll(commands.Select(x => _mediator.Send(x))); _logger.Info($"Sent email to {finalRecipients.Count} recipients for ukprn: {providerId}", providerId); }
public async Task <GetUserNotificationSettingsResponse> Handle(GetUserNotificationSettingsQuery message, CancellationToken cancellationToken) { var userSettings = (await _userRepository.GetUserSetting(message.UserRef)).ToList(); if (!userSettings.Any()) { _logger.Info($"No settings found for user {message.UserRef}"); await _userRepository.AddSettings(message.UserRef); userSettings = (await _userRepository.GetUserSetting(message.UserRef)).ToList(); _logger.Info($"Created default settings for user {message.UserRef}"); } return(new GetUserNotificationSettingsResponse { NotificationSettings = userSettings.Select( m => new UserNotificationSetting { UserRef = m.UserRef, ReceiveNotifications = m.ReceiveNotifications, }).ToList() }); }
public async Task <IHttpActionResult> GetAccountUsers(long ukprn) { _logger.Info($"Getting account users for ukprn: {ukprn}", providerId: ukprn); var result = await _orchestrator.GetAccountUsers(ukprn); _logger.Info($"Found {result.Count()} user accounts for ukprn: {ukprn}", providerId: ukprn); return(Ok(result)); }
public async Task <IHttpActionResult> GetUserSettings(string userRef) { _logger.Info($"Getting users settings for user: {userRef}"); var result = await _orchestrator.GetUser(userRef); _logger.Info($"Found {(result == null ? "0" : "1")} users settings for user: {userRef}"); return(Ok(result)); }
public async Task <DataLockMismatchViewModel> GetApprenticeshipMismatchDataLock(long providerId, string hashedApprenticeshipId) { var apprenticeshipId = _hashingService.DecodeValue(hashedApprenticeshipId); _logger.Info($"Getting apprenticeship datalock for provider: {providerId}", providerId: providerId, apprenticeshipId: apprenticeshipId); var datalockSummary = await _mediator.Send(new GetApprenticeshipDataLockSummaryQueryRequest { ProviderId = providerId, ApprenticeshipId = apprenticeshipId }); var data = await _mediator.Send(new GetApprenticeshipQueryRequest { ProviderId = providerId, ApprenticeshipId = apprenticeshipId }); var commitmentData = await _mediator.Send(new GetCommitmentQueryRequest { ProviderId = providerId, CommitmentId = data.Apprenticeship.CommitmentId }); var priceHistory = await _mediator.Send(new GetApprenticeshipPriceHistoryQueryRequest { ProviderId = providerId, ApprenticeshipId = apprenticeshipId }); var datalockSummaryViewModel = await _dataLockMapper.MapDataLockSummary(datalockSummary.DataLockSummary, data.Apprenticeship.HasHadDataLockSuccess); var dasRecordViewModel = _apprenticeshipMapper.MapApprenticeship(data.Apprenticeship, commitmentData.Commitment); var priceDataLocks = datalockSummaryViewModel .DataLockWithCourseMismatch .Concat(datalockSummaryViewModel.DataLockWithOnlyPriceMismatch) .Where(m => m.DataLockErrorCode.HasFlag(DataLockErrorCode.Dlock07)) .OrderBy(x => x.IlrEffectiveFromDate); return(new DataLockMismatchViewModel { ProviderId = providerId, HashedApprenticeshipId = hashedApprenticeshipId, DasApprenticeship = dasRecordViewModel, DataLockSummaryViewModel = datalockSummaryViewModel, EmployerName = data.Apprenticeship.LegalEntityName, PriceDataLocks = _dataLockMapper.MapPriceDataLock(priceHistory.History, priceDataLocks), CourseDataLocks = _dataLockMapper.MapCourseDataLock(dasRecordViewModel, datalockSummaryViewModel.DataLockWithCourseMismatch, data.Apprenticeship, priceHistory.History) }); }
public BulkUploadResult CreateViewModels(long providerId, CommitmentView commitment, string fileInput) { const string errorMessage = "Upload failed. Please check your file and try again."; using (var tr = new StringReader(fileInput)) { try { var csvReader = new CsvReader(tr); csvReader.Configuration.HasHeaderRecord = true; csvReader.Configuration.IsHeaderCaseSensitive = false; csvReader.Configuration.ThrowOnBadData = true; csvReader.Configuration.RegisterClassMap <CsvRecordMap>(); return(new BulkUploadResult { Data = csvReader.GetRecords <CsvRecord>() .ToList() .Select(record => MapTo(record, commitment)) }); } catch (CsvMissingFieldException) { _logger.Info("Failed to process bulk upload file (missing field).", providerId, commitment.Id); return(new BulkUploadResult { Errors = new List <UploadError> { new UploadError("Some mandatory fields are incomplete. Please check your file and upload again.") } }); } catch (Exception) { _logger.Info("Failed to process bulk upload file.", providerId, commitment.Id); return(new BulkUploadResult { Errors = new List <UploadError> { new UploadError(errorMessage) } }); } } }
public async Task <CommitmentView> GetCommitment(long providerId, long commitmentId) { Logger.Info($"Getting commitment:{commitmentId} for provider:{providerId}", providerId, commitmentId); var data = await Mediator.Send(new GetCommitmentQueryRequest { ProviderId = providerId, CommitmentId = commitmentId }); return(data.Commitment); }
public async Task SaveIdentityAttributes(string userId, long ukprn, string displayName, string email) { _logger.Info($"Updating \"{userId}\" attributes - ukprn:\"{ukprn}\", displayname:\"{displayName}\", email:\"{email}\""); await _mediator.Send(new UpsertRegisteredUserCommand { UserRef = userId, DisplayName = displayName, Ukprn = ukprn, Email = email }); }
public async Task <GetAccountUsersResponse> Handle(GetAccountUsersQuery request, CancellationToken cancellationToken) { if (request.Ukprn < 1) { throw new ValidationException($"Ukprn must be more than 0 when getting account users."); } var response = new GetAccountUsersResponse(); _logger.Info($"Getting users from repository for {request.Ukprn}", providerId: request.Ukprn); var providerUsers = await _userRepository.GetUsers(request.Ukprn); foreach (var user in providerUsers) { var settings = await _userSettingsRepository.GetUserSetting(user.UserRef); response.Add(user, settings.FirstOrDefault()); } _logger.Info($"Retrieved {providerUsers.Count()} users from repository for {request.Ukprn}", providerId: request.Ukprn); return(response); }
public async Task <IHttpActionResult> SendEmailToAllProviderRecipients(long ukprn, ProviderEmailRequest request) { try { await _emailOrchestrator.SendEmailToAllProviderRecipients(ukprn, request); _logger.Info($"Email template '{request?.TemplateId}' sent to Provider recipients successfully", ukprn); return(Ok()); } catch (Exception e) { _logger.Error(e, $"Error sending email template '{request?.TemplateId}' to Provider recipients", ukprn); throw; } }
public async Task <User> GetUser(string userRef) { var userSetting = await _mediator.Send(new GetUserNotificationSettingsQuery { UserRef = userRef }); var setting = userSetting.NotificationSettings.SingleOrDefault(); if (setting == null) { _logger.Info($"Unable to get user with ref {userRef}"); return(null); } return(new User { UserRef = setting.UserRef, ReceiveNotifications = setting.ReceiveNotifications }); }
public IHttpActionResult GetStatus() { _logger.Info("Called HealthCheck for Provider Account API"); return(Ok()); }
public async Task <BulkUploadResult> ValidateFileStructure(UploadApprenticeshipsViewModel uploadApprenticeshipsViewModel, long providerId, CommitmentView commitment) { if (uploadApprenticeshipsViewModel.Attachment == null) { return new BulkUploadResult { Errors = new List <UploadError> { new UploadError("No file chosen") } } } ; var fileContent = new StreamReader(uploadApprenticeshipsViewModel.Attachment.InputStream).ReadToEnd(); var fileName = uploadApprenticeshipsViewModel?.Attachment?.FileName ?? "<- NO NAME ->"; _logger.Trace($"Saving bulk upload file. {fileName}"); var bulkUploadId = await _mediator.Send( new SaveBulkUploadFileCommand { ProviderId = uploadApprenticeshipsViewModel.ProviderId, CommitmentId = commitment.Id, FileContent = fileContent, FileName = fileName }); _logger.Info($"Saved bulk upload with Id: {bulkUploadId}"); var fileAttributeErrors = _bulkUploadValidator.ValidateFileSize(uploadApprenticeshipsViewModel.Attachment).ToList(); if (fileAttributeErrors.Any()) { foreach (var error in fileAttributeErrors) { _logger.Warn($"File Structure Error --> {error.Message}", uploadApprenticeshipsViewModel.ProviderId, commitment.Id); } _logger.Info($"Failed validation bulk upload file with {fileAttributeErrors.Count} errors", uploadApprenticeshipsViewModel.ProviderId, commitment.Id); return(new BulkUploadResult { Errors = fileAttributeErrors }); } var uploadResult = _fileParser.CreateViewModels(providerId, commitment, fileContent); if (uploadResult.HasErrors) { return(uploadResult); } var errors = _bulkUploadValidator.ValidateCohortReference(uploadResult.Data, uploadApprenticeshipsViewModel.HashedCommitmentId).ToList(); errors.AddRange(_bulkUploadValidator.ValidateUlnUniqueness(uploadResult.Data).ToList()); return(new BulkUploadResult { Errors = errors, Data = uploadResult.Data, BulkUploadId = bulkUploadId }); }