Ejemplo n.º 1
0
        public async Task <ActionResult> ForgottenPassword(ForgottenPasswordViewModel model)
        {
            //If all required feilds are present then procced
            if (ModelState.IsValid)
            {
                var userStore = new UserStore();
                UserManager <IdentityUser> UserManager = new UserManager <IdentityUser>(userStore)
                {
                    PasswordHasher = new MyPasswordHasher()
                };
                UserManager.UserValidator = new UserValidator <IdentityUser>(UserManager)
                {
                    AllowOnlyAlphanumericUserNames = false
                };
                var provider = new MachineKeyProtectionProvider();
                UserManager.UserTokenProvider = new DataProtectorTokenProvider <IdentityUser>(provider.Create("ResetPasswordPurpose"));
                var userSelected = (await userStore.GetUsersAsync()).Where(x => x.Email == model.Email || x.UserName == model.Email).FirstOrDefault();

                if (userSelected != null)
                {
                    string newPassword = Regex.Replace(Membership.GeneratePassword(8, 0), @"[^a-zA-Z0-9]", m => new Random().Next(9).ToString());
                    var    token       = UserManager.GeneratePasswordResetToken <IdentityUser, string>(userSelected.Id);
                    var    result      = UserManager.ResetPassword(userSelected.Id, token, newPassword);

                    //Build email template model

                    RestPasswordEmailViewModel emailModel = new RestPasswordEmailViewModel();
                    emailModel.message    = "Your new password request has been proccessed, please find your new password below.";
                    emailModel.Salutation = "Dear " + userSelected.FirstName + " " + userSelected.LastName;
                    emailModel.Username   = userSelected.UserName;
                    emailModel.Password   = newPassword;

                    //Generate HTML for the confirmation email

                    ViewData.Model = emailModel;
                    var restPasswordEmail = new StringWriter();
                    var viewResult        = ViewEngines.Engines.FindPartialView(ControllerContext, "~/Views/Emails/ResetPassword.cshtml");
                    var viewContext       = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, restPasswordEmail);
                    viewResult.View.Render(viewContext, restPasswordEmail);
                    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);

                    if (result.Succeeded)
                    {
                        if (MailClient.SendResetPasswordEmail(userSelected.Email, restPasswordEmail.GetStringBuilder().ToString()))
                        {
                            ViewBag.Message = String.Format("The new password for user <strong>{0} ({1})</strong> has been sent by email.",
                                                            String.Concat(userSelected.FirstName, " ", userSelected.LastName).Trim(),
                                                            userSelected.Email);
                            ViewBag.Message2 = "";
                            return(View("PasswordReset"));
                        }
                        ViewBag.Message = String.Format("The new password for user <strong>{0} ({1})</strong> has been generated but an email could not be sent.",
                                                        String.Concat(userSelected.FirstName, " ", userSelected.LastName).Trim(),
                                                        userSelected.Email);
                        ViewBag.Message2 =
                            "<strong>Password:</strong> " + newPassword;

                        return(View("PasswordReset"));
                    }
                }
            }
            //If we reach this point something has gone wrong
            model.Invalid = true;
            return(View(model));
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> ResetPassword(EditContactViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userStore = new UserStore();
                UserManager <IdentityUser> UserManager = new UserManager <IdentityUser>(userStore)
                {
                    PasswordHasher = new MyPasswordHasher()
                };
                UserManager.UserValidator = new UserValidator <IdentityUser>(UserManager)
                {
                    AllowOnlyAlphanumericUserNames = false
                };
                var provider = new MachineKeyProtectionProvider();
                UserManager.UserTokenProvider = new DataProtectorTokenProvider <IdentityUser>(provider.Create("ResetPasswordPurpose"));

                var contact = (await db.GetCustomerContacts(ActiveCustomer))
                              .Where(x => x.ContactPersonKey == model.contactPerson.ContactPersonKey && x.Activated == true).FirstOrDefault();
                var user = (await userStore.GetUsersAsync()).Where(x => x.Id == contact.UserId).FirstOrDefault();

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

                string newPassword = Regex.Replace(Membership.GeneratePassword(8, 0), @"[^a-zA-Z0-9]", m => new Random().Next(9).ToString());
                var    token       = await UserManager.GeneratePasswordResetTokenAsync(contact.UserId);

                var result = await UserManager.ResetPasswordAsync(contact.UserId, token, newPassword);


                if (result.Succeeded)
                {
                    String emailAddress;
                    if (ROLWeb.Helpers.AppGlobal.IsProduction)
                    {
                        emailAddress = user.Email; //We send it to the user that we have changed password
                    }
                    else
                    {
                        emailAddress = ((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("Email").Value; //we send it to the logged in user
                    }

                    if (MailClient.SendResetPasswordEmail(
                            user.UserName,
                            emailAddress,
                            newPassword
                            ))
                    {
                        ViewBag.Message  = String.Format(Resources.NewPasswordSentMessage, contact.FullName, contact.Email);
                        ViewBag.Message2 = "";

                        return(View("Completed"));
                    }

                    ViewBag.Message  = String.Format(Resources.NewPasswordNotSentMessage, contact.FullName, contact.Email);
                    ViewBag.Message2 = String.Format(Resources.PasswordMessage, newPassword);

                    return(View("Completed"));
                }
            }

            ViewBag.Message  = Resources.ErrorPasswordNotChanged;
            ViewBag.Message2 = "";

            return(View("Completed"));
        }