/// <summary> /// Deletes an entity in MongDB. /// </summary> /// <author>Anna Krebs</author> /// <param name="id"></param> public async Task <ValidationResultList> DeleteAsync(string id) { var validationResult = new ValidationResultList(); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { // Create filter, that filters for ObjectId in MongoDB. var idFilter = MongoHelper.GetFilter <TEntity>(Constants._id, new ObjectId(id)); // Delete the entry with the appropriate MongoDB id. var deleteResult = await _collection.DeleteOneAsync(idFilter); if (deleteResult.DeletedCount == 0) { // Add error to validation result, if entity wasn't deleted. Log.Error($"No entity with id {id} was deleted."); validationResult.Errors.Add(typeof(TEntity).Name, string.Format(Resources.Resources.Error_NoEntityWithIdDeleted, id)); } ts.Complete(); Log.Info($"Deleted {deleteResult.DeletedCount} entity with {id} in database."); } return(validationResult); }
/// <summary> /// Resets the password of the user, after he requested a reset after ForgotPassword. /// </summary> /// <author>Anna Krebs</author> /// <seealso>adesso SzkB.Ehypo project</seealso> /// <param name="email"></param> /// <param name="password"></param> /// <param name="passwordResetKey"></param> /// <returns></returns> public async Task <ValidationResultList> ResetPasswordAsync(string email, string password, Guid passwordResetKey) { var validationResult = new ValidationResultList(); var users = await Repository.GetByFilterAsync(new UserFilter { Email = email }); var user = users.SingleOrDefault(); if (user == null) { validationResult.Errors.Add(Constants.Email, Resources.Resources.Error_NoUserWithEmail); return(validationResult); } // Exception, if reset key was not found in database. if (user.PasswordResetKey != passwordResetKey) { Log.Error($"Password for email {email} cannot be reset using key {passwordResetKey}"); throw new InvalidOperationException( $"Password for email {email} cannot be reset using key {passwordResetKey}"); } var hashedPassword = _cryptoService.GeneratePasswordHash(password); user.PasswordHash = hashedPassword; user.PasswordResetKey = null; validationResult = await Repository.UpdateAsync(user); Log.Info( $"ResetPasswordAsync for email {email}. Validation Result has errors: {validationResult?.HasErrors}"); return(validationResult); }
/// <summary> /// Inserts an entity in MongDB. /// </summary> /// <author>Anna Krebs</author> /// <param name="entity"></param> public async Task <ValidationResultList> InsertAsync(TEntity entity) { var validationResult = new ValidationResultList(); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { // Check, if entry already exists in database. var isDuplicate = await MongoHelper <TEntity> .IsDuplicate(entity.GetPrimaryName(), entity.GetPrimaryValue(), _collection, null); // If entity doesn't exist, insert in database. if (!isDuplicate) { await _collection.InsertOneAsync(entity); } else { validationResult.Errors.Add(typeof(TEntity).Name, Resources.Resources.Error_EntityAlreadyExists); } ts.Complete(); Log.Info($"Inserted {entity} with id {entity.ObjectId} in database."); } return(validationResult); }
public ValidationResultList Validate(ValidationOptions options) { var list = new ValidationResultList(); foreach (var form in Steps.Select(s => s.Form)) { var validationResult = form.Validate(new ValidationOptions { ValidateFiles = options.ValidateFiles, ValidateCaptcha = false }); list.AddRange(validationResult); } if (options.ValidateCaptcha && RequiresCaptcha) { var requiresCaptchaAttr = new RequiresCaptchaAttribute(); var form = new HttpContextWrapper(HttpContext.Current); requiresCaptchaAttr.Validate(form, list); } return(list); }
/// <summary> /// Changes password. /// </summary> /// <author>Anna Krebs</author> /// <seealso>adesso SzkB.Ehypo project</seealso> /// <param name="email"></param> /// <param name="oldPassword"></param> /// <param name="newPassword"></param> /// <returns></returns> public async Task <ValidationResultList> ChangePasswordAsync(string email, string oldPassword, string newPassword) { var validationResult = new ValidationResultList(); var users = await Repository.GetByFilterAsync(new UserFilter { Email = email }); var user = users.SingleOrDefault(); if (user == null) { validationResult.Errors.Add(Constants.Email, Resources.Resources.Error_NoUserWithEmail); return(validationResult); } if (!_cryptoService.ValidatePassword(oldPassword, user.PasswordHash)) { validationResult.Errors.Add(Constants.Password, Resources.Resources.Error_OldPasswordInvalid); return(validationResult); } // Generate new password & update user. var hashedPassword = _cryptoService.GeneratePasswordHash(newPassword); user.PasswordHash = hashedPassword; validationResult = await Repository.UpdateAsync(user); Log.Info( $"ChangePasswordAsync for email {user.Email}. Validation Result has errors: {validationResult?.HasErrors}"); return(validationResult); }
/// <summary> /// Prepares and sends the email, that is sent to the new registered user in order to verify his account. /// </summary> /// <author>Anna Krebs</author> /// <param name="existingUser"></param> /// <param name="user"></param> /// <returns></returns> private async Task <ValidationResultList> PrepareAndSendConfirmUserEmail(User existingUser, User user) { var validationResult = new ValidationResultList(); // User is changed from not confirmed to confirmed by admin. var isUserConfirmation = !existingUser.IsConfirmed && user.IsConfirmed; // Send email to user, if admin confirmed the user. if (isUserConfirmation) { // Get url from user mail. var loginUrl = Url.Action("Login", "Account", new { email = user.Email }); var loginUrlFull = Url.Action("Login", "Account", new { email = user.Email }, Request?.Scheme) ?? loginUrl; Log.Info($"loginUrlFull is {loginUrlFull}"); if (loginUrlFull != null) { validationResult = await _userService.GenerateAndSendMailForUserAsync(user, new Uri(loginUrlFull), Constants.InfoAboutRegistrationConfirmationSubject, Constants.InfoAboutRegistrationConfirmationText); } } return(validationResult); }
public async Task <EventBusinessResponseVO> ProcessEvent(DeviceEventDTO dvcEvtDTO) { int value; string valueType = string.Empty; int.TryParse(dvcEvtDTO.Valor, out value); if (value != 0) { valueType = "INT"; } else { valueType = "STR"; } ValidationResultList validatonResultList = _validator.Validate(dvcEvtDTO); //Seria mais elegante ter feito por filters, mas fiz assim para deixar explicito o processo if (validatonResultList.items.Count > 0) { return(new EventBusinessResponseVO("error", "The request provided contain errors", DeviceEventBusinessStatusResponse.ERROR, validatonResultList)); } DeviceEvent dvcEvt = DeviceEvent.CreateFromDTOParameters(dvcEvtDTO.Timestamp, dvcEvtDTO.Tag, dvcEvtDTO.Valor, valueType); await _dvcEvtRepository.Add(dvcEvt); return(new EventBusinessResponseVO("success", "The request was processed successfully", DeviceEventBusinessStatusResponse.SUCCESS, validatonResultList)); }
public async Task <ActionResult> AssignMolecule(AssignMoleculeViewModel model, IList <AssignValueViewModel> assignValueViewModels) { var validationResult = new ValidationResultList(); model.AssignMolecules = assignValueViewModels; if (ModelState.IsValid) { try { if (assignValueViewModels == null || string.IsNullOrEmpty(model.EssentialOilId)) { Log.Error("AssignMolecule. An unexpected error occurred. Value is null."); throw new ArgumentNullException(Resources.Resources.Error_UnexpectedError); } // Delete all assigned molecules from database in order to update. validationResult = await _essentialOilMoleculeService.DeleteAssignedMoleculesAsync(model.EssentialOilId); // Insert assigned molecules if deletion was successful. if (!validationResult.HasErrors) { foreach (var assignValueViewModel in assignValueViewModels) { // Insert the assigned molecules in database. validationResult = await AssignMoleculeToEssentialOil(model, assignValueViewModel); } } } catch (Exception e) { Log.Error($"AssignMolecule. An unexpected error occurred while inserting or editing: {e}"); throw; } } // Show validation result, if validation error occurred while // inserting or if ModelState is invalid. if (validationResult.HasErrors || !ModelState.IsValid) { AddGeneralModelStateError(validationResult); AddValidationResultsToModelStateErrors(validationResult.Errors); // Set substances to display in list. var substances = await _substanceService.GetAllAsync(new SubstanceFilter()); model.Substances = substances; Log.Info("Show AssignMolecule"); return(View(nameof(AssignMolecule), model)); } Log.Info("Redirect to AssignEffect"); return(RedirectToAction(nameof(AssignEffect), new { id = model.EssentialOilId })); }
/// <summary> /// Sends email with the configured parameters. /// </summary> /// <param name="email"></param> /// <param name="isValidationErrorVisibleForAdmin"></param> /// <seealso>adesso SzkB.Ehypo project</seealso> /// <returns></returns> public async Task <ValidationResultList> SendEmailAsync(Email email, bool isValidationErrorVisibleForAdmin) { var validationResult = new ValidationResultList(); // Read Email settings from Configuration collection in database. var smtpServer = await _configurationService.GetConfigurationParameterByKeyAsync(Constants.SmtpServer); var smtpPort = Convert.ToInt32(await _configurationService.GetConfigurationParameterByKeyAsync(Constants.SmtpPort)); var smtpEnableSsl = Convert.ToBoolean( await _configurationService.GetConfigurationParameterByKeyAsync(Constants.SmtpEnableSsl)); var smtpEmailUser = await _configurationService.GetConfigurationParameterByKeyAsync(Constants.SmtpEmailUser); var smtpEmailUserPassword = await _configurationService.GetConfigurationParameterByKeyAsync(Constants.SmtpEmailUserPassword); var smtpEmailFrom = await _configurationService.GetConfigurationParameterByKeyAsync(Constants.SmtpEmailFrom); // Setup the smtp client with the given configuration. using (var client = new SmtpClient(smtpServer, smtpPort) { Credentials = new NetworkCredential(smtpEmailUser, smtpEmailUserPassword), EnableSsl = smtpEnableSsl }) { try { using (var message = new MailMessage(smtpEmailFrom, email.EmailAddress)) { message.Body = email.EmailHtmlText; message.IsBodyHtml = true; message.SubjectEncoding = Encoding.UTF8; message.Subject = email.Subject; // Send the email. await client.SendMailAsync(message); Log.Info( $"SendEmailAsync was successful. E-Mail with subject {email.Subject} was sent to user {email.User}"); } } catch (Exception ex) { Log.Error($"SendEmailAsync failed. Exception Message: {ex.Message}"); // Show text "contact admin" according to whether the validation message is shown for the user or the admin. var contactAdminText = !isValidationErrorVisibleForAdmin ? Resources.Resources.Error_ContactAdmin : string.Empty; validationResult.Errors.Add(Constants.SendEmailValidationError, $"{Resources.Resources.Error_SendingEmailFailed} {contactAdminText}"); } return(validationResult); } }
public void AddValidationResults(IEnumerable <ICommandValidationResult> validationResults) { if (validationResults == null) { return; } ValidationResultList.AddRange(validationResults); }
/// <summary> /// Get ModelState errors and add them to the ValidationResult as an error in order to display the error at the top of /// the page. /// </summary> /// <author>Anna Krebs</author> /// <param name="validationResult"></param> private void AddGeneralModelStateError(ValidationResultList validationResult) { var modelStateErrors = ModelState.Values.Where(m => m.Errors.Count != 0).ToList(); if (!validationResult.HasErrors && modelStateErrors.Any()) { validationResult.Errors.Add(string.Empty, Resources.Resources.Error_NotValidMoleculePercentage); } }
public async Task <ActionResult> CreateOrEdit(EssentialOilViewModel model, IFormFile uploadFile) { ValidationResultList validationResult = new ValidationResultList(); EssentialOil essentialOil = new EssentialOil(); if (ModelState.IsValid) { try { if (uploadFile?.Length > 0) { // Get file name & base 64 string for picture. essentialOil.PictureFileName = Path.GetFileName(uploadFile.FileName); essentialOil.PictureDataAsString = await _conversionHelper.ResizeAndGenerateBase64StringForPicture(uploadFile); } // Map view model to entity. model.MapViewModelToEntity(essentialOil); // Edit or create if (essentialOil.Id != null) { // Edit // Only update if essential oil name doesn't already exist. validationResult = await _essentialOilService.UpdateAsync(essentialOil); } else { // Create // Only insert if essential oil name doesn't already exist. validationResult = await _essentialOilService.InsertAsync(essentialOil); } } catch (Exception e) { Log.Error($"CreateOrEdit. An unexpected error occurred while inserting or editing: {e}"); throw new ArgumentException(Resources.Resources.Error_UnexpectedError); } } // Show validation result, if validation error occurred while // inserting or if ModelState is invalid. if (validationResult.HasErrors || !ModelState.IsValid) { AddValidationResultsToModelStateErrors(validationResult.Errors); Log.Info("Show CreateOrEdit"); return(View(nameof(CreateOrEdit), model)); } // If form is valid, navigate to AssignMolecule. Log.Info("Redirect to AssignMolecule"); return(RedirectToAction(nameof(AssignMolecule), new { id = model.Id })); }
public async Task <ActionResult> CreateOrEdit(MoleculeViewModel model) { var validationResult = new ValidationResultList(); if (ModelState.IsValid) { try { var molecule = new Molecule(); // Map view model to entity. model.MapViewModelToEntity(molecule); // Edit or create if (molecule.Id != null) { // Edit // Only update if molecule name doesn't already exist. validationResult = await _moleculeService.UpdateAsync(molecule); } else { // Create // Only insert if molecule name doesn't already exist. validationResult = await _moleculeService.InsertAsync(molecule); model.Id = molecule.Id; } } catch (Exception e) { Log.Error($"An unexpected error occurred while inserting or editing: {e}"); throw new ArgumentException(Resources.Resources.Error_UnexpectedError); } } // Show validation result, if validation error occurred while // inserting or if ModelState is invalid. if (validationResult.HasErrors || !ModelState.IsValid) { AddValidationResultsToModelStateErrors(validationResult.Errors); // Set substances to display in drop down. var substances = await _substanceService.GetAllAsync(new SubstanceFilter()); model.Substances = substances; Log.Info("Show CreateOrEdit"); return(View(nameof(CreateOrEdit), model)); } Log.Info("Redirect to Index"); return(RedirectToAction(nameof(Index), new { lastEditedMoleculeId = model.Id })); }
public override void Validate(HttpContextBase ctx, ValidationResultList validationMessages) { var encryptedValue = ctx.Request.Form[HiddenFieldName]; var postedValue = ctx.Request.Form[InputFieldName]; var isValid = Captcha.Decrypt(encryptedValue, out _, out var value) && value == postedValue; if (!isValid) { validationMessages.Add(InputFieldName, Localization.T("Captcha.CompositeC1.Error")); } }
/// <summary> /// Remains in same view if form not valid and adds validation error. /// </summary> /// <author>Anna Krebs</author> /// <param name="model"></param> /// <param name="validationResult"></param> /// <param name="errorMessage"></param> /// <param name="viewName"></param> /// <returns></returns> private ActionResult RemainInSameViewAndShowValidationError(LoginViewModel model, ValidationResultList validationResult, string errorMessage, string viewName) { // Stay in view if ModelState is invalid, redisplay form. Log.Info("ModelState is invalid."); validationResult.Errors.Add(string.Empty, errorMessage); AddValidationResultsToModelStateErrors(validationResult.Errors); // Stay in same view if validation failed. Log.Info($"Show {viewName}"); return(View(viewName, model)); }
public ValidationResultList Validate(ValidationOptions options) { var validationList = new ValidationResultList(); if (SubmittedValues == null || SubmittedValues.AllKeys.Length == 0) { return(validationList); } if (Model.OnValidateHandler != null) { var e = new FormValidationEventArgs(SubmittedValues); Model.OnValidateHandler(this, e); if (e.Cancel) { return(validationList); } } EnsureRulesList(); foreach (var kvp in _ruleList) { if (!options.ValidateFiles) { var valueType = kvp.Key.ValueType; if (valueType == typeof(FormFile) || valueType == typeof(IEnumerable <FormFile>)) { continue; } } var result = ValidationResultList.GetFormValidationResult(kvp.Value, false); validationList.AddRange(result); } if (options.ValidateCaptcha) { var requiresCaptchaAttr = Attributes.OfType <RequiresCaptchaAttribute>().SingleOrDefault(); if (requiresCaptchaAttr != null) { var form = new HttpContextWrapper(HttpContext.Current); requiresCaptchaAttr.Validate(form, validationList); } } return(validationList); }
public async Task <ActionResult> AssignEssentialOil(AssignEssentialOilEffectViewModel model, IList <AssignValueViewModel> assignValueViewModels) { var validationResult = new ValidationResultList(); model.AssignEffects = assignValueViewModels; if (ModelState.IsValid) { try { if (assignValueViewModels == null || string.IsNullOrEmpty(model.EffectId)) { Log.Error("AssignEffect. An unexpected error occurred. Value is null."); throw new ArgumentNullException("An unexpected error occurred. Value is null."); } // Delete all assigned essential oils from database in order to update. validationResult = await _essentialOilEffectService.DeleteAssignedEssentialOilsAsync(model.EffectId); // Insert assigned effects if deletion was successful. if (!validationResult.HasErrors) { foreach (var assignValueViewModel in assignValueViewModels) { // Insert the assigned effects in database. validationResult = await AssignEssentialOilToEffect(model, assignValueViewModel); } } } catch (Exception e) { Log.Error($"AssignEffect. An unexpected error occurred while inserting or editing: {e}"); throw new ArgumentException(Resources.Resources.Error_UnexpectedError); } } // Show validation result, if validation error occurred while // inserting or if ModelState is invalid. if (validationResult.HasErrors || !ModelState.IsValid) { AddValidationResultsToModelStateErrors(validationResult.Errors); Log.Info("Show AssignEssentialOil"); return(View(nameof(AssignEssentialOil), model)); } Log.Info("Redirect to Index"); return(RedirectToAction(nameof(Index), new { lastEditedEffectId = model.EffectId })); }
public async Task <ActionResult> CreateOrEdit(EffectViewModel model) { var validationResult = new ValidationResultList(); var effect = new Effect(); if (ModelState.IsValid) { try { // Map view model to entity. model.MapViewModelToEntity(effect); // Edit or create if (effect.Id != null) { validationResult = await _effectService.UpdateAsync(effect); } else { validationResult = await _effectService.InsertAsync(effect); } } catch (Exception e) { Log.Error($"An unexpected error occurred while inserting or editing: {e}"); throw new ArgumentException(Resources.Resources.Error_UnexpectedError); } } // Show validation result, if validation error occurred while // inserting or if ModelState is invalid. if (validationResult.HasErrors || !ModelState.IsValid) { AddValidationResultsToModelStateErrors(validationResult.Errors); // Set categories to display in drop down. var categories = await _categoryService.GetAllAsync(new CategoryFilter()); model.Categories = categories; Log.Info("Show CreateOrEdit"); return(View(nameof(CreateOrEdit), model)); } // If form is valid, navigate to AssignMolecule. Log.Info("Redirect to AssignMolecule"); return(RedirectToAction(nameof(AssignMolecule), new { id = effect.Id })); }
/// <summary> /// Deletes all assigned molecules for specific essential oil from database. /// </summary> /// <author>Anna Krebs</author> /// <param name="essentialOilId"></param> /// <returns></returns> public async Task <ValidationResultList> DeleteAssignedMoleculesAsync(string essentialOilId) { var validationResult = new ValidationResultList(); var essentialOilMolecules = await _essentialOilMoleculeRepository.GetAllAsync(new EssentialOilMoleculeFilter { EssentialOilId = essentialOilId }); foreach (var essentialOilMolecule in essentialOilMolecules) { validationResult = await _essentialOilMoleculeRepository.DeleteAsync(essentialOilMolecule.Id); Log.Info( $"Delete assigned molecule with id {essentialOilMolecule.MoleculeId} for essential oil with id {essentialOilMolecule.EssentialOilId}"); } return(validationResult); }
/// <summary> /// Deletes all assigned molecules for specific effect from database. /// </summary> /// <author>Anna Krebs</author> /// <param name="effectId"></param> /// <returns></returns> public async Task <ValidationResultList> DeleteAssignedMoleculesAsync(string effectId) { var validationResult = new ValidationResultList(); var effectMolecules = await _effectMoleculeRepository.GetAllAsync(new EffectMoleculeFilter { EffectId = effectId }); foreach (var effectMolecule in effectMolecules) { validationResult = await _effectMoleculeRepository.DeleteAsync(effectMolecule.Id); Log.Info( $"Delete assigned molecule with id {effectMolecule.MoleculeId} for effect with id {effectMolecule.EffectId}"); } return(validationResult); }
/// <summary> /// Deletes all assigned effects for specific essential oil from database. /// </summary> /// <author>Anna Krebs</author> /// <param name="essentialOilId"></param> /// <returns></returns> public async Task <ValidationResultList> DeleteAssignedEffectsAsync(string essentialOilId) { var validationResult = new ValidationResultList(); var essentialOilEffects = await _essentialOilEffectRepository.GetAllAsync(new EssentialOilEffectFilter { EssentialOilId = essentialOilId }); foreach (var essentialOilEffect in essentialOilEffects) { validationResult = await _essentialOilEffectRepository.DeleteAsync(essentialOilEffect.Id); Log.Info( $"Delete assigned effect with id {essentialOilEffect.EffectId} for essential oil with id {essentialOilEffect.EssentialOilId}"); } return(validationResult); }
public bool IsValid(IEnumerable <string> fieldNames) { EnsureRulesList(); foreach (var fieldName in fieldNames) { var field = Fields.Single(f => f.Name == fieldName); var result = ValidationResultList.GetFormValidationResult(_ruleList[field], true); if (result.Any(r => r.AffectedFormIds.Contains(fieldName))) { return(false); } } return(true); }
public override void Validate(HttpContextBase ctx, ValidationResultList validationMessages) { var response = ctx.Request.Form[HiddenFieldName]; var ip = ctx.Request.UserHostAddress; var url = $"{SiteVerifyUrl}?secret={_secret}&remoteip={ip}&v={Version}&response={response}"; using (var client = new HttpClient()) { var resultString = client.GetStringAsync(url).Result; var result = JsonConvert.DeserializeObject <Response>(resultString); if (!result.Success) { validationMessages.Add(InputFieldName, String.Join(", ", result.ErrorCodes)); } } }
/// <summary> /// Generates a PasswordResetKey, which is sent to user in order to change his password, when forgotten. /// </summary> /// <author>Anna Krebs</author> /// <seealso>adesso SzkB.Ehypo project</seealso> /// <param name="email"></param> /// <returns></returns> public async Task <ValidationResultList> GenerateAndUpdatePasswordResetKeyAsync(string email) { var validationResult = new ValidationResultList(); var users = await Repository.GetByFilterAsync(new UserFilter { Email = email }); var user = users.SingleOrDefault(); if (user == null) { validationResult.Errors.Add(Constants.Email, Resources.Resources.Error_NoUserWithEmail); return(validationResult); } user.PasswordResetKey = Guid.NewGuid(); return(await Repository.UpdateAsync(user)); }
public async Task <ActionResult> Edit(ConfigurationViewModel model) { var validationResult = new ValidationResultList(); if (ModelState.IsValid) { try { var configuration = new Configuration(); // Map view model to entity. model.MapViewModelToEntity(configuration); if (configuration.Id == null) { Log.Error("An unexpected error occurred while getting id. No entity could be found."); throw new ArgumentNullException(string.Format(Resources.Resources.Error_UnexpectedError)); } // Only update if molecule name doesn't already exist. validationResult = await _configurationService.UpdateAsync(configuration); } catch (Exception e) { Log.Error($"An unexpected error occurred while editing: {e}"); throw new ArgumentException(Resources.Resources.Error_UnexpectedError); } } // Show validation result, if validation error occurred while // updating or if ModelState is invalid. if (validationResult.HasErrors || !ModelState.IsValid) { AddValidationResultsToModelStateErrors(validationResult.Errors); Log.Info("Show Edit"); return(View(nameof(Edit), model)); } Log.Info("Redirect to Index"); return(RedirectToAction(nameof(Index))); }
public ValidationResultList Validate(DeviceEventDTO dvcEvtDTO) { ValidationResultList error = new ValidationResultList(); if (dvcEvtDTO.Timestamp <= 0) { error.items.Add(new ValidationResult(false, "Invalid value provided for Timestamp")); } if (string.IsNullOrWhiteSpace(dvcEvtDTO.Tag)) { error.items.Add(new ValidationResult(false, "Tag cannot be empty")); } else if (dvcEvtDTO.Tag.Length < 0 && dvcEvtDTO.Tag.Length > 250) { error.items.Add(new ValidationResult(false, "Tag must be between 0 and 250 characters in size")); } return(error); }
/// <summary> /// Updates an entity in MongDB. /// </summary> /// <author>Anna Krebs</author> /// <param name="entity"></param> /// <returns></returns> public async Task <ValidationResultList> UpdateAsync(TEntity entity) { var validationResult = new ValidationResultList(); using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { // Create filter, that filters for ObjectId in MongoDB. var idFilter = MongoHelper.GetFilter <TEntity>(Constants._id, new ObjectId(entity.Id)); // Check, if entry already exists in database. var isDuplicate = await MongoHelper <TEntity> .IsDuplicate(entity.GetPrimaryName(), entity.GetPrimaryValue(), _collection, entity.ObjectId); ReplaceOneResult replaceResult = null; // If changed entity doesn't exist, update in database. if (!isDuplicate) { // Update the entry with the appropriate MongoDB id. replaceResult = await _collection.ReplaceOneAsync(idFilter, entity); if (replaceResult.MatchedCount == 0) { // Add error to validation result, if entity wasn't found. Log.Error($"No entity with id {entity.Id} was found."); validationResult.Errors.Add(typeof(TEntity).Name, string.Format(Resources.Resources.Error_NoEntityWithIdFound, entity.Id)); } } else { // Add error to validation result, if entity already exists. validationResult.Errors.Add(typeof(TEntity).Name, Resources.Resources.Error_EntityAlreadyExists); } ts.Complete(); Log.Info($"Updated {replaceResult?.ModifiedCount ?? 0} entity with {entity.Id} in database."); } return(validationResult); }
/// <summary> /// Prepares and sends the email, that is sent to the user in order to reset his password. /// </summary> /// <author>Anna Krebs</author> /// <param name="user"></param> /// <returns></returns> private async Task <ValidationResultList> PrepareAndSendResetPasswordEmail(User user) { var validationResult = new ValidationResultList(); // Get url from user mail & password reset key. var passwordResetPath = Url.Action("ResetPassword", "Account", new { email = user.Email, passwordResetKey = user.PasswordResetKey }); var passwordResetUrlFull = Url.Action("ResetPassword", "Account", new { email = user.Email, passwordResetKey = user.PasswordResetKey }, Request?.Scheme) ?? passwordResetPath; Log.Info($"passwordResetUrlFull is {passwordResetUrlFull}"); if (passwordResetUrlFull != null) { validationResult = await _userService.GenerateAndSendMailForUserAsync(user, new Uri(passwordResetUrlFull), Constants.ForgotPasswordEmailSubject, Constants.ForgotPasswordEmailText); } return(validationResult); }
/// <summary> /// Prepares and sends the email, that is sent to the new registered user in order to verify his account. /// </summary> /// <author>Anna Krebs</author> /// <param name="user"></param> /// <returns></returns> private async Task <ValidationResultList> PrepareAndSendVerifyAccountEmail(User user) { var validationResult = new ValidationResultList(); // Get url from user mail & confirmation key. var verifyAccountUrl = Url.Action("VerifyAccount", "Account", new { email = user.Email, verifyAccountKey = user.VerifyAccountKey }); var verifyAccountUrlFull = Url.Action("VerifyAccount", "Account", new { email = user.Email, verifyAccountKey = user.VerifyAccountKey }, Request?.Scheme) ?? verifyAccountUrl; Log.Info($"verifyAccountUrlFull is {verifyAccountUrlFull}"); if (verifyAccountUrlFull != null) { validationResult = await _userService.GenerateAndSendMailForUserAsync(user, new Uri(verifyAccountUrlFull), Constants.VerifyAccountEmailSubject, Constants.VerifyAccountEmailText); } return(validationResult); }
/// <summary> /// Register new account in database. /// </summary> /// <author>Anna Krebs</author> /// <seealso>adesso SzkB.Ehypo project</seealso> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public async Task <ValidationResultList> RegisterAccountAsync(User user, string password) { var validationResult = new ValidationResultList(); var userExisting = await _userRepository.GetByFilterAsync(new UserFilter { Email = user.Email }); // Check if user with same email already exists. if (userExisting.Any()) { // User already exist. validationResult.Errors.Add(string.Empty, Resources.Resources.Error_UserAllreadyRegistered); } else { // Create new user with hashed password. user.PasswordHash = _cryptoService.GeneratePasswordHash(password); validationResult = await Repository.InsertAsync(user); } Log.Info( $"RegisterAccountAsync for email {user.Email}. Validation Result has errors: {validationResult.HasErrors}"); return(validationResult); }