Пример #1
0
        public ActionResult Forgotten(ForgottenPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var user = this._userService.GetApplicationUser(model.UserName);

                if (user == null)
                {
                    TempData["message"] = "Please contact your administrator.";
                    return(View(model));
                }

                if (this._securityAnswerService.HasSecurityAnswers(user.Id))
                {
                    TempData["UserId"] = user.Id;
                    return(RedirectToAction("SecurityQuestions", "Password"));
                }
                else
                {
                    TempData["message"] = "Please contact your administrator.";
                    return(View(model));
                }
            }
            else
            {
                TempData["message"] = "Please correct the errors and try again.";
                return(View(model));
            }
        }
Пример #2
0
        public ActionResult ForgottenPassword(ForgottenPasswordModel forgottenPasswordModel)
        {
            if (!ModelState.IsValid)
            {
                return View(forgottenPasswordModel);
            }

            var user = _userManager.Get(new User { UserName = forgottenPasswordModel.Username.ToLower() });
            _logger.Info("Model.usernname " + forgottenPasswordModel.Username + "User email address " + user.Email);
            if (!string.IsNullOrWhiteSpace(user.UserName))
            {
                _userManager.CreateToken(user, new TimeSpan(0, 3, 0, 0));
                _logger.Info("After Creating Token: Model.usernname " + forgottenPasswordModel.Username + "User email address " + user.Email);
                try
                {
                    UserMailer.PasswordReset(user, new Uri(Url.Action("ResetPassword", null, null, Request.Url.Scheme))).Send();
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);

                }
            }

            SetRedirectMessage(MessageKey.PasswordResetEmailSent);

            return RedirectToAction("SignIn");
        }
        public ActionResult ForgottenPassword(ForgottenPasswordModel model)
        {
            bool   status = true;
            string exMsg  = "";

            if (ModelState.IsValid)
            {
                SystemSettingsRepository sysRepo = new SystemSettingsRepository();
                var sys = sysRepo.GetSystemSettings();
                using (DBEntities db = new DBEntities())
                {
                    Users user = db.Users.FirstOrDefault(u => u.EmailAddress == model.Email);
                    if (user != null)
                    {
                        //Now Send an Email to User for Username and Password!
                        if (sys.EmailsEnabled)
                        {
                            try
                            {
                                //Random rndm = new Random();
                                //var RandomNum = rndm.Next(10001, int.MaxValue);
                                Guid   guid = Guid.NewGuid();
                                string EncryptedRandomNum = guid.ToString();
                                SecurityUtils.CheckforInvalidFileNameChar(ref EncryptedRandomNum); //it will remove any unsupported characters
                                user.PasswordResetCode = EncryptedRandomNum;
                                user.ResetCodeExpiry   = DateTime.Now.AddHours(2);
                                db.SaveChanges();

                                status = SendEmail(user, EncryptedRandomNum);
                            }
                            catch (Exception ex)
                            {
                                ViewBag.status = "Failed to send an Email. Please contact your Site Administrator" + ex.Message;
                                exMsg          = ex.Message;
                            }

                            if (status)
                            {
                                //Add To Log
                                SecurityUtils.AddAuditLog("Requested for Forgotten Password", "User \"" + user.FullName + "\" requested for Forgotten Password , Email Sent to: \"" + user.EmailAddress + "\"", this);
                                ViewBag.status = "Your Login Details has been sent to above email address. <a style='color:black' href='/Account/Logon'> Log On </a>";
                            }
                            else
                            {
                                ViewBag.status = "Failed to send an Email. Please contact your Site Administrator." + exMsg + " - " + EmailsRepository.EmailErrorMsg;
                            }
                        }
                    }
                    else
                    {
                        ViewBag.status = "Your provided email address is not valid. Please contact site Administrator.";
                    }
                }
            }

            return(View());
        }
Пример #4
0
        public void WhenISubmitForgottenPasswordPage_AndUserNameFieldIsEmpty_ThenTheForgottenViewShouldContainTheModel()
        {
            var model = new ForgottenPasswordModel();

            _controller.ModelState.AddModelError("UserName", "UserName is required");

            var result = (ViewResult)this._controller.Forgotten(model);

            result.Model.Should().BeOfType <ForgottenPasswordModel>();
            result.TempData["message"].ToString().ShouldBeEquivalentTo("Please correct the errors and try again.");
        }
