예제 #1
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Nie ujawniaj informacji o tym, że użytkownik nie istnieje lub nie został potwierdzony
                    return(View("ForgotPasswordConfirmation"));
                }

                // Aby uzyskać więcej informacji o sposobie włączania potwierdzania konta i resetowaniu hasła, odwiedź stronę https://go.microsoft.com/fwlink/?LinkID=320771
                // Wyślij wiadomość e-mail z tym łączem
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Resetuj hasło", "Resetuj hasło, klikając <a href=\"" + callbackUrl + "\">tutaj</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Dotarcie do tego miejsca wskazuje, że wystąpił błąd, wyświetl ponownie formularz
            return(View(model));
        }
예제 #2
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

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

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #3
0
        public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                //var code = await _userManager.GeneratePasswordResetTokenAsync(user);
                //var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                //await _emailSender.SendEmailAsync(model.Email, "Reset Password",
                //   $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
                //return View("ForgotPasswordConfirmation");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #4
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // No revelar que el usuario no existe o que no está confirmado
                    return(View("ForgotPasswordConfirmation"));
                }

                // Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite https://go.microsoft.com/fwlink/?LinkID=320771
                // Enviar correo electrónico con este vínculo
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Restablecer contraseña", "Para restablecer la contraseña, haga clic <a href=\"" + callbackUrl + "\">aquí</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return(View(model));
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Não revelar que o usuário não existe ou não está confirmado
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Enviar um email com este link
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Redefinir senha", "Redefina sua senha, clicando <a href=\"" + callbackUrl + "\">aqui</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Se chegamos até aqui e houver alguma falha, exiba novamente o formulário
            return(View(model));
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Не показывать, что пользователь не существует или не подтвержден
                    return(View("ForgotPasswordConfirmation"));
                }

                // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: http://go.microsoft.com/fwlink/?LinkID=320771
                // Отправка сообщения электронной почты с этой ссылкой
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Сброс пароля", "Сбросьте ваш пароль, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return(View(model));
        }
예제 #7
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Ne révélez pas que l'utilisateur n'existe pas ou qu'il n'est pas confirmé
                    return(View("ForgotPasswordConfirmation"));
                }

                // Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
                // Envoyer un message électronique avec ce lien
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Réinitialiser le mot de passe", "Réinitialisez votre mot de passe en cliquant <a href=\"" + callbackUrl + "\">ici</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
            return(View(model));
        }
예제 #8
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // 请不要显示该用户不存在或者未经确认
                    return(View("ForgotPasswordConfirmation"));
                }

                // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771
                // 发送包含此链接的电子邮件
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "重置密码", "请通过单击 <a href=\"" + callbackUrl + "\">此处</a>来重置你的密码");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(View(model));
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Non rivelare che l'utente non esiste o non è confermato
                    return(View("ForgotPasswordConfirmation"));
                }

                // Per ulteriori informazioni su come abilitare la conferma dell'account e la reimpostazione della password, visitare http://go.microsoft.com/fwlink/?LinkID=320771
                // Inviare un messaggio di posta elettronica con questo collegamento
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Reimposta password", "Per reimpostare la password, fare clic <a href=\"" + callbackUrl + "\">qui</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Se si è arrivati a questo punto, significa che si è verificato un errore, rivisualizzare il form
            return(View(model));
        }
예제 #10
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // 不顯示使用者不存在或未受確認
                    return(View("ForgotPasswordConfirmation"));
                }

                // 如需如何進行帳戶確認及密碼重設的詳細資訊,請前往 https://go.microsoft.com/fwlink/?LinkID=320771
                // 傳送包含此連結的電子郵件
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "重設密碼", "請按 <a href=\"" + callbackUrl + "\">這裏</a> 重設密碼");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // 如果執行到這裡,發生某項失敗,則重新顯示表單
            return(View(model));
        }
        public void ForgotPassword_InvalidUserName_DoesntSendEmail_But_RedirectsTo_PasswordResetRequestedView()
        {
            // Arrange
            const string nonExistingUser = "******";

            _webSecurity.Setup(x => x.GetUserId(nonExistingUser)).Returns(-1);

            // Act
            var model = new ForgotPasswordViewModel
            {
                UserNameOrEmail = nonExistingUser
            };

            Mother.ControllerHelpers.SetupControllerModelState(model, _controllerUnderTest);
            var response = _controllerUnderTest.ForgotPassword(model);

            // Assert
            var result = response as RedirectToRouteResult;

            Assert.AreEqual("PasswordResetRequested", result.RouteValues["action"]);

            _messageService.Verify(x => x.SendMessage(It.IsAny <Message>(), It.IsAny <Person>(), It.IsAny <string>()), Times.Never);
        }
