public async Task <IActionResult> ForgotPassword(ForgottenPassword input)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(input.Email);

                if (user == null)// || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    ViewData["NoEmail"] = "No account for that email address exists";
                    return(View());
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                code = WebUtility.UrlEncode(code);
                var callbackUrl = $"{this.Request.Scheme}://{this.Request.Host}/ResetPassword?code={code}";
                //var callbackUrl = Url.Action("ResetPassword", "ApplicationUser", new { code });

                await _emailSender.SendEmailAsync(
                    input.Email,
                    "Reset Password",
                    $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                return(Redirect("/ForgotPasswordConfirmation"));
            }

            return(View());
        }
Пример #2
0
 public ActionResult Create(ForgottenPassword Model)
 {
     return Dispatcher.Create(
         DataModel: Model,
         SuccessResult: m => RedirectToAction("Create", "Login"),
         InvalidResult: m => View(m));
 }
        public ActionResult HandleForgottenPasswordForm(ForgottenPasswordForm forgottenPasswordForm)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.CurrentUmbracoPage());
            }

            IPartier partier = this.Members.GetByUsername(forgottenPasswordForm.EmailAddress) as IPartier;

            if (partier != null)
            {
                Guid forgottenPasswordGuid = Guid.NewGuid();

                partier.ForgottenPasswordGuid = forgottenPasswordGuid;

                ForgottenPassword forgottenPassword = (ForgottenPassword)this.CurrentPage;

                MailMessage mailMessage = new MailMessage();

                mailMessage.From = new MailAddress(forgottenPassword.ServerEmailAddress);
                mailMessage.To.Add(new MailAddress(partier.Email));
                mailMessage.Subject    = forgottenPassword.EmailSubject;
                mailMessage.IsBodyHtml = true;

                mailMessage.Body = forgottenPassword.EmailBody.Replace("[%RESET_PASSWORD_LINK%]", this.Request.Url.Scheme + "://" + this.Request.Url.Host.ToLower() + this.Umbraco.TypedContentSingleAtXPath("//" + ResetPassword.Alias).Url + "?forgottenPasswordGuid=" + forgottenPasswordGuid.ToString("D"));

                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.Send(mailMessage);
                }
            }

            return(this.View("ForgottenPassword/Complete", this.CurrentPage));
        }
Пример #4
0
        public Response <RequestPasswordResetDto> RequestPasswordReset(RequestPasswordResetRequest request)
        {
            try
            {
                SetUserRepositoryByEmail(request.EmailAddress);

                var user = _userRepository.FindUserByEmail(request.EmailAddress);

                if (user == null)
                {
                    throw new ServiceException(ResponseCode.NotFound, "Selected Agents does not exist.");
                }

                var expiryLength = _settingRepository.FindSettingAsInt(SettingName.PasswordResetLength);

                var passwordResetRequest = new ForgottenPassword(Guid.NewGuid());

                user.AddPasswordResetRequest(passwordResetRequest, expiryLength);

                _userRepository.Save();

                var dto = new RequestPasswordResetDto
                {
                    UserGuid = user.UserGuid,
                    Key      = passwordResetRequest.Key
                };

                return(new Response <RequestPasswordResetDto>(dto));
            }
            catch (Exception e)
            {
                return(HandleException <RequestPasswordResetDto>(e));
            }
        }
Пример #5
0
        public void ForgottenPasswordCheckUserAndShowAnswerView()
        {
            //ARRANGE
            const string userName = "******";
            var          model    = new ForgottenPassword {
                UserName = userName
            };

            var userLogic = new Mock <IUserLogic>();

            userLogic.Setup(x => x.FindByName(userName))
            .Returns(new User())
            .Verifiable("shoud get teh user to populate the model");

            var controller = new AccountController(userLogic.Object, null, null);

            var result = controller.ForgottenPassword(model) as ViewResult;

            //ASSERT
            userLogic.Verify();

            Assert.NotNull(result);
            Assert.NotNull(result.Model);
            Assert.That(result.ViewName, Is.EqualTo("AnswerQuestion"));
        }
        public void IsExpiredFalse()
        {
            _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));

            var result = _forgottenPassword.IsExpired(2);

            Assert.AreEqual(false, result);
        }
        public void ConstructorSuccessfulTest()
        {
            _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));

            Assert.IsNotNull(_forgottenPassword.Key);
            Assert.GreaterOrEqual(DateTime.Now, _forgottenPassword.Created);
            Assert.AreEqual(false, _forgottenPassword.Used);
        }
        public void IsValidFalseIsExpiredTest()
        {
            _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));
            Thread.Sleep(2000);

            var result = _forgottenPassword.IsValid(0);

            Assert.AreEqual(false, result);
        }