Пример #5
0
        public void WhenISubmitForgottenPasswordPage_IfModelStateIsValidButUserDoesNotExist_ThenTheForgottenViewShouldContainTheModel()
        {
            var model = new ForgottenPasswordModel();

            this._userService.Setup(x => x.GetApplicationUser(It.IsAny <string>())).Returns(It.IsAny <ApplicationUser>());

            var result = (ViewResult)this._controller.Forgotten(model);

            this._userService.Verify(x => x.GetApplicationUser(It.IsAny <string>()), Times.AtLeastOnce);
            result.Model.Should().BeOfType <ForgottenPasswordModel>();
            result.TempData["message"].ToString().ShouldBeEquivalentTo("Please contact your administrator.");
        }
Пример #6
0
        //id = DashboardURLId
        public ActionResult ForgottenPassword(string id)
        {
            ViewBag.status = "";
            ForgottenPasswordModel model = new ForgottenPasswordModel()
            {
                DashboardURLId = id
            };

            ViewBag.ModelIsLogin = true;

            return(View(model));
        }
        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 = "این ایمیل در سیستم ثبت نشده است"
            }));
        }
Пример #8
0
        public ActionResult HandleForgottenPassword(ForgottenPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(CurrentUmbracoPage());
            }

            var memberService = Services.MemberService;
            //Find the member with the email address
            var member = memberService.GetByEmail(model.EmailAddress);

            if (member.Username != null)
            {
                //Set expiry date to 48 hours from now
                DateTime expiryTime = DateTime.Now.AddHours(48);

                //update the resetPasswordToken property for the member
                var token = Guid.NewGuid();
                member.SetValue("ResetPasswordToken", token);
                member.SetValue("ResetPasswordExpireDate", expiryTime);

                //    //Save the member with the up[dated property value
                memberService.Save(member);
                ViewData["Saved"] = "saved";
                var firstHalfEmail  = "<!DOCTYPE HTML><html xmlns='http://www.w3.org/1999/xhtml' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office'><head><title>Reset Password</title> <!--[if !mso]><!-- --><meta http-equiv='X-UA-Compatible' content='IE=edge'> <!--<![endif]--><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1'><style type='text/css'>#outlook a{padding:0}body{margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}table,td{padding:20px;border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt}img{border:0;height:auto;line-height:100%;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic}.h1{font-size:36px;font-weight:700;color:#153558;letter-spacing:0;line-height:43px;margin-bottom:0}p{font-family:'Open Sans',sans-serif;font-size:18px;line-height:1.666em;font-weight:400;color:#254151;display:block;margin:13px 0}.button{background:#619ECE;border-radius:25.5px;font-weight:700;font-size:14px;color:#fff!important;line-height:40px;padding:0 24px;border:0;height:40px;display:inline-flex;align-items:center;text-decoration:none;font-family:'Open Sans',sans-serif}</style><!--[if mso]> <xml> <o:OfficeDocumentSettings> <o:AllowPNG/> <o:PixelsPerInch>96</o:PixelsPerInch> </o:OfficeDocumentSettings> </xml> <![endif]--> <!--[if lte mso 11]><style type='text/css'>.outlook-group-fix{width:100% !important}</style><![endif]--><!--[if !mso]><!--><link href='https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap' rel='stylesheet' type='text/css'><style type='text/css'>@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap');</style><!--<![endif]--></head><body style='background-color:#E1E1E1;'><div style='display:none;font-size:1px;color:#ffffff;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;'> Need to reset your password? No biggie. Just click below to get started.</div><div style='background-color:#E1E1E1;'><!--[if mso | IE]><table align='center' border='0' cellpadding='0' cellspacing='0' class='' style='width:600px;' width='600' ><tr><td style='line-height:0px;font-size:0px;mso-line-height-rule:exactly;'> <![endif]--><div style='background:#ffffff;background-color:#ffffff;margin:0px auto;max-width:600px;'><table align='center' border='0' cellpadding='0' cellspacing='0' role='presentation' style='background:#ffffff;background-color:#ffffff;width:100%;'><tbody><tr><td style='direction:ltr;font-size:0px;padding:0px;text-align:center;'> <!--[if mso | IE]><table role='presentation' border='0' cellpadding='0' cellspacing='0'><tr><td class='' style='vertical-align:top;width:600px;' > <![endif]--><div class='mj-column-per-100 outlook-group-fix' style='font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;'><table border='0' cellpadding='0' cellspacing='0' role='presentation' width='100%'><tbody><tr><td style='vertical-align:top;padding:0px;'><table border='0' cellpadding='0' cellspacing='0' role='presentation' style='' width='100%'><tr><td align='center' style='font-size:0px;padding:0px;word-break:break-word;'><table border='0' cellpadding='0' cellspacing='0' role='presentation' style='border-collapse:collapse;border-spacing:0px;'><tbody><tr><td style='width:600px;'></td></tr><tr><td style='width:600px;'><p class='h1'>Reset your sgf.dev password</p><p>Need to reset your password? No biggie. Just click below to get started.</p></td></tr><tr><td style='width:600px;'> <a href='https://sgf.dev/reset-password?token=";
                var secondHalfEmail = "' class='button'>Reset Your Password</a></td></tr></tbody></table></td></tr></table></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table> <![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table> <![endif]--></div></body></html>";
                var mm = new MailMessage
                {
                    Body       = firstHalfEmail + member.GetValue("ResetPasswordToken") + secondHalfEmail,
                    IsBodyHtml = true,
                    Subject    = "Reset SGF.Dev Password",
                    From       = new MailAddress("*****@*****.**")
                };

                mm.To.Add(new MailAddress(model.EmailAddress.ToString()));

                new SmtpClient().Send(mm);


                //    //EmailHelper email = new EmailHelper();
                //    //email.SendResetPasswordEmail(findMember.Email, expiryTime.ToString("ddMMyyyyHHmmssFFFF"));
                return(CurrentUmbracoPage());
            }
            else
            {
                return(CurrentUmbracoPage());
            }
        }