예제 #12
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            var response = new RequestStatus();

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

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

            if (user == null)
            {
                response.StatusCode = "1";
                response.Message    = "User not Found.";
                return(BadRequest("Invalid User"));
            }
            else
            {
                //User is Authenticated!
                var securityCode = CodeGenerator.ConfirmationString(10);
                user.ConfirmationCode = securityCode;
                await UserManager.UpdateAsync(user);

                response.StatusCode = "0";
                response.Message    = "Success";
                var message = new IdentityMessage
                {
                    Destination = model.Email,
                    Body        = string.Format("Dear <b>{0}</b>,<br/><br/>Please enter the below code to reset your KE Automated Communications System account password <br/><br/>Code: <b>{1}</b><br/><br/> Sincerely,<br/>Automated Communications Team", user.Name, user.ConfirmationCode), //string.Format("<a href=\"" + baseUrl + "/#/SetPassword\" target=\"_blank\">Reset Password link</a>"),
                    Subject     = "KE Automated Communications System- Password Reset Code"
                };
                await UserManager.EmailService.SendAsync(message);

                return(Ok(response));
            }
        }
예제 #13
0
        public async Task <IHttpActionResult> ForgotPassword([FromBody] ForgotPasswordViewModel info)
        {
            #region Parameter validation

            if (info == null)
            {
                info = new ForgotPasswordViewModel();
                Validate(info);
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            #endregion

            var students = UnitOfWork.RepositoryStudent.Search();
            var account  =
                await students.Where(x => x.Email.Equals(info.Email, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefaultAsync();

            // Check account exist or not
            if (account == null)
            {
                return(ResponseMessage(
                           Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.AccountNotFound)));
            }

            // Update account
            account.ForgotPassword = true;

            await UnitOfWork.CommitAsync();

            //            var mailTo = new MailAddress("*****@*****.**");
            //            _emailService.SendMail(new[]{ mailTo },"Hi", "Hello Dat",null, false, false);

            return(Ok(account));
        }
예제 #14
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                    MailMessage mail   = new MailMessage("*****@*****.**", user.Email);
                    SmtpClient  client = new SmtpClient();
                    client.Port                  = Globals.SMTPPort;
                    client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    client.UseDefaultCredentials = false;
                    client.Host                  = Globals.MailServer;
                    mail.IsBodyHtml              = true;
                    mail.Subject                 = "Reset mật khẩu tại phongdaotao.com";
                    mail.Body = "Chào bạn, xin vui lòng reset mật khẩu theo link <a href=\"" + callbackUrl + "\">sau</a>";
                    client.Send(mail);

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

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #15
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

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

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                //var from = "NYTracker<*****@*****.**>";
                //var email = new MailMessage(from, WebConfigurationManager.AppSettings["emailto"])
                //{
                //    Subject = "Padawan Prospect",
                //    Body = string.Format(body, model.FromName, model.FromEmail, model.Body),
                //    IsBodyHtml = true
                //};

                ////Instantiate and Invoke the email service
                //var svc = new EmailService();
                //bool result = await svc.SendMailAsync(email);

                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #16
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link


                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                var emailFrom = WebConfigurationManager.AppSettings["emailto"];
                var email     = new MailMessage(emailFrom, model.Email)
                {
                    Subject    = "Password reset request",
                    Body       = "Reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>",
                    IsBodyHtml = true
                };

                var emailServe = new PersonalEmail();
                await emailServe.SendAsync(email);

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #17
0
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        ApplicationUser user = null;
                        var             code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.Mobile);

                        var url = $"http://172.16.5.10:8800/?PhoneNumber={model.Mobile}&Text=Code:{code}&User=ravabetomomi&Password=ravabet123";
                        try
                        {
                            await new System.Net.Http.HttpClient().GetAsync(url);
                        }
                        catch (Exception)
                        {
                        }
                        return(RedirectToAction("ResetPassword", new { user = user.Id }));
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("", ex.Message);
                        return(View(model));
                    }
                }
                return(View(model));
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                return(View("~/Views/Shared/Error.cshtml", new ErrorViewModel {
                    RequestId = e.Message
                }));
            }
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("sifremi-unuttum"));
                }

                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("sifre-sifirla", "hesabim", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Şifre Sıfırlama", "Parolanızı bu linke tıklayarak sıfırlayabilirsiniz :" + callbackUrl);

                return(RedirectToAction("sifremi-unuttum-onay", "hesabim"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #19
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByEmailAsync(model.Email);

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

                // 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);

                //var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);

                return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #20
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    ModelState.AddModelError("", "Email not registred");
                    return(View(model));
                }
                else if (User != null)
                {
                    string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                    await UserManager.SendEmailAsync(user.Id, "Reset Password AK Hotel", "Reset your password by clicking <a href=\"" + callbackUrl + "\">Here</a>");

                    return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
                }
            }
            return(View(model));
        }
