예제 #1
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            var user = await _processor.FindByEmailAsync(model.Email);

            if (user == null)
            {
                // don't reveal to the user that the e-mail address is not registered
                return(Ok());
            }

            try
            {
                var result = await _processor.ResetPassword(model);

                IHttpActionResult errorResult = GetErrorResult(result);

                if (!result.Succeeded)
                {
                    return(BadRequest());
                }
            }
            catch (DbEntityValidationException ex)
            {
                TraceErrors(ex);
            }

            return(Ok());
        }
예제 #2
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = UserManager.FindByEmail(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("model.Email", "User not found for this email address");
                return(BadRequest(ModelState));
            }

            var result = await UserManager.RemovePasswordAsync(user.Id);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            result = await UserManager.AddPasswordAsync(user.Id, model.NewPassword);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
예제 #3
0
 public async Task <IActionResult> ChangePassword(ResetPasswordBindingModel model)
 {
     if (!ModelState.IsValid)
     {
         this.TempData.Put(MessagesConstants.TempDataMessageKey, new MessageModel()
         {
             Message = ErrorMessages.Models.InvalidModelStateMessage,
             Type    = MessageType.Danger
         });
         return(View(model));
     }
     if (!await this.usersService.ChangePasswordAsync(model))
     {
         this.TempData.Put(MessagesConstants.TempDataMessageKey, new MessageModel()
         {
             Message = InfoMessages.UnableToChangeUserPassword,
             Type    = MessageType.Warning
         });
         return(RedirectToPage("/Users/All", new { area = AreasConstants.AreaNames.Administrator }));
     }
     this.TempData.Put(MessagesConstants.TempDataMessageKey, new MessageModel()
     {
         Message = SuccessMessages.ChangedUserPassword,
         Type    = MessageType.Success
     });
     return(RedirectToPage("/Users/All", new { area = AreasConstants.AreaNames.Administrator }));
 }
예제 #4
0
        public ActionResult ResetPassword(ResetPasswordBindingModel formData)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var email           = formData.Email;
            var password        = formData.Password;
            var confirmPassword = formData.ConfirmPassword;
            var code            = formData.Code;

            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("email", email));
            parameters.Add(new KeyValuePair <string, string>("password", password));
            parameters.Add(new KeyValuePair <string, string>("confirmPassword", confirmPassword));
            parameters.Add(new KeyValuePair <string, string>("code", code));
            var response = RequestHelper.SendGetRequest(parameters, "Account"
                                                        , nameof(AccountController.ResetPassword), null);

            if (response.IsSuccessStatusCode)
            {
                return(View("ResetPasswordConfirmation"));
            }

            if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
            {
                return(View("Error"));
            }

            DealBadRequest(response);

            return(View());
        }
예제 #5
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    ModelState.AddModelError("", "No user found.");
                    return(BadRequest(ModelState));
                }

                IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

                if (result.Succeeded)
                {
                    return(Ok());
                }

                IHttpActionResult errorResult = GetErrorResult(result);

                if (errorResult != null)
                {
                    return(errorResult);
                }
            }
            return(BadRequest(ModelState));
        }
예제 #6
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            string message = "Error ResetPassword.";

            if (!ModelState.IsValid)
            {
                // Don't reveal that the user does not exist
                return(BadRequest(message));
            }

            var user = await _appUserManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(BadRequest(message));
            }

            var result = await _appUserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(Ok(new JsonResponse {
                    Success = true, Message = "Your password has been reset."
                }));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }

            return(BadRequest(ModelState));
        }
        public async Task <IHttpActionResult> ResetPassword([FromBody] ResetPasswordBindingModel resetPasswordModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            ApplicationUser user = await this.UserManager.FindByNameAsync(resetPasswordModel.Email);

            if (user == null)
            {
                return(this.BadRequest("User with email: " + resetPasswordModel.Email + " is not found!"));
            }

            if (string.IsNullOrEmpty(user.PasswordHash))
            {
                return(this.BadRequest("The user with email: " + resetPasswordModel.Email + "does not have local login!"));
            }

            this.UserManager.SetUserTokenProvider("ForgottenPassword");
            IdentityResult resetPasswordResult = await this.UserManager.ResetPasswordAsync(user.Id, resetPasswordModel.Token, resetPasswordModel.NewPassword);

            IHttpActionResult errorResult = GetErrorResult(resetPasswordResult);

            if (errorResult != null)
            {
                return(errorResult);
            }

            return(this.Ok());
        }