Пример #9
0
        public void WhenISubmitForgottenPasswordPage_IfModelStateIsValidUserExistsAndHasNoSecurityAnswers_ThenIGetTheCorrectView()
        {
            var model = new ForgottenPasswordModel();

            var user = new ApplicationUser();

            this._userService.Setup(x => x.GetApplicationUser(It.IsAny <string>())).Returns(user);

            this._securityAnswerService.Setup(x => x.HasSecurityAnswers(It.IsAny <string>())).Returns(true);

            var result = this._controller.Forgotten(model);

            this._userService.Verify(x => x.GetApplicationUser(It.IsAny <string>()), Times.AtLeastOnce);
            this._securityAnswerService.Verify(x => x.HasSecurityAnswers(It.IsAny <string>()), Times.AtLeastOnce);
            result.Should().BeOfType <RedirectToRouteResult>();
        }
Пример #10
0
        public async Task <IActionResult> ForgottenPassword(ForgottenPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await _identityService.GetPasswordResetResult(model.Email);

                if (result.IsSucessfull)
                {
                    var          link    = Url.Action("ResetPassword", "Account", result.Values[0], Request.Scheme);
                    EmailMessage message = EmailGenerator.GeneratePasswordResetMessage(link, model.Email);
                    await _emailService.SendEmailAsync(message);
                }

                return(View("ForgotPasswordConfirmation"));
            }

            return(View());
        }