예제 #21
0
        public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {    
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByNameAsync(model.Email);
                if (user == null || !(await userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                var code = await userManager.GeneratePasswordResetTokenAsync(user);
                var resetUrl = Url.Action("ResetPassword", "Account", 
                    new { userId = user.Id.ToString(), code = code }, 
                    protocol: HttpContext.Request.Scheme);

                // await emailSender.SendPasswordResetEmailAsync(
                // not awaiting this awaitable method on purpose
                // so it does not delay the ui response
                // vs would show a warning squiggly line here if not for .Forget()
                //http://stackoverflow.com/questions/35175960/net-core-alternative-to-threadpool-queueuserworkitem
                //http://stackoverflow.com/questions/22629951/suppressing-warning-cs4014-because-this-call-is-not-awaited-execution-of-the
                emailSender.SendPasswordResetEmailAsync(
                    userManager.Site,
                    model.Email,
                    sr["Reset Password"],
                    resetUrl).Forget();
               
                return View("ForgotPasswordConfirmation");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #22
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    // Just show them a confirmation screen....muhhuuhhahahah
                    return(View("ForgotPasswordConfirmation"));
                }
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);

                await _emailSender.SendResetPasswordEmailAsync(EmailType.ResetPassword, user.Email, user.FirstName, callbackUrl);

                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #23
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByNameAsync(model.Email);

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

                    var passwordResetLink = Url.Action("ResetPassword", "Account", new { email = model.Email, token = token }, Request.Scheme);

                    SmtpClient client = new SmtpClient();
                    client.Connect("smtp.gmail.com", 465, true);
                    client.Authenticate(configuration["EmailUsernameSecret"], configuration["EmailPasswordsecret"]);

                    MimeMessage    message = new MimeMessage();
                    MailboxAddress from    = new MailboxAddress("Grant Shanklin", "*****@*****.**");
                    message.From.Add(from);
                    MailboxAddress to = new MailboxAddress(user.UserName, user.Email);
                    message.To.Add(to);
                    message.Subject = "Reset Password";
                    BodyBuilder bodyBuilder = new BodyBuilder();
                    bodyBuilder.TextBody = $"To reset your password, click on the link: {passwordResetLink}";
                    message.Body         = bodyBuilder.ToMessageBody();

                    client.Send(message);
                    client.Disconnect(true);
                    client.Dispose();

                    return(View("ForgotPasswordConfirmation"));
                }
                return(View("ForgotPasswordConfirmation"));
            }
            return(View(model));
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

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

                var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");

                ViewBag.Link = callbackUrl;
                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #25
0
        public ActionResult ForgotPassword(ForgotPasswordViewModel forgotPasswordViewModel)
        {
            if (!(ModelState.IsValid))
            {
                ModelState.AddModelError("UserEmail", "ایمیل را وارد کنید");
                return(View(forgotPasswordViewModel));
            }
            var user = _userService.GetUserByEmail(forgotPasswordViewModel.UserEmail);

            if (user == null)
            {
                ModelState.AddModelError("UserEmail", "این ایمیل یافت نشد");
                return(View(forgotPasswordViewModel));
            }
            string send = SendEmail.Send(user.UserEmail, "باز یابی کلمه عبور", _viewRenderService.RenderToStringAsync("_ForgotPassworEmail", user));

            if (send != "1")
            {
                ModelState.AddModelError("UserEmail", "خطا در ارسال ایمیل بازیابی ");
                return(View(forgotPasswordViewModel));
            }
            ViewBag.isSucsses = true;
            return(View());
        }