예제 #8
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    // Don't reveal that the user does not exist
                    return(Ok());
                }

                var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

                if (result.Succeeded)
                {
                    return(Ok());
                }
                else
                {
                    ModelState.AddModelError("InvalidToken", result.Errors.FirstOrDefault());
                }
            }

            return(BadRequest(ModelState));
        }
예제 #9
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (this.ModelState.IsValid)
            {
                var user = await this.UserManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    this.ModelState.AddModelError("", "No user found.");
                    return(this.BadRequest(this.ModelState));
                }
                var result = await this.UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

                if (result.Succeeded)
                {
                    return(this.Ok());
                }
                var errorResult = this.GetErrorResult(result);

                if (errorResult != null)
                {
                    return(errorResult);
                }
            }

            // If we got this far, something failed
            return(this.BadRequest(this.ModelState));
        }
예제 #10
0
        public async Task <IActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(model));
            }
            var user = await this.userManager
                       .FindByEmailAsync(model.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(this.RedirectToAction(nameof(this.ResetPasswordConfirmation)));
            }

            var result = await this.userManager
                         .ResetPasswordAsync(user, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(this.RedirectToAction(nameof(this.ResetPasswordConfirmation)));
            }

            this.AddErrors(result);

            return(this.View());
        }
예제 #11
0
        public async Task <IActionResult> SetPassword(ResetPasswordBindingModel model)
        {
            if (string.IsNullOrEmpty(model.UserId) || string.IsNullOrEmpty(model.NewPassword) || string.IsNullOrEmpty(model.Token))
            {
                ModelState.AddModelError("", "userId or password or token is missing");
                return(BadRequest(ModelState));
            }

            if (!IsPasswordValid(model.NewPassword))
            {
                ModelState.AddModelError("Password", PasswordRequirementMessage(model.NewPassword));
                return(BadRequest(ModelState));
            }

            ApplicationUser user = await userManager.FindByIdAsync(model.UserId).ConfigureAwait(false);

            user.ForcedPasswordChange = false;
            var token = WebUtility.UrlDecode(model.Token);

            if (user != null)
            {
                var result = await userManager.ResetPasswordAsync(user, token, model.NewPassword);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
            }

            return(Ok());
        }
예제 #12
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                return(Ok());
            }

            var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(Ok());
            }

            AddErrors(result);

            return(BadRequest(ModelState));
        }
