Exemplo n.º 1
0
 public ActionResult Update(ResetPassword Model)
 {
     return Dispatcher.Update(
         DataModel: Model,
         SuccessResult: m => RedirectToAction("Index", "Home"),
         InvalidResult: m => View(m));
 }
Exemplo n.º 2
0
        public virtual async Task<ActionResult> Post(ResetPassword command, string returnUrl, string emailAddress)
        {
            //System.Threading.Thread.Sleep(new Random().Next(5000, 5001));

            if (command == null || string.IsNullOrWhiteSpace(emailAddress))
                return View(MVC.Errors.Views.BadRequest);

            var verification = await _queries.Execute(new EmailVerificationBy(command.Ticket));
            if (verification == null) return HttpNotFound();

            if (!ModelState.IsValid)
            {
                ViewBag.EmailAddress = emailAddress;
                ViewBag.Ticket = command.Ticket;
                ViewBag.Token = command.Token;
                ViewBag.ReturnUrl = returnUrl;
                return View(MVC.Security.Views.ResetPassword.ResetPassword, command);
            }

            await _commands.Execute(command);

            var signIn = new SignIn
            {
                UserNameOrVerifiedEmail = verification.EmailAddress.Value,
                Password = command.Password
            };
            await _commands.Execute(signIn);
            Session.VerifyEmailTickets(null);
            Response.ClientCookie(signIn.SignedIn.Id, _queries);
            return this.RedirectToLocal(returnUrl, await MVC.UserName.Index());
        }
Exemplo n.º 3
0
 private void _resetPassword(ResetPassword request, Action<DriverAuthorizationResult> onSuccess, Action<GeneralFailureCode> onFailure) {
    if (request.ClientId == null || request.RegistrationCode.IsEmpty()) {
       Log.Warn("Driver registration: Attempt to reset password with bad arguments. UserId:{0}, UserSsn:{1}", request.ClientId, request.RegistrationCode);
       onFailure(GeneralFailureCode.InvalidData);
    } else {
       var loginName = AuthServices.GetLoginName(request.ClientId);
       if (loginName.NotEmpty()) {
          var roles = AuthServices.GetClientRoles(loginName);
          if (roles != null) {
             if (roles.Contains(BplRole.Get(OscarRoles.Driver))) {
                _checkDriver(request.ClientId, request.RegistrationCode, AuthorizationSessionKind.ResetPassword, onSuccess, r => onFailure(r.Error));
             } else {
                Log.Warn("Driver registration: {0} is {1}. Reset password is not supported yet.", request.ClientId, roles.FirstOrDefault());
                onFailure(GeneralFailureCode.InvalidData);
             }
          } else {
             Log.Warn("Driver registration: Unable to retrive client {0} role.", request.ClientId);
             onFailure(GeneralFailureCode.InvalidData);
          }
       } else {
          Log.Warn("Driver registration: Client {0} was not found for password reset.", request.ClientId);
          onFailure(GeneralFailureCode.InvalidData);
       }
    }
 }
        public async Task<ActionResult> ResetPassword(ResetPassword model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (!ModelState.IsValid)
            {
                return View(model);
            }

            if (await membershipService.ResetPassword(
                model.Token,
                model.Password))
            {
                Flash[FlashMessageType.Success] = "Your password is " +
                    "successfully changed.";
            }
            else
            {
                Flash[FlashMessageType.Error] = "Invalid reset token, " +
                    "you may have miss typed the token or the token has " +
                    "expired.";
            }

            return RedirectToHome();
        }
Exemplo n.º 5
0
 public void GivenAnonymousPostRequest_WithInvalidId_Redirects()
 {
     var model = new ResetPassword
         {
             Token = Guid.NewGuid()
         };
     var result = Controller.ResetPassword(model) as RedirectResult;
     result.Should().Not.Be.Null();
     result.Url.Should().Equal(Controller.Url.Account().ForgotPassword());
     var notification = Controller.TempData[ViewDataConstants.Notification] as Notification;
     notification.Should().Not.Be.Null();
 }