예제 #26
0
        public async Task ForgotPasswordPostReturnsForgotPasswordConfirmationView_WhenModelStateIsValid_AndUserIsNotNull_AndUsersEmailHasBeenVerified()
        {
            const string email = "*****@*****.**";
            var vm = new ForgotPasswordViewModel { Email = email };
            var userManager = CreateUserManagerMock();

            var user = new ApplicationUser();
            userManager.Setup(x => x.FindByNameAsync(email)).Returns(() => Task.FromResult(user));
            userManager.Setup(x => x.IsEmailConfirmedAsync(user)).Returns(() => Task.FromResult(true));
            userManager.Setup(x => x.GeneratePasswordResetTokenAsync(user)).Returns(() => Task.FromResult(It.IsAny<string>()));

            var sut = new AccountController(userManager.Object, null, null, Mock.Of<IMediator>(), null);
            sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
            sut.Url = Mock.Of<IUrlHelper>();
            var result = await sut.ForgotPassword(vm) as ViewResult;

            Assert.Equal(result.ViewName, "ForgotPasswordConfirmation");
        }
예제 #27
0
        public async Task ForgotPasswordPostInvokesUrlActionWithCorrectParameters_WhenModelStateIsValid_AndUserIsNotNull_AndUsersEmailHasBeenVerified()
        {
            const string requestScheme = "requestScheme";
            const string email = "*****@*****.**";
            var vm = new ForgotPasswordViewModel { Email = email };

            var userManager = CreateUserManagerMock();

            var user = new ApplicationUser();
            userManager.Setup(x => x.FindByNameAsync(email)).Returns(() => Task.FromResult(user));
            userManager.Setup(x => x.IsEmailConfirmedAsync(user)).Returns(() => Task.FromResult(true));
            userManager.Setup(x => x.GeneratePasswordResetTokenAsync(user)).Returns(() => Task.FromResult(It.IsAny<string>()));

            var sut = new AccountController(userManager.Object, null, null, Mock.Of<IMediator>(), null);
            var urlHelper = new Mock<IUrlHelper>();
            sut.SetFakeHttpRequestSchemeTo(requestScheme);
            sut.Url = urlHelper.Object;

            await sut.ForgotPassword(vm);

            urlHelper.Verify(mock => mock.Action(It.Is<UrlActionContext>(uac =>
                uac.Action == "ResetPassword"
                && uac.Controller == "Account"
                && uac.Protocol == requestScheme)), Times.Once);
        }
예제 #28
0
        public async Task ForgotPasswordPostReturnsForgotPasswordConfirmationView_WhenModelStateIsValid_AndUsersEmailIsUnverified()
        {
            const string email = "*****@*****.**";
            var vm = new ForgotPasswordViewModel { Email = email };

            var userManager = CreateUserManagerMock();

            var user = new ApplicationUser();
            userManager.Setup(x => x.FindByNameAsync(email)).Returns(() => Task.FromResult(user));
            userManager.Setup(x => x.IsEmailConfirmedAsync(user)).Returns(() => Task.FromResult(false));

            var sut = new AccountController(userManager.Object, null, null, null, null);
            var result = await sut.ForgotPassword(vm) as ViewResult;

            Assert.Equal(result.ViewName, "ForgotPasswordConfirmation");
        }
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    ModelState.AddModelError("", "Der Benutzer ist nicht vorhanden oder wurde nicht bestätigt.");
                    return View();
                }

                // Weitere Informationen zum Aktivieren der Kontobestätigung und Kennwortzurücksetzung finden Sie unter "http://go.microsoft.com/fwlink/?LinkID=320771".
                // E-Mail-Nachricht mit diesem Link senden
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);		
                // await UserManager.SendEmailAsync(user.Id, "Kennwort zurücksetzen", "Bitte setzen Sie Ihr Kennwort zurück. Klicken Sie dazu <a href=\"" + callbackUrl + "\">hier</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Wurde dieser Punkt erreicht, ist ein Fehler aufgetreten; Formular erneut anzeigen.
            return View(model);
        }
예제 #30
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    ModelState.AddModelError("", "El usuario no existe o no se ha confirmado.");
                    return View();
                }

                // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
                // Enviar correo electrónico con este vínculo
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);		
                // await UserManager.SendEmailAsync(user.Id, "Restablecer contraseña", "Para restablecer la contraseña, haga clic <a href=\"" + callbackUrl + "\">aquí</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario
            return View(model);
        }