Пример #9
0
        public DateTime RequestDate(string key)
        {
            ForgottenPassword selectedItem = _forgottenPasswords.FirstOrDefault(x => x.Key == key);

            if (selectedItem != null)
            {
                return(selectedItem.ResetDateTime);
            }
            throw new ArgumentException("This Key is not exist", "key");
        }
        public void UseDomainValidationExceptionExpiredTest()
        {
            _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));
            Thread.Sleep(2000);

            Assert.Throws <DomainValidationException>(() =>
            {
                _forgottenPassword.Use(0);
            });
        }
Пример #11
0
        public User FindUser(string key)
        {
            ForgottenPassword selectedItem = _forgottenPasswords.FirstOrDefault(x => x.Key == key);

            if (selectedItem != null)
            {
                return(selectedItem.User);
            }
            throw new ArgumentException("This Key is not exist", "key");
        }
Пример #12
0
        public void AddPasswordRequestDomainValidationExceptionExpiredTest()
        {
            _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));
            Thread.Sleep(2000);

            Assert.Throws <DomainValidationException>(() =>
            {
                _user.AddPasswordResetRequest(_forgottenPassword, 0);
            });
        }
        public void IsExpiredTrue()
        {
            _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));

            Thread.Sleep(2000);

            var result = _forgottenPassword.IsExpired(0);

            Assert.AreEqual(true, result);
        }
Пример #14
0
        public void IsValidKeyFalseExpiredTest()
        {
            _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));

            _user.AddPasswordResetRequest(_forgottenPassword, 5);
            Thread.Sleep(2000);

            var result = _user.IsValidKey(_forgottenPassword.Key, 0);

            Assert.AreEqual(false, result);
        }
Пример #15
0
        public void AddPasswordRequestSuccessfulHasOtherActiveResetRequestsTest()
        {
            var firstRequest = new ForgottenPassword(new Guid(ForgottenPasswordGuid));

            _user.AddPasswordResetRequest(firstRequest, 5);
            _user.AddPasswordResetRequest(_forgottenPassword, 5);

            Assert.IsNotEmpty(_user.ForgottenPasswords);
            Assert.Contains(firstRequest, _user.ForgottenPasswords.ToList());
            Assert.Contains(_forgottenPassword, _user.ForgottenPasswords.ToList());
            Assert.AreEqual(true, firstRequest.Used);
        }
Пример #16
0
 public IActionResult ForgetPassword(ForgottenPassword forgottenPassword)
 {
     // is Admin [Master] Code
     if (forgottenPassword.VerificationCode.Length == 10)
     {
         // if the code doesn't match the Master Code return Exception [BadRequest]
         if (forgottenPassword.VerificationCode != _config.GetValue <string>("MasterVerificationCode"))
         {
             throw new Exception("Invalid Verification Code!!!");
         }
         user = _service.Find <User, string>(forgottenPassword.UserId);
         // (_) If user not found then return Exception [BadRequest]
         if (user == null)
         {
             throw new Exception("Invalid User !!!");
         }
         // (_) if user and code ok then Change Password with the new one
         return(_DoChangePassword(user, forgottenPassword.NewPassword));
     }
     // is User [email - sms] Code
     else
     {
         // (_) Get User by UserId Including all its VerificationCodes
         user = _service.GetOne <User>(new List <string>()
         {
             "VerificationCodes"
         }, u => u.UserId == forgottenPassword.UserId);
         // (_) If user not found then return [BadRequest]
         if (user == null)
         {
             throw new Exception("Invalid User !!!");
         }
         // (_) Get VerificationCodeLifetime in Hours from AppSettings
         int codeLifetime = _config.GetValue <int>("VerificationCodeLifetime");
         // (_) Get VerificationCode where code = forgottenPassword.VerificationCode
         // and CodeTypeId == 1 [FORGET_PASSWORD] and not expired
         var code = user.VerificationCodes.FirstOrDefault(vc =>
                                                          vc.Code == forgottenPassword.VerificationCode &&
                                                          vc.SentTime >= DateTime.UtcNow.AddHours(3 - codeLifetime) &&
                                                          vc.CodeTypeId == 1
                                                          );
         // (_) if code not found then return [BadRequest]
         if (code == null)
         {
             throw new Exception("Invalid OR Expired VerificationCode !!!");
         }
         // (_) if user and code ok then Change Password with the new one
         return(_DoChangePassword(user, forgottenPassword.NewPassword));
     }
 }