Exemplo n.º 6
0
        public virtual ActionResult Validate(ResetPassword command, string fieldName = null)
        {
            //System.Threading.Thread.Sleep(new Random().Next(5000, 5001));

            if (command == null)
            {
                Response.StatusCode = 400;
                return Json(null);
            }

            var result = new ValidatedFields(ModelState, fieldName);

            //ModelState[command.PropertyName(x => x.UserName)].Errors.Clear();
            //result = new ValidatedFields(ModelState, fieldName);

            return new CamelCaseJsonResult(result);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> ResetPassword(ResetPassword resetPassword)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = await _userManager.FindByEmailAsync(resetPassword.Email);

            if (user == null)
            {
                return(BadRequest(ModelState));
            }
            var resetPassResult = await _userManager.ResetPasswordAsync(user, resetPassword.Token, resetPassword.Password);

            if (!resetPassResult.Succeeded)
            {
                return(BadRequest(ModelState));
            }
            return(Ok());
        }
        public async Task <bool> ResetPassword(ResetPassword model)
        {
            var user = await _unitOfWork.UserManager.FindByEmailAsync(model.Email);

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

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

            if (result.Succeeded)
            {
                _logger.Info($"The password for  {model.Email} was reseted");

                return(true);
            }

            throw new Exception("Cannot change the password");
        }
        public async Task ResetPasswordReturnsNoContentIfCodeIsValid()
        {
            var userManager = TestHelpers.CreateUserManagerWithUser(out var testUser);
            var controller  = CreateController(userManager);

            var code = await userManager.GeneratePasswordResetTokenAsync(testUser);

            var resetPassword = new ResetPassword
            {
                UserId      = testUser.Id,
                NewPassword = "******",
                Code        = code
            };

            var res = await controller.ResetPassword(resetPassword);

            res.Should().BeOfType <NoContentResult>();

            (await userManager.CheckPasswordAsync(testUser, resetPassword.NewPassword)).Should().BeTrue();
        }
Exemplo n.º 10
0
        public String GetResetPassword(String ResetPasswordvalue)
        {
            String        Msg           = String.Empty;
            ResetPassword resetPassword = Users.GetResetPassword(ResetPasswordvalue);

            Msg = resetPassword.Message;
            if (resetPassword.Message.Contains("Sucessfull"))
            {
                var issent = SendPasswordResetEmail(resetPassword.Email, resetPassword.Username, resetPassword.UniqueId);
                if (issent)
                {
                    Msg = "An email with instructions to reset your password is sent to  " + resetPassword.Email;
                }
                else
                {
                    Msg = "Due to internal error a email with instructions  failed to send to  " + resetPassword.Email;
                }
            }
            return(Msg);
        }
        private IResult CreatePasswordResetToken(string Email)
        {
            var user = _userService.GetByEmail(Email);

            if (user != null)
            {
                var token          = Guid.NewGuid().ToString();
                var expirationTime = DateTime.Now.AddDays(1);
                var resetUser      = new ResetPassword
                {
                    UserId         = user.Id,
                    Token          = token,
                    ExpirationTime = expirationTime
                };
                _sifreYenilemeDal.Add(resetUser);
                return(new SuccessResult());
            }
            _loggerService.Info("CreatePasswordResetToken: " + "UserNotFound");
            return(new ErrorResult("UserNotFound"));
        }
Exemplo n.º 12
0
        public async Task <ActionResult> ResetPassword(ResetPassword model)
        {
            if (!Data.CheckPasswordResetRequest(model.RequestId))
            {
                ModelState.AddModelError("", "Request ID is invalid. It might have been used already.");
            }

            if (!ModelState.IsValid)
            {
                return(View(new ResetPassword()));
            }

            var user = Data.ResetPassword(model.RequestId, model.NewPass);

            await SetAuthCookieAsync(user.Name, createPersistentCookie : false);

            TempData.SetStatusMessage("Password reset successfully!");

            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult AuthenticateResetPassword(string token)
        {
            DataManager dm = new DataManager();
            //validate token
            var m = dm.ValidateToken(token, 1440);

            //does it exist
            //has it expired
            if (m == null)
            {
                dm.TryInvalidateToken(token);
                TempData["ErrorMessage"] = "We could not validate you on the system. This could be because the token is invalid. Please try again.";
                return(PartialView("ResetPasswordForm", new ResetPassword()));
            }

            ResetPassword model = new ResetPassword();

            model.Token = token;
            return(PartialView("ResetPasswordForm", model));
        }
Exemplo n.º 14
0
        public ActionResult Reset(string email)
        {
            var user = _usersService.GetByEmail(email);

            if (user == null)
            {
                ModelState.AddModelError("email", "User with this email is not registred.");
            }
            if (ModelState.IsValid)
            {
                var newPass = GenerateNewPassword(7);
                var cmd     = new ResetPassword
                {
                    Id = email
                };
                Send(cmd);
                return(Redirect("/"));
            }
            return(View("Forgot", (object)email));
        }
Exemplo n.º 15
0
        public async Task <IActionResult> Activate([FromBody] ResetPassword model)
        {
            var isActivate = await AuthenticationService.IsUserActive(model.UserName);

            if (isActivate)
            {
                return(BadRequest(new Result("", "User Account has already been activated").ValidationFailures));
            }

            var result = await AuthenticationService.ResetPassword(model);

            if (!result.Success)
            {
                return(BadRequest(result.ValidationFailures));
            }

            result.Tag = await AuthenticationService.GenerateToken(model.UserName, JwtOptions);

            return(Ok(result));
        }
        public IHttpActionResult Delete([FromBody] ResetPassword resetPassword, [FromUri] string lang = "en")
        {
            using (CSSPDBContext db = new CSSPDBContext(DatabaseType))
            {
                ResetPasswordService resetPasswordService = new ResetPasswordService(new Query()
                {
                    Language = (lang == "fr" ? LanguageEnum.fr : LanguageEnum.en)
                }, db, ContactID);

                if (!resetPasswordService.Delete(resetPassword))
                {
                    return(BadRequest(String.Join("|||", resetPassword.ValidationResults)));
                }
                else
                {
                    resetPassword.ValidationResults = null;
                    return(Ok(resetPassword));
                }
            }
        }
Exemplo n.º 17
0
        public async Task <IActionResult> ForgotPassword(ResetPassword model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByEmailAsync(model.Email);

                if (user != null && user.EmailConfirmed)
                {
                    var token = await userManager.GeneratePasswordResetTokenAsync(user);

                    var passwordResetLink = Url.Action("ResetPassword", "Account",
                                                       new { email = model.Email, token = token }, Request.Scheme);
                    ViewBag.message = "Reset Link: " + passwordResetLink;

                    return(View("ForgotPasswordConfirmation"));
                }
                return(View("ForgotPasswordConfirmation"));
            }
            return(View(model));
        }