예제 #31
0
        public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Email);
                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                // Send an email with this link
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code }, Request.Scheme);

                var message = new AuthMessageSender.Message
                {
                    Subject = "Reset Password",
                    Body = "Please reset your password by clicking:  <a href='" + callbackUrl + "'>this link</a>"
                };

                await _emailSender.SendEmailAsync(model.Email, message.Subject, message.Body, _userEmailAccount,
                    _userEmailPassword);

                return View("ForgotPasswordConfirmation");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #32
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                var person = await this.personManager.FindByNameAsync(model.Email);
                if (person == null || !person.EmailConfirmed)
                {
                    // Don't reveal that the person does not exist or is not confirmed
                    return this.View("ForgotPasswordConfirmation");
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                var code = await this.personManager.GeneratePasswordResetTokenAsync(person.Id);
                var email = await this.personManager.GetEmailAsync(person.Id);
                await this.emailManager.SendPasswordResetAsync(person.Id, code, email);
                return this.RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return this.View(model);
        }
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null)// || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
                    return View();
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);		
                SmtpClient myClient = new SmtpClient("smtp.gmail.com",25);
                myClient.UseDefaultCredentials = false;
                myClient.EnableSsl = true;
                myClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "ClintIsASillyWabbit");
                string to = user.Email;
                string from = "*****@*****.**";
                string subject = "STAPPPP password: Forgettable as Chris Farley's career?";
                string body = "You forgot your password.  Acknowledge your shame and move on by clicking the following link to reset your password: "******"ForgotPasswordConfirmation", "Account");

            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Email);
                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                //var code = await _userManager.GeneratePasswordResetTokenAsync(user);
                //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                //await _emailSender.SendEmailAsync(model.Email, "Reset Password",
                //   "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
                //return View("ForgotPasswordConfirmation");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #35
0
 public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
 {
     if (ModelState.IsValid)
     {
         var user = await UserManager.FindByNameAsync(model.Email);
         if (user != null && !(await UserManager.IsEmailConfirmedAsync(user.Id)))
         {
             try
             {
                 string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                 var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                 MailManager.sendPasswordResetEmail("Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>", user.Email);
                 return View("ForgotPasswordConfirmation");
             }
             catch (Exception)
             {
                 ModelState.AddModelError("", "Please! Try again.");
                 return View(model);
             }
         }
         else
         {
             ModelState.AddModelError("", "User does not exist.");
             return View(model);
         }
     }
     return View(model);
 }
예제 #36
0
 public ActionResult ForgotPassword(string id = null)
 {
     ForgotPasswordViewModel objForgotPasswordViewModel = new ForgotPasswordViewModel();
     if (id != null)
     {
         objForgotPasswordViewModel.Email = id;
         return View(objForgotPasswordViewModel);
     }
     else { return View(); }
 }
예제 #37
0
        public ForgotPassword()
        {
            InitializeComponent();

            BindingContext = new ForgotPasswordViewModel();
        }
