public async Task <IActionResult> PostAsync([FromBody] UsersPost model) { if (await cachedUserManager.GetUserByUserNameAndFilterRoleAssignmentsByClientIdAsync(model.UserName, userPrincipalBuilder.GetCurrentClientId()) != null) { throw new UserAlreadyExistsException(); } if (await userManager.Users.FirstOrDefaultAsync(u => u.NormalizedEmail == model.Email.Trim().ToUpper()) != null) { throw new EmailAlreadyExistsException(); } if (!hiringTypes.Contains(model.HiringType)) { throw new InvalidHiringTypeException(); } var user = mapper.Map <UsersPost, ApplicationUser>(model); user.EmailConfirmed = !model.GeneratePassword && string.IsNullOrWhiteSpace(model.Password); var password = model.GeneratePassword ? passwordGenerator.GenerateRandomPassword() : model.Password; var creationResult = !string.IsNullOrWhiteSpace(password) ? await userManager.CreateAsync(user, password) : await userManager.CreateAsync(user); if (creationResult.Succeeded) { if (!user.EmailConfirmed) { var token = await userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.RouteUrl("ConfirmEmail", new { username = user.UserName, token }, Request.Scheme); await emailSender.NotifyNewUserAsync(model.Email, model.UserName, callbackUrl, model.GeneratePassword?password : null); } return(CreatedAtRoute("UsersGet", new { username = user.UserName }, new PostResult(user.Id, user.UserName))); } else { throw new IdentityOperationException(creationResult.Errors.Select(e => new IdentityOperationExceptionItem(e.Code, e.Description))); } }
public void ResetPassword(User user) { if (user == null) { throw new ArgumentException("User is null", "user"); } try { _userRepository.StartTransaction(); var newPassword = _passwordGenerator.GenerateRandomPassword(); user.PasswordHash = _passwordCryptography.GenerateHash(newPassword); _userRepository.UpdateUser(user); _userRepository.Commit(); _mailSender.SendEmail(user.Email, CreateNewPasswordBody(newPassword), "New Password"); } catch (Exception e) { _userRepository.Rollback(); _log.LogError("Error in password reset", e); } }