Exemplo n.º 18
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using HttpClient client = _httpClientFactory.CreateClient(_configuration["ApplicationIds:IdManagementId"]);
            client.BaseAddress      = new Uri(_configuration["AppURLS:IdApiBaseUrl"]);

            string        asJson  = JsonSerializer.Serialize <ForgotPasswordViewModel>(model);
            StringContent content = new StringContent(asJson, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync("/api/v1/Account/ForgotPasswordAsync", content);

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogError("~/Account/ForgotPassword(ForgotPasswordViewModel) - An error occurred with the Http Response Message. Response:{0}", response);
                throw new HttpRequestException($"An error occurred attempting to reset the password on the account with the email address: {model.Email}");
            }

            string responseContent = await response.Content.ReadAsStringAsync();

            ResetPassword forgotPasswordObj = JsonSerializer.Deserialize <ResetPassword>(responseContent);

            response.EnsureSuccessStatusCode();

            var callbackUrl = Url.ResetPasswordCallbackLink(forgotPasswordObj.Code, Request.Scheme);

            try
            {
                await _emailSender.SendEmailAsync(model.Email, "Reset Your Password", $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
            }
            catch (SmtpException ex)
            {
                _logger.LogError("An error occurred sending Password reset email for User Email:{0}, Error:{1}, Error Message{2}, Stack Trace:{3}", forgotPasswordObj.Email, ex, ex.Message, ex.StackTrace);
                throw;
            }

            return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
        }
        public async Task <ActionResult <ItemResponse <int> > > ResetPassword(ResetPassword model)
        {
            int          iCode        = 200;
            BaseResponse response     = null;
            int          userId       = 0;
            bool         isSuccessful = false;


            try
            {
                userId       = _authService.GetCurrentUserId();
                isSuccessful = _service.ResetPassword(model, userId);
                if (isSuccessful == true)
                {
                    try
                    {
                        await _authService.LogOutAsync();
                    }
                    catch (Exception ex)
                    {
                        iCode = 500;
                        base.Logger.LogError(ex.ToString());
                        response = new ErrorResponse($"Logout Error: {ex.Message}");
                    }
                    response = new SuccessResponse();
                }
                else
                {
                    iCode    = 404;
                    response = new ErrorResponse("Resource Not Found");
                }
            }
            catch (Exception ex1)
            {
                iCode = 500;
                base.Logger.LogError(ex1.ToString());
                response = new ErrorResponse($"Server Error: {ex1.Message}");
            }

            return(StatusCode(iCode, response));
        }