예제 #13
0
        public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordBindingModel bm)
        {
            if (bm == null)
            {
                return(BadRequest("The payload must not be null."));
            }

            if (string.IsNullOrWhiteSpace(bm.Token))
            {
                return(BadRequest("The token is required."));
            }

            if (string.IsNullOrWhiteSpace(bm.Password))
            {
                return(BadRequest("A password is required."));
            }

            if (string.IsNullOrWhiteSpace(bm.ConfirmPassword))
            {
                return(BadRequest("A password confirmation is required."));
            }

            if (bm.Password != bm.ConfirmPassword)
            {
                return(BadRequest("The passwords must match."));
            }

            try
            {
                var json         = Helpers.DecodeToken(bm.Token);
                var emailAddress = json.FirstOrDefault(x => x.Key == "email").Value;

                if (string.IsNullOrWhiteSpace(emailAddress))
                {
                    return(BadRequest("The email is invalid."));
                }

                var user = await _userService.GetUserByEmail(emailAddress);

                if (user == null)
                {
                    return(NotFound());
                }

                await _userService.SetPassword(emailAddress, bm.Password);

                var email = EmailTemplates.GetResetPasswordEmail(user.FirstName);
                await _emailService.SendAsync(user.Email, "Password Reset", email);

                _logger.LogInformation("Forgot password email sent successfully.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(Ok("The password has been updated."));
        }
예제 #14
0
        public ActionResult ResetPassword(string token, string email)
        {
            var model = new ResetPasswordBindingModel {
                Token = token, Email = email
            };

            return(View(model));
        }
예제 #15
0
        public ActionResult ResetPassword(string code)
        {
            var model = new ResetPasswordBindingModel()
            {
                Code = code
            };

            return(View(model));
        }
예제 #16
0
        public ActionResult ResetPassword(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(
                new KeyValuePair <string, string>("Email", model.Email));
            parameters.Add(
                new KeyValuePair <string, string>("Password", model.Password));
            parameters.Add(
                new KeyValuePair <string, string>("ConfirmPassword", model.ConfirmPassword));

            parameters.Add(
                new KeyValuePair <string, string>("Code", model.Code));

            var encodedParameters = new FormUrlEncodedContent(parameters);

            var httpClient = new HttpClient();

            var response = httpClient
                           .PostAsync("http://localhost:64310/api/account/resetpassword",
                                      encodedParameters)
                           .Result;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(RedirectToAction("ResetPasswordSuccess"));
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                var data = response.Content.ReadAsStringAsync().Result;

                var errors = JsonConvert.DeserializeObject <Error>(data);

                foreach (var key in errors.ModelState)
                {
                    foreach (var error in key.Value)
                    {
                        ModelState.AddModelError(key.Key, error);
                    }
                }

                return(View(model));
            }
            else
            {
                //Create a log for the error message

                ModelState.AddModelError("", "Sorry. An unexpected error has occured. Please try again later");
                return(View(model));
            }
        }
예제 #17
0
        public async Task <IHttpActionResult> RequestResetPassword(ResetPasswordBindingModel resetmodel)
        {
            using (var dataContext = HttpContext.Current.GetOwinContext().Get <ApplicationDbContext>())
            {
                using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted))
                {
                    try
                    {
                        resetmodel.token = RandomLink.getVerifyPathResetPsw() + resetmodel.token;
                        var resetpass = dataContext.ResetPasswords.FirstOrDefault(t => t.email.Equals(resetmodel.email) && t.token.Equals(resetmodel.token));
                        if (resetpass == null)
                        {
                            throw new ApiDataException(16, "No existe una confirmación en el sistema para confirmar"
                                                       , System.Net.HttpStatusCode.NotFound, "Http://");
                        }

                        if (resetpass.state == (Int32)StatesEnum.Confirmed)
                        {
                            throw new ApiBusinessException(0006, "El link ya fue utilizado", System.Net.HttpStatusCode.NotFound, "Http");
                        }

                        if (resetpass.state == (Int32)StatesEnum.Annulled)
                        {
                            throw new ApiDataException(18, "La confirmación fue reemplazada por una nueva o ya expiró"
                                                       , System.Net.HttpStatusCode.NotFound, "Http://");
                        }

                        if (resetpass.expiredate < DateTime.Now)
                        {
                            throw new ApiBusinessException(17, "Esta solicitud ya expiró, mande una nueva solicitud."
                                                           , System.Net.HttpStatusCode.NotFound, "Http://");
                        }

                        var user = await this.AppUserManager.FindByEmailAsync(resetpass.email);

                        if (user == null)
                        {
                            throw new ApiDataException(15, "No existe ese email en nuestro sistema",
                                                       System.Net.HttpStatusCode.NotFound, "Http://");
                        }

                        user.PasswordHash = this.AppUserManager.PasswordHasher.HashPassword(resetmodel.newpassword);
                        this.AppUserManager.UpdateSecurityStamp(user.Id);
                        resetpass.state = (Int32)StatesEnum.Confirmed;
                        dataContext.SaveChanges();
                        trans.Commit();
                        return(Ok());
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw HandlerExceptions.GetInstance().RunCustomExceptions(ex);
                    }
                }
            }
        }