Пример #17
0
        public virtual ActionResult Index(ForgottenPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView(MVC.ForgottenPassword.Views._Index, model));
            }

            bool isEmailExist = _userService.ExistsByEmail(model.Email);

            if (isEmailExist)
            {
                User   selecteduser     = _userService.GetUserByEmail(model.Email);
                string key              = Guid.NewGuid().ToString();
                var    newRequestTicket = new ForgottenPassword
                {
                    User          = selecteduser,
                    Key           = key,
                    ResetDateTime = DateAndTime.GetDateTime()
                };

                _forgttenPasswordService.Add(newRequestTicket);

                if (_emailService.SendResetPasswordConfirmationEmail(selecteduser.UserName, model.Email, key)
                    == SendingMailResult.Successful)
                {
                    _uow.SaveChanges();
                }
                else
                {
                    return(Json(new
                    {
                        result = "true",
                        message = "متاسفانه خطایی در ارسال ایمیل رخ داده است."
                    }));
                }

                return(Json(new
                {
                    result = "true",
                    message = "ایمیلی برای تایید بازنشانی کلمه عبور برای شما ارسال شد.اعتبارایمیل ارسالی 24 ساعت است."
                }));
            }

            return(Json(new
            {
                result = "false",
                message = "این ایمیل در سیستم ثبت نشده است"
            }));
        }
Пример #18
0
        public void UpdatePasswordWithKeyDomainValidationExceptionExpiredTest()
        {
            _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));

            _user.AddPasswordResetRequest(_forgottenPassword, 5);
            Thread.Sleep(2000);

            Assert.Throws <DomainValidationException>(() =>
            {
                _user.UpdatePasswordWithKey(_forgottenPassword.Key, 0, "Password2");
            });

            var validateResult = _user.ValidatePassword("Password2");

            Assert.AreEqual(false, validateResult);
        }
Пример #19
0
        public ActionResult ForgottenPassword(ForgottenPassword model)
        {
            var ctx2 = PTFReportsContext.Current;
            var isOk = ctx2.SetPasswordForgotten(model.usr, model.eml);

            if (isOk)
            {
                var path = Server.MapPath("~/Views/Account/ForgottenPassword.htm");
                var text = io.File.ReadAllText(path);
                var str  = Url.Encode(string.Concat(model.usr, ";", model.eml, ";", DateTime.Now.ToString("g")).Encript());
                text = string.Format(text, str);
                EmailSender.Send(model.eml, "PTFReports password recovery service", text, true);
                return(View("ForgottenPasswordSuccess"));
            }
            return(View("ForgottenPasswordFailure"));
        }
Пример #20
0
        public void RemindPassword(String emailAddress)
        {
            if (String.IsNullOrEmpty(emailAddress))
            {
                throw new ArgumentNullException("emailAddress");
            }

            var member = Member.GetMemberByEmail(emailAddress);

            if (member == null)
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.Argument_EmailAddressNotExist, emailAddress));
            }

            ForgottenPassword.RemindPassword(member.MemberID, emailAddress);
        }
 public IActionResult ForgetPassword(ForgottenPassword forgottenPassword)
 {
     // if the code doesn't match the Master Code return Exception [BadRequest]
     if (forgottenPassword.VerificationCode != _config.GetValue <string>("MasterVerificationCode"))
     {
         throw new Exception("Invalid Verification Code!!!");
     }
     // get the user by Email
     user = _service.Find <User, string>(forgottenPassword.Email);
     // (_) If user not found then return Exception [BadRequest]
     if (user == null)
     {
         throw new Exception("Invalid User !!!");
     }
     // (_) if user and code ok then Change Password with the new one
     return(_DoChangePassword(user, forgottenPassword.NewPassword));
 }