예제 #38
0
        public virtual ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            string userName = membershipService.GetUserNameByEmail(model.Email);

            // Get the userName by the email address
            if (string.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("Email", "Email address does not exist. Please check your spelling and try again.");
                return(RedirectToAction("ForgotPassword"));
            }

            MembershipUser user = membershipService.GetUser(userName);

            if (user == null)
            {
                ModelState.AddModelError("", "The user does not exist.  Please check your entry and try again.");
                return(RedirectToAction("ForgotPassword"));
            }

            if (model.RequireSecretQuestionAndAnswer && model.Checked == false)
            {
                // Get the SecretQuestion
                model.SecretQuestion = user.PasswordQuestion;
                model.Checked        = true;

                return(RedirectToAction("EnterSecretAnswer", model));
            }

            if (model.RequireSecretQuestionAndAnswer && model.Checked == true)
            {
                if (string.IsNullOrEmpty(model.SecretAnswer))
                {
                    ModelState.AddModelError("SecretAnswer", "The Secret Answer is required.");
                    return(RedirectToAction("EnterSecretAnswer", model));
                }
            }



            // Now reset the password
            string newPassword = string.Empty;

            if (membershipService.RequiresQuestionAndAnswer)
            {
                try
                {
                    newPassword = user.ResetPassword(model.SecretAnswer);
                }
                catch (NullReferenceException)
                {
                    ModelState.AddModelError("PasswordAnswer", "The Secret Password is required.");
                    return(RedirectToAction("EnterSecretAnswer", model));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("PasswordAnswer", ex.Message);
                    return(RedirectToAction("EnterSecretAnswer", model));
                }
            }
            else
            {
                newPassword = user.ResetPassword();
            }

            // Email the new pasword to the user
            try
            {
                SmtpSection smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

                // Set the MailerModel properties that will be passed to the MvcMailer object.
                // Feel free to modify the properties as you need.
                MailerModel m = new MailerModel();
                m.UserName  = user.UserName;
                m.Password  = newPassword;
                m.FromEmail = smtp.From;
                m.Subject   = ConfigSettings.SecurityGuardEmailSubject;
                m.ToEmail   = model.Email;

                Mailer.PasswordReset(m).Send();
            }
            catch (Exception ex)
            {
                string a = ex.ToString();
            }

            return(RedirectToAction("ForgotPasswordSuccess"));
        }
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                var code = await _userManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                string subject = IdentityResourceHelper.Load(IdentitySettings.IdentityResource, "Notify_ForgotPassword_Subject");
                string bodyFormatString = IdentityResourceHelper.Load(IdentitySettings.IdentityResource, "Notify_ForgotPassword_Body");
                string body = string.Format(bodyFormatString, callbackUrl);
                await _userManager.SendEmailAsync(user.Id, subject, body);

                return View("ForgotPasswordConfirmation");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #40
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #41
0
        public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return Ok();
                }

                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                string urlencoded = HttpUtility.UrlEncode(code);
                //var callbackUrl = Url.Route("ResetPassword", new { userId = user.Id, code = code });
                var callbackUrl = "http://" + ConfigurationManager.AppSettings["Server"] + "/resetpassword/resetpassword/forgotpassword?userId=" + user.Id + "&Code=" + urlencoded;
                await UserManager.SendEmailAsync(user.Id, "Reset Password",
                   "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                return Ok();
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
예제 #42
0
    public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
    {
      if (ModelState.IsValid)
      {
        var user = await _userManager.FindByNameAsync(model.Email);
        if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
        {
          // Don't reveal that the user does not exist or is not confirmed
          return View("ForgotPasswordConfirmation");
        }

        //Send an email with this link
        var code = await _userManager.GeneratePasswordResetTokenAsync(user);
        var callbackUrl = Url.Action(new UrlActionContext
        {
          Action = nameof(ResetPassword),
          Controller = "Account",
          Values = new { userId = user.Id, code = code },
          Protocol = HttpContext.Request.Scheme
        });
        await _emailSender.SendEmailAsync(model.Email, "Reset allReady Password", $"Please reset your allReady password by clicking here: <a href=\"{callbackUrl}\">link</a>");

        return View("ForgotPasswordConfirmation");
      }

      // If we got this far, something failed, redisplay form
      return View(model);
    }
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    ModelState.AddModelError("", "用户不存在或未确认。");
                    return View();
                }

                // 有关如何启用帐户确认和密码重置的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=320771
                // 发送包含此链接的电子邮件
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);		
                // await UserManager.SendEmailAsync(user.Id, "重置密码", "请通过单击 <a href=\"" + callbackUrl + "\">此处</a>来重置你的密码");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return View(model);
        }
예제 #44
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Не показывать, что пользователь не существует или не подтвержден
                    return View("ForgotPasswordConfirmation");
                }

                // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: http://go.microsoft.com/fwlink/?LinkID=320771
                // Отправка сообщения электронной почты с этой ссылкой
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);		
                // await UserManager.SendEmailAsync(user.Id, "Сброс пароля", "Сбросьте ваш пароль, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return View(model);
        }
예제 #45
0
        public async Task<string> ajax_ForgotPassword(ForgotPasswordViewModel model)
        {
            ResultInfo rAjaxResult = new ResultInfo();

            try
            {
                if (ModelState.IsValid)
                {
                    var user = await UserManager.FindByEmailAsync(model.Email);
                    //2014-5-20 Jerry 目前本系統不作Email驗證工作
                    //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                    if (user == null)
                        throw new Exception(Resources.Res.Login_Err_Password);

                    string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                    var callbackUrl = Url.Action("ResetPassword", "MNGLogin", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await UserManager.SendEmailAsync(user.Id, "重設密碼", "請按 <a href=\"" + callbackUrl + "\">這裏</a> 重設密碼");

                    rAjaxResult.result = true;
                }
                else
                {
                    List<string> errMessage = new List<string>();
                    foreach (ModelState modelState in ModelState.Values)
                        foreach (ModelError error in modelState.Errors)
                            errMessage.Add(error.ErrorMessage);

                    rAjaxResult.message = String.Join(":", errMessage);
                    rAjaxResult.result = false;
                }
            }
            catch (Exception ex)
            {
                rAjaxResult.result = false;
                rAjaxResult.message = ex.Message;
            }

            return defJSON(rAjaxResult);
        }
예제 #46
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }
                //TODO: Generacion de codigo para ressetpassword
                var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                String body = IdentitySample.Common.Helper.Build_ForgotPassword(user.UserName, model.Email,callbackUrl);

                await UserManager.SendEmailAsync(user.Id, "Reestablecimiento de contraseña", body);
                ViewData["email"] = model.Email;
                ViewData["token"] = code;
                return View("ForgotPasswordConfirmation");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #47