예제 #18
0
        public async Task ResetPassword_Should_ReturnBadRequest_When_TheDecodedEmailDoesNotExist()
        {
            var token   = Helpers.GenerateToken("email", "*****@*****.**");
            var payload = new ResetPasswordBindingModel {
                Token = token, Password = "******", ConfirmPassword = "******"
            };
            var response = await Client.PostAsJsonAsync("/api/auth/reset-password", payload);

            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
예제 #19
0
        public Task <MessageViewModel> ResetPassword(string emailAddress, string resetCode, string password)
        {
            var bm = new ResetPasswordBindingModel
            {
                EmailAddress = emailAddress,
                ResetCode    = resetCode,
                Password     = password
            };

            return(_authService.ResetPassword(bm));
        }
예제 #20
0
        public IActionResult ResetPassword(string code = null)
        {
            if (code == null)
            {
                throw new ApplicationException(AccountConstants.SuppliedCode);
            }

            var model = new ResetPasswordBindingModel {
                Code = code
            };

            return(this.View(model));
        }
예제 #21
0
        public async Task <IHttpActionResult> PasswordReset(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            PasswordResetToken _token = await UnitOfWork.PasswordResetTokenStore.FindByToken(model.ResetToken);

            if (_token == null)
            {
                return(BadRequest("Invalid Token"));
            }
            if (_token.Expires < DateTime.Now)
            {
                return(BadRequest("Expired Token"));
            }
            if (_token.Used.HasValue)
            {
                return(BadRequest("Token Already Used"));
            }
            ISS.Authentication.Domain.Models.User _user = await UnitOfWork.UserStore.FindByIdAsync(_token.UserId);

            if (_user == null)
            {
                return(BadRequest("User not Found"));
            }
            IdentityResult _result = await UserManager.RemovePasswordAsync(_user.Id);

            _result = await UserManager.AddPasswordAsync(_user.Id, model.NewPassword);

            _token.Used = DateTime.Now;
            if (_result.Succeeded)
            {
                await UnitOfWork.PasswordResetTokenStore.UpdateAsync(_token);

                return(Ok());
            }
            else
            {
                string _errors = "";
                foreach (string _error in _result.Errors)
                {
                    if (_errors != "")
                    {
                        _errors += "; ";
                    }
                    _errors += _error;
                }
                return(BadRequest(_errors));
            }
        }
예제 #22
0
        public IHttpActionResult PostResetPassword(ResetPasswordBindingModel model)
        {
            var result = UserManager.ResetPassword(model.UserID, model.PasswordResetToken, model.NewPassword);

            if (!result.Succeeded)
            {
                result = UserManager.ResetPassword(model.UserID, HttpUtility.UrlDecode(model.PasswordResetToken), model.NewPassword);
                if (!result.Succeeded)
                {
                    result = UserManager.ResetPassword(model.UserID, model.PasswordResetToken.Replace(' ', '+'), model.NewPassword);
                }
            }
            return(Ok(result));
        }
예제 #23
0
        public async Task ResetPassword_Should_ReturnOk_When_TheDataIsComplete()
        {
            var token   = Helpers.GenerateToken("email", "*****@*****.**");
            var payload =
                new ResetPasswordBindingModel {
                Token = token, Password = "******", ConfirmPassword = "******"
            };
            var response = await Client.PostAsJsonAsync("/api/auth/reset-password", payload);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
            var responseString = await response.Content.ReadAsStringAsync();

            responseString.Should().Be("The password has been updated.");
        }
예제 #24
0
        public async Task <IHttpActionResult> ResetPassword([FromBody] ResetPasswordBindingModel model)
        {
            DBUpdates dbupdates = new DBUpdates();
            Response  response  = new Response();

            if (model.SecurityAnswer != null && model.SecurityAnswer != "")
            {
                response = dbupdates.IsSecurityValid(model.Email, model.SecurityAnswer);

                if (response.isSuccess)
                {
                    if (model.Email != null)
                    {
                        var user  = UserManager.FindByEmail(model.Email);
                        var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                        var result = await UserManager.ResetPasswordAsync(user.Id, token, model.NewPassword);

                        if (!result.Succeeded)
                        {
                            return(GetErrorResult(result));
                        }

                        return(Ok());
                    }
                    else
                    {
                        response.ErrorList = new List <string> {
                            "Email Is Blank or Incorrect. Please Enter Correct Email."
                        };
                        return(GetErrorResult(response));
                    }
                }
                else
                {
                    response.ErrorList = new List <string> {
                        "Answer for Security Question is Incorrect. Please Enter Correct Security Question Answer."
                    };
                    return(GetErrorResult(response));
                }
            }
            else
            {
                response.ErrorList = new List <string> {
                    "Answer for Security Question is Incorrect. Please Enter Correct Security Question Answer."
                };
                return(GetErrorResult(response));
            }
        }
예제 #25
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var user = UserManager2.FindUser(model.email);
                if (user == null)
                {
                    return(BadRequest("email not found"));
                }

                var newPassword = NameGenerator.RandomString(7);
                var emailResult = EmailManager.SendNewPassword(model.email, newPassword);

                if (emailResult)
                {
                    //IdentityResult result = await .SetPasswordHashAsync(user, newPassword);

                    var provider = new DpapiDataProtectionProvider("Todo");
                    UserManager.UserTokenProvider = new DataProtectorTokenProvider <User, long>(provider.Create("ASP.NET Identity"))
                                                    as IUserTokenProvider <User, long>;

                    var            resetToken = UserManager.GeneratePasswordResetToken(user.Id);
                    IdentityResult result     = UserManager.ResetPassword(user.Id, resetToken, newPassword);

                    if (!result.Succeeded)
                    {
                        return(GetErrorResult(result));
                    }

                    user = await UserManager.FindByIdAsync(user.Id);

                    user = UserManager2.Update(user);

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, $"ResetPassword error: {ex}");
                return(BadRequest(ex.Message));
            }

            return(BadRequest());
        }