Пример #11
0
        public ActionResult ForgottenPassword(ForgottenPasswordModel forgottenmodel)
        {
            ForgottenPasswordModel model = new ForgottenPasswordModel();


            // Kullanıcı kayıtlımı diye kontrol ediyorum.
            var user = (from x in db.tbl_kullanicis
                        where x.Eposta == forgottenmodel.Eposta
                        select x).FirstOrDefault();

            if (user == null)
            {
                model.Error = "Bu E-Posta Sistemde Kayıtlı Değil. Farklı bir E-Posta adresi deneyiniz.";
            }
            else
            {
                var          fromAddress  = new MailAddress("*****@*****.**", "Sistem Yöneticisi");
                var          toAddress    = new MailAddress(forgottenmodel.Eposta, user.Isim + " " + user.Soyisim);
                const string fromPassword = "******";
                string       subject      = "MediForum - Şifremi Unuttum";
                string       body         = "Merhabalar. Sistemde şifrenizi unuttuğunuzu söylediniz. Şifreniz: " + user.Sifre;

                var smtp = new SmtpClient
                {
                    Host                  = "smtp.gmail.com",
                    Port                  = 587,
                    EnableSsl             = true,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })
                {
                    smtp.Send(message);
                }
                model.Error = "Şifreniz E-Posta Adresinize Gönderildi.";
            }
            return(View(model));
        }
        public ActionResult ForgottenPassword(ForgottenPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            string userName = model.UserName;
            var    dbUser   = db.UserProfiles.FirstOrDefault(u => u.Name.Equals(userName, StringComparison.OrdinalIgnoreCase));

            if (dbUser == null)
            {
                var userEmailList = db.UserProfiles.Where(u => u.Email.Equals(userName, StringComparison.OrdinalIgnoreCase)).ToList();
                int n             = userEmailList.Count;
                if (n > 1)
                {
                    return(RedirectToAction("ForgottenPassword", new { initialName = userName, message = ValidateStatusMessage.ManyEmails }));
                }
                else if (n <= 0)
                {
                    return(RedirectToAction("ForgottenPassword", new { initialName = userName, message = ValidateStatusMessage.IncorrectUser }));
                }
                dbUser = userEmailList[0];
            }
            dbUser.Token = GenerateToken();
            dbUser.PasswordTokenExpirationTime = DateTime.UtcNow.AddDays(1.0);
            db.SaveChanges();
            ValidateStatusMessage result;

            if (!MailService.SendMessage(dbUser.Email, "Сброс пароля",
                                         String.Format("Для установки нового пароля для Вашего пользователя {1},{0}пожалуйста, перейдите по ссылке {2}",
                                                       Environment.NewLine, dbUser.Name,
                                                       Url.Action("Activate", "Account", new { id = dbUser.Token }, "http")
                                                       )))
            {
                result = ValidateStatusMessage.ProviderError;
            }
            else
            {
                result = ValidateStatusMessage.Success;
            }
            return(RedirectToAction("ForgottenPassword", new { initialName = userName, message = result }));
        }
Пример #13
0
        public async Task <IActionResult> ForgottenPassword(ForgottenPasswordModel forgottenPassword)
        {
            if (!ModelState.IsValid)
            {
                return(View(forgottenPassword));
            }
            User user = await _userManager.FindByEmailAsync(forgottenPassword.Email);

            if (user == null)
            {
                return(RedirectToAction(nameof(ForgottenPasswordConfirm)));
            }
            var token = await _userManager.GeneratePasswordResetTokenAsync(user);

            var    callback    = Url.Action(nameof(ResetPassword), "Account", new { token, email = user.Email }, Request.Scheme);
            string contentBody = $"Hi {user.UserName},\nYou've asked to reset your password for the CSharpDataProject. Please click the link below\n<a>{callback}</a>";
            var    message     = new Message(new string[] { user.Email }, "Your Password Reset token", contentBody);
            await _emailMessenger.SendEmailAsync(message);

            return(RedirectToAction(nameof(ForgottenPasswordConfirm)));
        }
        public ActionResult ForgottenPassword(string initialName = null, ValidateStatusMessage message = ValidateStatusMessage.Nothing)
        {
            ForgottenPasswordModel model = new ForgottenPasswordModel();

            if (initialName != null)
            {
                model.UserName = initialName;
            }
            string msg;

            switch (message)
            {
            case ValidateStatusMessage.IncorrectUser:
                msg = "Неправильное имя пользователя или E-mail";
                break;

            case ValidateStatusMessage.ManyEmails:
                msg = "Для данного адреса электронной почты восстановление пароля невозможно";
                break;

            case ValidateStatusMessage.Expired:
                msg = "Истек срок действия кода подтверждения смены пароля. Запросите новый код";
                break;

            case ValidateStatusMessage.ProviderError:
                msg = "Ошибка отправки кода сброса пароля. Пожалуйста, повторите попытку";
                break;

            case ValidateStatusMessage.Success:
                msg = "Код сброса пароля отправлен на Ваш e-mail. Срок действия кода 24 часа";
                model.ModelSuccess = true;
                break;

            default:
                msg = String.Empty;
                break;
            }
            ViewBag.StatusMessage = msg;
            return(View(model));
        }
Пример #15
0
        public ActionResult ForgottenPassword()
        {
            ForgottenPasswordModel forgottenpassword = new ForgottenPasswordModel();

            return(View(forgottenpassword));
        }