0
        public async Task ForgotPasswordPostInvokesIsEmailConfirmedAsyncWithThecorrectUser_WhenModelStateIsValid()
        {
            const string email = "*****@*****.**";
            var vm = new ForgotPasswordViewModel { Email = email };

            var userManager = CreateUserManagerMock();

            var user = new ApplicationUser();
            userManager.Setup(x => x.FindByNameAsync(email)).Returns(() => Task.FromResult(user)).Verifiable();

            var sut = new AccountController(userManager.Object, null, null, null, null);
            await sut.ForgotPassword(vm);

            userManager.Verify(m => m.IsEmailConfirmedAsync(user), Times.Once);
        }
예제 #48
0
        public ActionResult ForgotPassword()
        {
            var model = new ForgotPasswordViewModel();

            return(View(model));
        }
예제 #49
0
        public async Task ForgotPasswordPostInvokesGeneratePasswordResetTokenAsyncWithCorrectUser_WhenModelStateIsValid_AndUserIsNotNull_AndUsersEmailHasBeenVerified()
        {
            const string email = "*****@*****.**";
            var vm = new ForgotPasswordViewModel { Email = email };

            var userManager = CreateUserManagerMock();

            var user = new ApplicationUser();
            userManager.Setup(x => x.FindByNameAsync(email)).Returns(() => Task.FromResult(user));
            userManager.Setup(x => x.IsEmailConfirmedAsync(user)).Returns(() => Task.FromResult(true));
            userManager.Setup(x => x.GeneratePasswordResetTokenAsync(user)).Returns(() => Task.FromResult(It.IsAny<string>()));

            var emailSender = new Mock<IEmailSender>();
            emailSender.Setup(x => x.SendEmailAsync(email, It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult(It.IsAny<Task>()));

            var sut = new AccountController(userManager.Object, null, null, Mock.Of<IMediator>(), null);

            sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
            sut.Url = Mock.Of<IUrlHelper>();

            await sut.ForgotPassword(vm);

            userManager.Verify(x => x.GeneratePasswordResetTokenAsync(user), Times.Once);
        }
예제 #50
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }


                try
                {
                    string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                    var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    var mailer = new Mailer();
                    mailer.Mail(model.Email, "Glömt lösenord till Fuji", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                }
                catch (Exception)
                {

                    return View(model);
                }



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

            // If we got this far, something failed, redisplay form;
            return View(model);
        }
예제 #51
0
        public async Task ForgotPasswordPostSendsSendResetPasswordEmailWithCorrectParameters_WhenModelStateIsValid_AndUserIsNotNull_AndUsersEmailHasBeenVerified()
        {
            const string email = "*****@*****.**";
            const string callbackUrl = "callbackUrl";

            var vm = new ForgotPasswordViewModel { Email = email };
            var userManager = CreateUserManagerMock();

            var user = new ApplicationUser();
            userManager.Setup(x => x.FindByNameAsync(email)).Returns(() => Task.FromResult(user));
            userManager.Setup(x => x.IsEmailConfirmedAsync(user)).Returns(() => Task.FromResult(true));
            userManager.Setup(x => x.GeneratePasswordResetTokenAsync(user)).Returns(() => Task.FromResult(It.IsAny<string>()));

            var mediator = new Mock<IMediator>();

            var sut = new AccountController(userManager.Object, null, null, mediator.Object, null);
            var urlHelper = new Mock<IUrlHelper>();
            urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(callbackUrl);
            sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>());
            sut.Url = urlHelper.Object;

            await sut.ForgotPassword(vm);

            mediator.Verify(x => x.SendAsync(It.Is<SendResetPasswordEmail>(y => y.Email == vm.Email && y.CallbackUrl == callbackUrl)), Times.Once);
        }