Пример #22
0
        public ActionResult ForgottenPassword(ForgottenPassword model)
        {
            try
            {
                var token = WebSecurity.GeneratePasswordResetToken(model.Email, 10);
                var url   = String.Format("{0}/account/RestoreForgottenPassword?token={1}", WebConfigurationManager.AppSettings["AppHost"], token);
                var href  = String.Format("<a href=\"{0}\">Go to restore password page</a>", url);
                using (var mail = new MailMessage())
                {
                    mail.From = new MailAddress(WebConfigurationManager.AppSettings["SmtpSenderMail"], WebConfigurationManager.AppSettings["SmtpSenderName"]);
                    mail.To.Add(new MailAddress(model.Email));
                    mail.Subject = "Offwind password restore [" + model.Email + "]";

                    var text = new StringBuilder();
                    text.AppendFormat("You received this message because you have requested a password restore. If it wasn't you just ignore this message.<br /><br />");
                    text.AppendFormat("{0}", href);
                    mail.Body       = text.ToString();
                    mail.IsBodyHtml = true;

                    var smtpClient = new SmtpClient
                    {
                        Host                  = WebConfigurationManager.AppSettings["SmtpHost"],
                        Port                  = Convert.ToInt32(WebConfigurationManager.AppSettings["SmtpHostPort"]),
                        EnableSsl             = Convert.ToBoolean(WebConfigurationManager.AppSettings["SmtpEnableSSL"]),
                        DeliveryMethod        = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials =
                            Convert.ToBoolean(WebConfigurationManager.AppSettings["SmtpUseDefaultCredentialas"]),
                        Credentials = new NetworkCredential()
                        {
                            UserName = WebConfigurationManager.AppSettings["SmtpSenderMail"],
                            Password = WebConfigurationManager.AppSettings["SmtpSenderPswd"]
                        }
                    };
                    smtpClient.Send(mail);
                }
            }
            catch (Exception)
            {
                ViewBag.UserNotFound = true;
                return(View());
            }
            ViewBag.UserNotFound = false;
            return(View());
        }
Пример #23
0
        public async Task <ActionResult> ForgotPassword(ForgottenPassword model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    //ModelState.AddModelError("", "Email doesn't exist");
                    ViewBag.SuccessMessage = $"An email will be sent to the specified address with instructions on how to reset your password, if the address matches our records";
                    return(View(model));
                }

                var token = Guid.NewGuid().ToString();

                var meta = new PuckMeta {
                    Name    = DBNames.PasswordResetToken
                    , Key   = token
                    , Value = model.Email
                };
                repo.AddMeta(meta);
                repo.SaveChanges();

                var uri      = HttpContext.Request.GetUri() ?? PuckCache.FirstRequestUrl;
                var resetUrl = uri.Scheme + "://"
                               + uri.Host
                               + (uri.Port != 80 ? (":" + uri.Port) : "")
                               + $"/puck/admin/resetpassword?token={token}";

                puck.core.Helpers.ApiHelper.Email(
                    model.Email
                    , "Reset your password - Puck CMS"
                    , $"click <a href=\"{resetUrl}\">here</a> to reset your password."
                    );

                ViewBag.SuccessMessage = $"An email will be sent to the specified address with instructions on how to reset your password, if the address matches our records";

                return(View(model));
            }
            return(View(model));
        }
Пример #24
0
    protected void btnSend_Click(object sender, EventArgs e)
    {
        Member ForgetfulMember = Member.GetMemberByEmail(txtEmail.Text);

        // if the address is not available then the user is valid
        if (ForgetfulMember != null)
        {
            ForgottenPassword forgottenPassword = new ForgottenPassword();
            forgottenPassword.EmailAddress = txtEmail.Text;
            forgottenPassword.IPAddress    = HttpContext.Current.Request.UserHostAddress;
            forgottenPassword.DTCreated    = DateTime.Now;
            forgottenPassword.MemberID     = ForgetfulMember.MemberID;
            forgottenPassword.Save();

            PasswordSent = true;
        }
        else
        {
            // that email address does not exist
            libMessage.Text = "<p class='error_alert'>Sorry, we do not have an account with that email</p>";
        }
    }
 public void SetUp()
 {
     _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));
 }
Пример #26
0
 public void SetUp()
 {
     _user = new User(Guid.NewGuid(), "Name", "EmailAddress", "Password");
     _forgottenPassword = new ForgottenPassword(new Guid(ForgottenPasswordGuid));
 }
Пример #27
0
        public void Test_ForgottenPasswordClass_EmailPasswordMethod_Retruns_true_For_Valid_Username()
        {
            ForgottenPassword pswd = new ForgottenPassword();

            Assert.IsTrue(pswd.EmailPassword("kimberley.jackson"));
        }
Пример #28
0
 public void Add(ForgottenPassword model)
 {
     _forgottenPasswords.Add(model);
 }