Exemplo n.º 20
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (this.ModelState.IsValid)
            {
                // Deliberately slow this method down slightly to avoid leaking information via time taken
                await Task.Delay(TimeSpan.FromMilliseconds(new Random().Next(200)));

                var user = await this.userManager.FindByEmailAsync(this.Input.Email);

                if (user == null || !(await this.userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(this.RedirectToPage("./ForgotPasswordConfirmation"));
                }

                var code = await this.userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = this.Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { code },
                    protocol: "https");

                var ipAddress = this.httpContextAccessor.GetOriginatingIpAddress();

                var resetPasswordEmail = new ResetPassword(this.Input.Email, callbackUrl, ipAddress);

                var recentlySent = this.emailRepository
                                   .GetRecent()
                                   .Any(e => e.To == resetPasswordEmail.To && e.Subject == resetPasswordEmail.Subject);

                if (!recentlySent)
                {
                    this.emailRepository.AddToQueue(resetPasswordEmail);
                }

                return(this.RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(this.Page());
        }
Exemplo n.º 21
0
        public async Task <IActionResult> ResetPassword(ResetPassword model)
        {
            if (ModelState.IsValid)
            {
                model.Token = model.Token.Replace(' ', '+');
                var result = await _accountRepository.ResetPasswordAsync(model);

                if (result.Succeeded)
                {
                    ModelState.Clear();
                    model.IsSuccess = true;
                    return(View(model));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View(model));
        }
Exemplo n.º 22
0
        public async Task <IActionResult> ResetPassword(string id)
        {
            IEnumerable <RoleViewModel> lstRoles = await ApiInvoker.GetAsync <IEnumerable <RoleViewModel> >(APIURL.IdentityBaseUri + IdentityAPI.Role.GetAll);

            var objParam = new
            {
                id = id
            };
            UserEditGetModel user = await ApiInvoker.PostAsync <UserEditGetModel>(objParam, APIURL.IdentityBaseUri + IdentityAPI.User.GetByID);

            ResetPassword reset = new ResetPassword();

            if (user != null)
            {
                reset.UserName = user.UserName;
            }
            Dictionary <string, string> _localLabel = await LocalizeData(LocalizePath);

            ViewData["LocalLabel"] = _localLabel;
            return(View("ResetPassword", reset));
        }
Exemplo n.º 23
0
        public ActionResult RestPassword(ResetPassword resetPassword)
        {
            int   uid       = Convert.ToInt32(Session["Id"]);
            Users UserIndDb = db.Users.Single(e => e.Id == uid);

            if (UserIndDb.UserPass == resetPassword.CurrentPassword && resetPassword.NewPassword.Length >= 8)
            {
                UserIndDb.UserPass = resetPassword.NewPassword;

                db.SaveChanges();



                Session["message"] = "successfully new pass  ";
            }
            else
            {
                Session["message"] = "invalid";
            }
            return(RedirectToAction("UserProfile", new { id = UserIndDb.Id }));
        }
Exemplo n.º 24
0
 public ActionResult ResetPassword(string id)
 {
     BGBC.Web.Models.ResetPassword reset = new ResetPassword();
     try
     {
         PasswordReset pwd = passwordresetRepo.Get().Where(x => x.Token == id).FirstOrDefault();
         if (pwd == null)
         {
             ViewBag.ValidEmail = false;
         }
         else
         {
             reset.TokenID = id; ViewBag.ValidEmail = true;
         }
     }
     catch (Exception ex)
     {
         log.Error(ex.Message);
     }
     return(View(reset));
 }
Exemplo n.º 25
0
		public IHttpActionResult ResetPassword(ResetPassword resetPassword)
		{
			if (resetPassword.Key != "123")
			{
				return Content(HttpStatusCode.Forbidden, "Code is wrong");
			}

			if (resetPassword.Password != resetPassword.PasswordConfirm)
			{
				return Content(HttpStatusCode.Forbidden, "Password is not matched");
			}

			var user = _userService.GetByUserNameActive(resetPassword.UserName);
			user.Password = PasswordHash.GetPass(resetPassword.Password);
			_userService.UpdatePassword(user);

			return Ok(new
			{
				data = "Ok"
			});
		}
Exemplo n.º 26
0
        public void GivenAnonymousPostRequest_WithValidData_LogsInUser()
        {
            var expectedObject = new PasswordRetrieval
            {
                Token  = Guid.NewGuid(),
                UserId = User.Id
            };

            Db.Save(expectedObject);

            var model = new ResetPassword
            {
                Token    = expectedObject.Token,
                Password = "******" + GetRandom.String(10),
            };

            model.PasswordConfirm = model.Password;
            Controller.ResetPassword(model);

            AuthenticationService.Verify(x => x.SetLoginCookie(It.Is <User>(u => u.Id == User.Id), true), Times.Once());
        }
Exemplo n.º 27
0
        public async Task <IActionResult> ResetPassword([FromBody] ResetPassword model)
        {
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                return(this.Ok());
            }
            var result = await UserManager.ResetPasswordAsync(user, model.Code, model.Password);

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

            return(this.BadRequest(new
            {
                Email = result.Errors.Where(e => e.Code.ToLower().Contains("email")).Select(x => x.Code).ToList(),
                Password = result.Errors.Where(e => e.Code.ToLower().Contains("password")).Select(x => x.Code).ToList(),
            }));
        }
Exemplo n.º 28
0
        public async Task resetpassword_command_should_fail_if_user_does_not_exist()
        {
            var id            = new AggregateId();
            var email         = "*****@*****.**";
            var fullname      = "fullname";
            var password      = "******";
            var newPassword   = "******";
            var pic           = "test.nl/image";
            var role          = Role.User;
            var securityStamp = new Guid().ToString();


            // generate reset token
            var token = await _dataProtectorTokenProvider.GenerateAsync(Purpose, id, securityStamp);

            var command = new ResetPassword(id, newPassword, token);

            _commandHandler
            .Awaiting(c => c.HandleAsync(command))
            .Should().Throw <UserNotFoundException>();
        }
Exemplo n.º 29
0
        public string ObtenerCodigoRestablecerPassword(string email)
        {
            ResetPassword C = new ResetPassword();

            try
            {
                using (SudokuContext Context = new SudokuContext())
                {
                    C = Context.ResetPassword.Where(x => x.Email == email && x.Estatus == false).OrderByDescending(x => x.Id).Take(1).FirstOrDefault();
                    if (C != null)
                    {
                        return(C.Codigo);
                    }
                }
            }
            catch (Exception ex)
            {
                InsertarSucesoLog(Funcion.ConstruirSucesoLog(ex.ToString().Substring(0, 300) + "*EngineDb/ObtenerCodigoRestablecerPassword*" + email));
            }
            return(string.Empty);
        }
Exemplo n.º 30
0
        public IActionResult ChangePassword(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var member = _security.GetMemberByApplicationId(id);

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

            ResetPassword cp = new ResetPassword();

            cp.Id       = id;
            cp.UserName = member.UserName;

            return(View(cp));
        }
Exemplo n.º 31
0
        public ActionResult ResetPassword(ResetPassword model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (resetPassword(model.Token, model.Password))
            {
                Flash[FlashMessageType.Success] = "Your password is " +
                                                  "successfully changed.";
            }
            else
            {
                Flash[FlashMessageType.Error] = "Invalid reset token, " +
                                                "you may have miss typed the token or the token has " +
                                                "expired.";
            }

            return(RedirectToHome());
        }
Exemplo n.º 32
0
        public async Task ResetPassword_ResetPasswordModel_Exception()
        {
            var email         = "*****@*****.**";
            var id            = "1";
            var resetPassword = new ResetPassword {
                Email = email
            };
            var user = new IdentityUser()
            {
                Email = email, Id = id
            };
            var userStore      = Mock.Of <IUserStore <IdentityUser> >();
            var userManager    = new Mock <ApplicationUserManager>(userStore);
            var identityResult = IdentityResult.Failed(null);

            userManager.Setup(_ => _.FindByEmailAsync(email)).Returns(Task.FromResult(user));
            userManager.Setup(_ => _.ResetPasswordAsync(id, It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(identityResult));
            _unitOfWorkMock.SetupGet(uof => uof.UserManager).Returns(userManager.Object);

            await Assert.ThrowsAsync <Exception>(() => _sut.ResetPassword(resetPassword));
        }
        public ActionResult ResetPassword(ResetPassword model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            if (resetPassword(model.Token, model.Password))
            {
                Flash[FlashMessageType.Success] = "Your password is " +
                    "successfully changed.";
            }
            else
            {
                Flash[FlashMessageType.Error] = "Invalid reset token, " +
                    "you may have miss typed the token or the token has " +
                    "expired.";
            }

            return RedirectToHome();
        }
Exemplo n.º 34
0
 public ActionResult Edit([Bind(Include = "email,old_password,password,confirm_password")] ResetPassword user)
 {
     try
     {
         // TODO: Add update logic here
         var the_user = db.Account.Find(user.email);
         if (the_user != null && the_user.Password == user.old_password)
         {
             if (user.password == user.confirm_password)
             {
                 the_user.Password = user.password;
                 db.SaveChanges();
             }
         }
         return(RedirectToRoute("default"));
     }
     catch
     {
         return(View());
     }
 }
Exemplo n.º 35
0
        public ActionResult ResetPassword(ResetPassword model, string ReturnUrl = "")
        {
            string message = "";
            bool   Status  = false;
            string type    = "Success";

            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var user = dc.Users.Where(x => x.EmailID == model.EmailID).FirstOrDefault();
                if (!user.Locked)
                {
                    message = "your account has not been locked please try forgotten password.";
                    type    = "Error";
                    Status  = true;
                }
                else
                {
                    if (user != null)
                    {
                        if (SendReActiveMail(user))
                        {
                            message = "Request has been sent to admin.";
                            type    = "Success";
                            Status  = true;
                        }
                        else
                        {
                            message = "Request has not been sent to admin. try writing a mail directly to admin if the error continues Admin-Mail: [email protected]";
                            type    = "Error";
                            Status  = true;
                        }
                    }
                }
            }

            ViewBag.Message = message;
            ViewBag.Status  = Status;
            ViewBag.Type    = type;
            return(View());
        }
Exemplo n.º 36
0
        public async Task <ActionResult> ResetPassword(ResetPassword model)
        {
            if (ModelState.IsValid)
            {
                var meta = repo.GetPuckMeta().Where(x => x.Name == DBNames.PasswordResetToken && x.Key == model.ResetToken).FirstOrDefault();

                if (meta == null)
                {
                    ModelState.AddModelError("", "Password reset request not found.");
                    return(View(model));
                }

                var user = await userManager.FindByEmailAsync(meta.Value);

                if (user == null)
                {
                    ModelState.AddModelError("", "User not found.");
                    return(View(model));
                }

                var token = await userManager.GeneratePasswordResetTokenAsync(user);

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

                if (!result.Succeeded)
                {
                    string message = string.Join(" ", result.Errors.Select(x => x.Description));
                    ModelState.AddModelError("", message);
                    return(View(model));
                }

                repo.DeleteMeta(meta);
                repo.SaveChanges();

                ViewBag.SuccessMessage = "Password successfully changed.";

                return(View(model));
            }
            return(View(model));
        }
Exemplo n.º 37
0
        public ActionResult ResetPassword(ResetPassword model)
        {
            if (!ConfigBase.Settings.PasswordReset)
            {
                return(HttpNotFound());
            }

            try
            {
                AntiForgery.Validate();
            }
            catch (Exception ex)
            {
                ex.Log();

                return(null);

                ///TODO: Change the message
                return(Json(new { status = "error", message = Words.Login_SessionExpired }));
            }

            if (!ModelState.IsValid)
            {
                return(null);
            }

            if (!ValidateEmail(model.EmailAddress))
            {
                return(Json(new { status = "error", message = Words.Login_PasswordResetInvalidEmail }));
            }

            if (new AuthLogin().ResetPassword(model.EmailAddress))
            {
                return(Json(new { status = "success", message = Words.Login_PasswordResetEmailSent }));
            }
            else
            {
                return(Json(new { status = "error", message = Words.Login_PasswordResetInvalidEmail }));
            }
        }
Exemplo n.º 38
0
        public void GivenAnonymousPostRequest_WithValidData_DeletesPasswordRetrieval()
        {
            var expectedObject = new PasswordRetrieval
                {
                    Token = Guid.NewGuid(),
                    UserId = User.Id
                };
            Db.Save(expectedObject);

            var model = new ResetPassword
                {
                    Token = expectedObject.Token,
                    Password = "******" + GetRandom.String(10),
                };
            model.PasswordConfirm = model.Password;
            var result = Controller.ResetPassword(model) as ViewResult;
            result.Should().Not.Be.Null();

            var previousObject = Db.SingleOrDefault<PasswordRetrieval>(new { expectedObject.Id });
            previousObject.Should().Be.Null();
        }
Exemplo n.º 39
0
        public ActionResult ResetPassword(ResetPassword model)
        {
            if (ModelState.IsValid)
            {
                using (RavenSession.GetCachingContext())
                {
                    model.Data = RavenSession.Query<PasswordRetrieval>().SingleOrDefault(x => x.Token == model.Token);

                    if (model.Data == null)
                        return Redirect(Url.Home().Index());

                    User.UserObject.Password = model.Password.ToSHAHash();
                    RavenSession.Store(User.UserObject);
                    RavenSession.Delete(model.Data);
                    RavenSession.SaveChanges();

                    Metrics.Increment(Metric.Users_ResetPassword);
                }
                //show confirmation
                return View("ResetPasswordConfirmation");
            }
            return View(model);
        }
Exemplo n.º 40
0
 public void GivenAuthenticatedPostRequest_Redirects()
 {
     var model = new ResetPassword();
     ControllerUtilities.SetupControllerContext(Controller, User);
     var result = Controller.ResetPassword(model) as RedirectResult;
     result.Should().Not.Be.Null();
     result.Url.Should().Equal(Controller.Url.Home().Index());
     var notification = Controller.TempData[ViewDataConstants.Notification] as Notification;
     notification.Should().Not.Be.Null();
 }
Exemplo n.º 41
0
        public void GivenAnonymousPostRequest_WithValidId_IncrementsMetric()
        {
            var expectedObject = new PasswordRetrieval
                {
                    Token = Guid.NewGuid(),
                    UserId = User.Id
                };
            Db.Save(expectedObject);

            var model = new ResetPassword
                {
                    Token = expectedObject.Token,
                    Password = "******" + GetRandom.String(10),
                };
            model.PasswordConfirm = model.Password;

            var result = Controller.ResetPassword(model) as ViewResult;
            result.Should().Not.Be.Null();
            MetricsMock.Verify(x => x.Increment(Metric.Users_ResetPassword), Times.Once());
        }
Exemplo n.º 42
0
        public void GivenAnonymousPostRequest_WithValidData_UpdatesUserPassword()
        {
            var expectedObject = new PasswordRetrieval
                {
                    Token = Guid.NewGuid(),
                    UserId = User.Id
                };
            Db.Save(expectedObject);

            var model = new ResetPassword
                {
                    Token = expectedObject.Token,
                    Password = "******" + GetRandom.String(10),
                };
            model.PasswordConfirm = model.Password;
            Controller.ResetPassword(model);

            var user = Db.SingleOrDefault<User>(new { User.Id });
            user.Password.Should().Equal(model.PasswordConfirm.ToSHAHash());
        }
Exemplo n.º 43
0
        public async Task<ActionResult> ResetPassword(ResetPassword formModel)
        {
            var userId = GetCookieValue(Request, StorefrontConstants.CustomerIdCookie);
            var token = GetCookieValue(Request, StorefrontConstants.PasswordResetTokenCookie);

            if (userId == null && token == null)
            {
                WorkContext.ErrorMessage = "Not enough info for reseting password";
                return View("error", WorkContext);
            }

            var result = await _commerceCoreApi.StorefrontSecurityResetPasswordAsync(userId, token, formModel.Password);

            if (result.Succeeded == true)
            {
                // Remove cookies
                SetCookieValue(Response, StorefrontConstants.CustomerIdCookie);
                SetCookieValue(Response, StorefrontConstants.PasswordResetTokenCookie);

                return View("customers/reset_password_confirmation", WorkContext);
            }
            else
            {
                ModelState.AddModelError("form", result.Errors.First());
            }

            return View("customers/reset_password", WorkContext);
        }
Exemplo n.º 44
0
        public ActionResult ResetPassword(ResetPassword model)
        {
            if (User.Identity.IsAuthenticated)
            {
                NotifyInfo("You are already logged in. Log out and try again.");
                return Redirect(Url.Home().Index());
            }
            if (ModelState.IsValid)
            {
                model.Data = Db.SingleOrDefault<PasswordRetrieval>(new { model.Token });

                if (model.Data == null)
                {
                    NotifyWarning("Sorry! We couldn't verify that this user requested a password reset. Please try resetting again.");
                    return Redirect(Url.Account().ForgotPassword());
                }

                var user = Db.Query<User>("delete from [{0}] where Id=@resetId;update [{1}] set Password=@Password, ModifiedOn=GetUtcDate() where Id=@UserId;select * from [{1}] where Id=@UserId"
                    .Fmt(
                        Db.GetTableName<PasswordRetrieval>(),
                        Db.GetTableName<User>()
                    ), new
                        {
                            ResetId = model.Data.Id,
                            Password = model.Password.ToSHAHash(),
                            model.Data.UserId
                        }).SingleOrDefault();
                Cache.Trigger(TriggerFor.Id<User>(user.Id));
                _authenticationService.SetLoginCookie(user, true);

                Metrics.Increment(Metric.Users_ResetPassword);
                //show confirmation
                return View("ResetPasswordConfirmation");
            }
            return View(model);
        }
Exemplo n.º 45
0
        public async Task<ActionResult> ResetPassword(ResetPassword formModel)
        {
            var customerIdCookie = HttpContext.Request.Cookies[StorefrontConstants.CustomerIdCookie];
            string userId = customerIdCookie != null ? customerIdCookie.Value : null;

            var tokenCookie = HttpContext.Request.Cookies[StorefrontConstants.PasswordResetTokenCookie];
            string token = tokenCookie != null ? tokenCookie.Value : null;

            if (userId == null && token == null)
            {
                WorkContext.ErrorMessage = "Not enough info for reseting password";
                return View("error", WorkContext);
            }

            var result = await _commerceCoreApi.StorefrontSecurityResetPasswordAsync(userId, token, formModel.Password);

            if (result.Succeeded == true)
            {
                HttpContext.Response.Cookies.Add(new HttpCookie(StorefrontConstants.CustomerIdCookie) { Expires = DateTime.UtcNow.AddDays(-1) });
                HttpContext.Response.Cookies.Add(new HttpCookie(StorefrontConstants.PasswordResetTokenCookie) { Expires = DateTime.UtcNow.AddDays(-1) });

                return View("customers/reset_password_confirmation", WorkContext);
            }
            else
            {
                ModelState.AddModelError("form", result.Errors.First());
            }

            return View("customers/reset_password", WorkContext);
        }
Exemplo n.º 46
0
 public void UpdatePassword(ResetPassword command)
 {
     this.PasswordHash = command.PasswordHash;
     this.UpdateAt = command.CreateAt;
     this.UpdateBy = command.CreateBy;
 }
Exemplo n.º 47
0
        public async Task<IHttpActionResult> ResetPassword(ResetPasswordVM vm)
        {
            var userSecurity = _userSecurityService.Get(vm.User);
            if (!userSecurity.EnsoureState(UserSecurityCommand.ResetPassword))
            {
                return Conflict();
            }

            ResetPassword action = new ResetPassword(
            userSecurity.UserId, DateTime.Now, userSecurity.UserId, _userSecurityService.PasswordHash(userSecurity.UserId, vm.Password), vm.Token);
            ActionResponse actionResponse = await ActionBus.SendAsync<UserActionBase, ResetPassword>(action);
            return Ok(ActionResponseVM.ToVM(actionResponse));
        }
Exemplo n.º 48
0
        public ActionResult ResetPassword(string token)
        {
            if (User.Identity.IsAuthenticated)
            {
                NotifyInfo("You are already logged in. Log out and try again.");
                return Redirect(Url.Home().Index());
            }
            Guid guidToken;
            if (!Guid.TryParse(token, out guidToken))
            {
                NotifyWarning("Sorry! We couldn't verify that this user requested a password reset. Please try resetting again.");
                return Redirect(Url.Account().ForgotPassword());
            }

            var model = new ResetPassword
                {
                    Token = guidToken,
                    Data = Db.SingleOrDefault<PasswordRetrieval>(new { Token = guidToken })
                };

            if (model.Data == null)
            {
                NotifyWarning("Sorry! We couldn't verify that this user requested a password reset. Please try resetting again.");
                return Redirect(Url.Account().ForgotPassword());
            }

            return View(model);
        }
Exemplo n.º 49
0
        public void GivenAnonymousPostRequest_WithValidData_LogsInUser()
        {
            var expectedObject = new PasswordRetrieval
                {
                    Token = Guid.NewGuid(),
                    UserId = User.Id
                };
            Db.Save(expectedObject);

            var model = new ResetPassword
                {
                    Token = expectedObject.Token,
                    Password = "******" + GetRandom.String(10),
                };
            model.PasswordConfirm = model.Password;
            Controller.ResetPassword(model);

            AuthenticationService.Verify(x => x.SetLoginCookie(It.Is<User>(u => u.Id == User.Id), true), Times.Once());
        }
Exemplo n.º 50
0
        public void GivenAnonymousPostRequest_WithValidData_ReturnsView()
        {
            var expectedObject = new PasswordRetrieval
                {
                    Token = Guid.NewGuid(),
                    UserId = User.Id
                };
            Db.Save(expectedObject);

            var model = new ResetPassword
                {
                    Token = expectedObject.Token,
                    Password = "******" + GetRandom.String(10),
                };
            model.PasswordConfirm = model.Password;
            var result = Controller.ResetPassword(model) as ViewResult;
            result.Should().Not.Be.Null();
            result.ViewName.Should().Equal("ResetPasswordConfirmation");
        }
Exemplo n.º 51
0
 public void ClearResetPasswordToken(ResetPassword command)
 {
     this.ResetPasswordToken = null;
     this.UpdateAt = command.CreateAt;
     this.UpdateBy = command.CreateBy;
 }
Exemplo n.º 52
0
        public ActionResult ResetPassword(Guid token)
        {
            var model = new ResetPassword { Token = token };

            using (RavenSession.GetCachingContext())
            {
                model.Data = RavenSession.Query<PasswordRetrieval>().SingleOrDefault(x => x.Token == token);

                if (model.Data == null)
                    return Redirect(Url.Home().Index());

                return View(model);
            }
        }
Exemplo n.º 53
-1
        public ActionResult ForgotPassword(ForgotPasswordViewModelMyOwn model)
        {
            if (ModelState.IsValid)
            {
                ResetPassword RP = new ResetPassword();
                UserModel UM = new UserModel();
                UserManagerFK UMF = new UserManagerFK();
                string email = UMF.GetUserEmail(model.UserName);

                if (email == null)
                {

                    return View("ForgotPasswordConfirmation");
                }

                Guid EMailCode = Guid.NewGuid();
                var callbackUrl = Url.Action("ResetPassword", "UserAccount", new { userId = email, code = EMailCode }, protocol: Request.Url.Scheme);

                UMF.AddResetPasswordDetails(EMailCode, email, "Y");

                //SmtpClient SmtpClient = new SmtpClient("smtp.gmail.com");
                //MailAddressCollection MailAddressCollection = new MailAddressCollection();
                //MailMessage message = new MailMessage();
                //message.From = new MailAddress("*****@*****.**", "Faheem Kathrada");
                //message.Body = "Please reset your password by clicking < a href =\"" + callbackUrl + "\">here</a>";
                //message.Subject = "Nexidia Log Files";
                //message.To.Add("*****@*****.**");

                //SmtpClient.Port = 587;
                //SmtpClient.EnableSsl = true;
                //SmtpClient.Send(message);
                //message.Dispose();

                var client = new SmtpClient("smtp.gmail.com", 587)
                {
                    Credentials = new NetworkCredential("*****@*****.**", "8September@008"),
                    EnableSsl = true
                };
                client.Send("*****@*****.**", "*****@*****.**", "Password Reset", "Please reset your password by clicking < a href =\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            return View(model);
        }