예제 #52
0
        public async Task<ActionResult> ResendConfirmEmail(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.GaTechId);
                if (user == null)
                {
                    ModelState.AddModelError("", string.Format("{0} does not exist.", model.GaTechId));
                    return View();
                }

                if ((await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    ModelState.AddModelError("", string.Format("{0} has already been confirmed.", user.Email));
                    return View();
                }

                return await SendAccountConfirmationEmail(user);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #53
0
        public async Task ForgotPasswordPostReturnsTheSameViewAndViewModel_WhenModelStateIsInvalid()
        {
            var vm = new ForgotPasswordViewModel();

            var sut = CreateAccountControllerWithNoInjectedDependencies();
            sut.AddModelStateError();

            var result = await sut.ForgotPassword(vm) as ViewResult;
            var modelResult = result.ViewData.Model as ForgotPasswordViewModel;

            Assert.IsType<ViewResult>(result);
            Assert.IsType<ForgotPasswordViewModel>(modelResult);
            Assert.Same(modelResult, vm);
        }
        public async Task <IdentityResult> ForgotPassword(ForgotPasswordViewModel forgotPasswordModel)
        {
            var result = await service.ForgotPassword(forgotPasswordModel.Id, forgotPasswordModel.NewPassword);

            return(result);
        }
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (model == null) throw new ArgumentNullException("model");

            if (ModelState.IsValid)
            {
                string resetToken;
                try
                {
                    resetToken = WebSecurity.GeneratePasswordResetToken(model.Email);
                }
                catch (Exception)
                {
                    TempData["Message"] = "Пользователя с таким Email не существует.";
                    return View(model);
                }
                try
                {
                    EmailManager.SendForgotPasswordEmail(model.Email, @Url.Action("ResetPassword", "Account",
                                                                                  new {id = resetToken},
                                                                                  Request.Url != null
                                                                                      ? Request.Url.Scheme
                                                                                      : null));
                    TempData["Message"] =
                        "На ваш электронный ящик отправлено письмо с дальнейшими инструкциями по восстановлению пароля. "
                        + "Проверьте ваш электронный ящик.";
                }
                catch (Exception)
                {
                    TempData["Message"] = "Ошибка при отправке сообщения. Обратитесь к администратору.";
                }
            }
            return View(model);
        }
예제 #56
0
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    SetRequestURL(APIURL.APPLICANT_FORGOT_PASSWORD, Method.POST);
                    request.AddBody(model);
                    var response = rest.Execute(request);

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        SetMessage("An instruction for resetting your password has been sent on your email.", MESSAGE_TYPE.INFO);
                        return RedirectToAction("ForgotPassword");
                    }
                    else
                    {
                        ModelState.AddModelError("", response.Content);
                    }

                }
            }
            catch (CustomException ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return View(model);
        }
예제 #57
0
        public Task <ActionResult> ForgotPasswordTest01([PexAssumeUnderTest] AccountController target, ForgotPasswordViewModel model)
        {
            Task <ActionResult> result = target.ForgotPassword(model);

            return(result);
            // TODO: aggiungere asserzioni a metodo AccountControllerTest.ForgotPasswordTest01(AccountController, ForgotPasswordViewModel)
        }
		public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordViewModel model) {
			if (!ModelState.IsValid) return BadRequest(ModelState);

			var user = await UserManager.FindByNameAsync(model.Email);
			if (user == null) {
				// Don't reveal that the user does not exist or is not confirmed
				ModelState.AddModelError("", "That user does not exist");
				return BadRequest(ModelState);
			}

			var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
			var callbackUrl = Utility.AbsoluteUrl("/ResetPassword?code="+HttpUtility.UrlEncode(code));
			await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
			return Ok(new { message = "We've emailed you a link to reset your password!" });
		}
예제 #59
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
                    return View();
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);		
                // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #60
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model, string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;

            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);
                if (user == null)
                    // Не показывать, что пользователь не существует или не подтвержден
                    return View("ForgotPasswordConfirmation");
                _logger.Trace($"User \"{user.UserName}\" send request to reset password.");

                //Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см.по адресу: http://go.microsoft.com/fwlink/?LinkID=320771
                //Отправка сообщения электронной почты с этой ссылкой
                string token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, token }, protocol: Request.Url.Scheme);

                var emailModel = new
                {
                    UserName = user.UserName,
                    CallbackUrl = callbackUrl
                };

                string body = await EmailBodyServiceFactory.GetEmailBody(emailModel, "ForgotPassword");
                await UserManager.SendEmailAsync(user.Id, "Відновлення пароля", body);
                _logger.Debug($"Send verification email to {user.UserName} for reset password.");

                return View("ForgotPasswordConfirmation");
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return View(model);
        }