예제 #26
0
        public async Task <IActionResult> ResetPasswordAsync([FromBody] ResetPasswordBindingModel rpbm)
        {
            string userId = rpbm.Token.Split('&')[0];
            string code   = rpbm.Token.Split('&')[1];
            var    user   = await userManager.FindByIdAsync(userId);

            var result = await userManager.ResetPasswordAsync(user, code, rpbm.Password);

            if (result.Succeeded)
            {
                return(Ok(new SuccessObject("Successfuly reseted password")));
            }

            return(BadRequest(result.Errors));
        }
예제 #27
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            var currentUser = await UserManager.FindByEmailAsync(model.Email);

            var result = await UserManager.ResetPasswordAsync(currentUser.Id, model.Token, model.NewPassword);

            var errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return(errorResult);
            }

            return(Ok(currentUser));
        }
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IdentityResult result = await UserManager.ResetPasswordAsync(model.Id, model.Code, model.NewPassword);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
예제 #29
0
        public IHttpActionResult ResetPassword(ResetPasswordBindingModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(Conflict());
                }

                return(Ok(_userService.ResetPassword(model.Email, model.NewPassword, model.Link)));
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
예제 #30
0
        public async Task <IHttpActionResult> ResetPassword(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            IdentityResult result = await UserManager.ResetPasswordAsync(model.UserId, model.Token, model.NewPassword);

            //return GetErrorResult(result);
            if (result.Succeeded)
            {
                await UserManager.ResetAccessFailedCountAsync(model.UserId); //not sure if necessary

                return(Ok());
            }
            return(GetErrorResult(result));
        }