Пример #16
0
        public ActionResult ForgottenPassword(ForgottenPasswordModel model)
        {
            bool   status = true;
            string exMsg  = "";

            if (ModelState.IsValid)
            {
                using (DBEntities db = new DBEntities())
                {
                    var playerDashboard = db.PlayerDashboard.FirstOrDefault(u => u.DashboardURL == model.DashboardURLId);

                    PlayersRepository playerRepo = new PlayersRepository();
                    var player = playerRepo.ReadOne_ByEmailAddress(model.Email, true);

                    if (playerDashboard != null && player != null)
                    {
                        //Now Send an Email to User for Username and Password!
                        //  if (sys.EmailsEnabled)
                        {
                            try
                            {
                                SystemSettingsRepository sysRepo = new SystemSettingsRepository();
                                var sys = sysRepo.GetSystemSettings();

                                //Random rndm = new Random();
                                //var RandomNum = rndm.Next(10001, int.MaxValue);
                                Guid   guid = Guid.NewGuid();
                                string EncryptedRandomNum = guid.ToString();
                                SecurityUtils.CheckforInvalidFileNameChar(ref EncryptedRandomNum); //it will remove any unsupported characters
                                playerDashboard.PasswordResetCode = EncryptedRandomNum;
                                playerDashboard.ResetCodeExpiry   = DateTime.Now.AddHours(24);
                                db.SaveChanges();

                                status = SendEmail(player, EncryptedRandomNum, sys.CurrentDomain);
                            }
                            catch (Exception ex)
                            {
                                model.Reason    = "Failed to send an Email. Please contact your Site Administrator" + ex.Message;
                                model.AlertType = "danger";
                                exMsg           = ex.Message;
                            }

                            if (status)
                            {
                                //Add To Log
                                SecurityUtils.AddAuditLog("Requested for Forgotten Password", "User \"" + player.FullName + "\" requested for Forgotten Password , Email Sent to: \"" + player.EmailAddress + "\"", this);
                                model.Reason    = "Your Login Details has been sent to above email address. <a style='color:black' href='/Member/Login/" + model.DashboardURLId + "'> Log In </a>";
                                model.AlertType = "success";
                            }
                            else
                            {
                                model.Reason    = "Failed to send an Email. Please contact your Site Administrator." + exMsg + " - " + EmailsRepository.EmailErrorMsg;
                                model.AlertType = "danger";
                            }
                        }
                    }
                    else
                    {
                        model.Reason    = "Your provided email address is not valid. Please contact us at [email protected]";
                        model.AlertType = "danger";
                    }
                }
            }

            ViewBag.ModelIsLogin = true;

            return(View(model));
        }
Пример #17
0
        public async Task <IActionResult> ResetPassword([FromBody] ForgottenPasswordModel model)
        {
            string msg;

            if (!ModelState.IsValid)
            {
                msg = $"{_localizer.GetString("Invalid model validation").Value}!<br />{ModelState.GetErrors()}";
                return(BadRequest(msg));
            }
            else
            {
                if (!String.Equals(model.NewPassword, model.NewPasswordConfirm))
                {
                    msg = "New password and confirmation do not match!";
                    return(BadRequest(msg));
                }
            }

            try
            {
                var user = await _userManager.FindByIdAsync(model.UserId);

                if (user != null)
                {
                    var code        = model.Token.Replace(" ", "+");
                    var resetResult = await _userManager.ResetPasswordAsync(user, model.Token, model.NewPassword);

                    if (resetResult.Succeeded)
                    {
                        //return Ok("Password is reset");

                        var userRoles = await _userManager.GetRolesAsync(user);

                        var token = GenerateToken(user, userRoles);
                        await InvalidateToken(Request.Headers[AuthHeaderName]);

                        var data = new
                        {
                            token           = new JwtSecurityTokenHandler().WriteToken(token),
                            userName        = user.UserName,
                            tokenExpiration = token.ValidTo,
                            userId          = user.Id
                        };

                        return(Ok(data));
                    }
                    else
                    {
                        msg = $"Reset password errors: {String.Join("; ", resetResult.Errors.Select(x => x.Code + "/" + x.Description))}";
                        return(BadRequest(msg));
                    }
                }
                else
                {
                    return(BadRequest("User not found"));
                }
            }
            catch (Exception e)
            {
                msg = $"BadRequest ({e.Message} {e.InnerException?.Message})";
                return(BadRequest(msg));
            }
        }
Пример #18
0
        public ActionResult Forgotten()
        {
            var forgottenPasswordModel = new ForgottenPasswordModel();

            return(View(forgottenPasswordModel));
        }