Ejemplo n.º 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)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    this.SetNotificationMessage(NotificationType.StickySuccess, "We've sent you an email so that you can reset your password.");
                    return(RedirectToAction("Login", "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
                var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { code = code }, protocol: Request.Url.Scheme);
                callbackUrl = callbackUrl + "&email=" + Uri.EscapeDataString(user.Email);
                var textReplacement = new TextReplacements
                {
                    BaseUrl           = ConfigUtil.BaseAppUrl,
                    RecipientEmail    = user.Email,
                    ResetPasswordLink = callbackUrl
                };

                _genericEmailManager.SendFromTemplate(user.Email, "Supdate Password Reset", TextTemplate.ForgotPasswordEmail, textReplacement);

                this.SetNotificationMessage(NotificationType.StickySuccess, "We've sent you an email so that you can reset your password.");
                return(RedirectToAction("Login", "Account"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 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)))
                {
                    // 请不要显示该用户不存在或者未经确认
                    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> PasswordRecover(AccountPasswordRecoverViewModel model)
        {
            if (ModelState.IsValid)
            {
                //
                var adminUser = await _appUserManager.FindByEmailAsync(model.Email);

                //
                if (adminUser != null && adminUser.Realms.Contains(Realm.AdminWebsite))
                {
                    //
                    var mailModel = new AccountPasswordRecoverMessageViewModel()
                    {
                        Name      = adminUser.FullName ?? adminUser.UserName,
                        PageTitle = GetLocalizedString <AreaResources>("RecoverPassword"),
                        ResetLink = Url.Action(nameof(PasswordSetNew), "Account", new
                        {
                            resetToken = await _appUserManager.GeneratePasswordResetTokenAsync(adminUser.Id),
                            area       = AppAreas.GetAreaName(Area.Users)
                        }, protocol: Request.Url.Scheme)
                    };

                    //
                    var subject = $"[{GetLocalizedString("AppName")}] {mailModel.PageTitle}";
                    var message = RenderViewToString("PasswordRecoverMessage", model: mailModel);

                    //
                    _emailDispatcherService.Dispatch(message, subject, new MailAddress(adminUser.Email, adminUser.FullName));
                }

                return(RedirectToAction(nameof(PasswordRecover), new { status = AccountActionStatus.PasswordRecoverMessageSent.ToLowerCaseString() }));
            }

            return(View(model));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./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.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { code },
                    protocol: Request.Scheme);

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

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

            return(Page());
        }
Ejemplo n.º 5
0
        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"));
                }

                // 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, "Alteração de Senha", "Altere a sua senha clicando <a href=\"" + callbackUrl + "\">aqui</a>");

                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 6
0
        public async Task <Boolean> BeforeSave(Int64 UserId, Object beforeData)
        {
            var before = beforeData as ExpandoObject;

            var userId = before.Eval <Int64>("User.Id");
            var pwd    = before.Eval <String>("User.Password");

            var token = await _userManager.GeneratePasswordResetTokenAsync(userId);

            var ir = await _userManager.ResetPasswordAsync(userId, token, pwd);

            if (!ir.Succeeded)
            {
                String errors = String.Empty;
                foreach (var e in ir.Errors)
                {
                    errors += "\n" + e;
                }
                throw new SecurityException("Set password failed." + errors);
            }
            var user = await _userManager.FindByIdAsync(userId);

            await _userManager.UpdateAsync(user);

            return(true);
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model, string Year)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                decimal CorrectYear = user.Birthday.Year;
                decimal UserYear    = Convert.ToDecimal(Year);
                if (CorrectYear != UserYear)
                {
                    ViewBag.ErrorMessage = "Incorrect birth year entered.";
                    return(View(model));
                }
                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
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                Messaging.EmailMessaging.SendEmail(user.Email, "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));
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> ForgetPassword(ForgetPassword model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

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

            if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
            {
                return(View("ForgetPasswordConfirm"));
            }

            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            var callBackUrl = Url.RouteUrl(
                "GetResetPassword",
                new
            {
                key = user.GeneratedKey,
                code
            }, Request.Scheme);

            var message = $"<a href=\"{callBackUrl}\"> Rest Password </a>";

            await _emailSender.SendEmailAsync(user.Email, "Rest Password", message);

            return(View("ForgetPasswordConfirm"));
        }
Ejemplo n.º 9
0
        public async Task <IHttpActionResult> ForgotPassword(string email)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = await AppUserManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(BadRequest("El email es incorrecto."));
            }

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

            code = HttpUtility.UrlEncode(code);

            var callbackUrl = string.Concat(
                Request.RequestUri.Scheme,
                "://",
                Request.RequestUri.Authority,
                "/#!/resetPassword?key=",
                user.Id,
                "&code=",
                code
                );
            await AppUserManager.SendEmailAsync(user.Id, "Recuperar Contraseña", "Por favor, recupere su contraseña siguiendo <a href=\"" + callbackUrl + "\">este enlace.</a>");

            return(Ok());
        }
Ejemplo n.º 10
0
        public async Task <ActionResult> EmployeeChangePassword(ResetPasswordViewModel model, string Id, string Password)
        {
            var token = await UserManager.GeneratePasswordResetTokenAsync(Id);

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await UserManager.FindByNameAsync(model.EmailAddress);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }

            var result = await UserManager.ResetPasswordAsync(Id, token, Password);

            if (result.Succeeded)
            {
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            AddErrors(result);
            return(View());
        }
Ejemplo n.º 11
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 cuenta y el restablecimiento de contraseña, visite 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);

                #region TODO: Código para el envio del correo electrónico

                /*PLNFramework.Mailing.IEmail email = new PLNFramework.Mailing.Email();
                 * email.Tos = new string[] { model.Email };
                 * email.Subject = "Restablecer contraseña";
                 * email.Body = "Para restablecer la contraseña, haga clic <a href=\"" + callbackUrl + "\">aquí</a>";
                 * AdminSoft.WebSite.Helpers.EmailHelper.SendMailRegister(email);*/
                #endregion

                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));
        }
Ejemplo n.º 12
0
        public async Task AfterSave(Object beforeData, Object afterData)
        {
            var before = beforeData as ExpandoObject;
            var after  = afterData as ExpandoObject;

            var userId = after.Eval <Int64>("User.Id");
            var pwd    = before.Eval <String>("User.Password");

            var token = await _userManager.GeneratePasswordResetTokenAsync(userId);

            var ir = await _userManager.ResetPasswordAsync(userId, token, pwd);

            if (!ir.Succeeded)
            {
                String errors = String.Empty;
                foreach (var e in ir.Errors)
                {
                    errors += "\n" + e;
                }
                throw new SecurityException("Set password failed." + errors);
            }
            var user = await _userManager.FindByIdAsync(userId);

            user.EmailConfirmed = true;
            user.SetModified(UserModifiedFlag.EmailConfirmed);
            await _userManager.UpdateAsync(user);
        }
Ejemplo n.º 13
0
        public async Task <Object> InvokeAsync(Int32 TenantId, Int64 UserId, Int64 Id, ExpandoObject User)
        {
            if (!_host.IsMultiTenant)
            {
                throw new InvalidOperationException("CreateTenantUserHandleris available only in multitenant environment");
            }

            User.Set("Tenant", TenantId);
            await _dbContext.ExecuteExpandoAsync(_host.CatalogDataSource, "a2security.[CreateUserSimple]", User);

            Int64 userId = User.Get <Int64>("Id");

            var token = await _userManager.GeneratePasswordResetTokenAsync(userId);

            var identityResult = await _userManager.ResetPasswordAsync(userId, token, User.Get <String>("Password"));

            if (!identityResult.Succeeded)
            {
                throw new InvalidOperationException(String.Join(",", identityResult.Errors));
            }
            var newAppUser = await _userManager.FindByIdAsync(userId);

            await _dbContext.ExecuteAsync <AppUser>(_host.TenantDataSource, "a2security.CreateTenantUser", newAppUser);

            var result = new ExpandoObject();

            result.Set("Id", userId);

            return(result);
        }
Ejemplo n.º 14
0
        public async Task <IHttpActionResult> ResetPassword(CreateUserBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            FogToken t = await FogAddUser(model, Helper.FOGRESETPASSWORDURL);

            if (null == t)
            {
                return(BadRequest(ModelState));
            }

            var user = await AppUserManager.FindByNameAsync(model.Username);

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

            string resetToken = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

            IdentityResult result = await AppUserManager.ResetPasswordAsync(user.Id, resetToken, model.Password);

            if (null == result)
            {
                return(BadRequest());
            }

            t = await FogCheck(model);

            if (null == t)
            {
                return(BadRequest(ModelState));
            }

            if (!user.UserToken.Equals(t.user_token) || !user.UserKey.Equals(t.user_id))
            {
                user.UserToken = t.user_token;
                user.UserKey   = t.user_id;
                IdentityResult x = await AppUserManager.UpdateAsync(user);

                if (null == x)
                {
                    return(BadRequest());
                }
            }

            UserToken u = CreateToken(model.Username, model.Password);

            u.fog_user_id    = t.user_id;
            u.fog_user_token = t.user_token;

            return(Ok(u));
        }
Ejemplo n.º 15
0
        public async Task <ActionResult> ChangeCustomerPassword(/*ChangePasswordViewModel model, */ string Id, string NewPassword, string ConfirmPassword)
        {
            var provider = new DpapiDataProtectionProvider("YourAppName");

            UserManager.UserTokenProvider = new DataProtectorTokenProvider <AppUser, string>(provider.Create("UserToken"))
                                            as IUserTokenProvider <AppUser, string>;

            if (!ModelState.IsValid)


            {
                ViewBag.Id = Id;
                return(View());
            }

            // check to see that the two passwords are the same
            if (NewPassword != ConfirmPassword)
            {
                ViewBag.Id           = Id;
                ViewBag.ErrorMessage = "Make sure your passwords are the same.";
                return(View());
            }


            try
            {
                string resetToken = await UserManager.GeneratePasswordResetTokenAsync(Id);

                IdentityResult passwordChangeResult = await UserManager.ResetPasswordAsync(Id, resetToken, NewPassword);

                db.SaveChanges();

                return(RedirectToAction("EmployeeDashboard", new { SuccessMessage = ManageMessageId.ChangePasswordSuccess }));
            } catch (Exception e)
            {
                ViewBag.ErrorMessage = "Looks like some error happened. It might be " + e.ToString();
                ViewBag.Id           = Id;
                return(View("ChangeCustomerPassword"));
            }



            //var result = await UserManager.ChangePasswordAsync(Id, model.OldPassword, model.NewPassword);
            //if (result.Succeeded)
            //{

            //    return RedirectToAction("EmployeeDashboard", new { SuccessMessage = ManageMessageId.ChangePasswordSuccess });
            //}
            //AddErrors(result);
            //ViewBag.Id = Id;
            //ViewBag.TestMessage = "Test Message from ChangeCustomerPassword Post Method in the end of the method";
        }
Ejemplo n.º 16
0
 public async Task<ActionResult> ForgotPassword(ForgotPasswordModel model)
 {
     var user = await _userManager.FindByNameAsync(model.UserName);
     if (user != null)
     {
         var token = await _userManager.GeneratePasswordResetTokenAsync(user.Id.ToString());
         var requestUrl = Url.Action("PasswordReset", "Auth", new { userId = user.Id, token = token }, Request.Url.Scheme);
         //await userManager.SendEmailAsync(user.Id.ToString(), "Password Reset", $"Use this link to reset Password:{requestUrl}");
         ViewBag.Url = requestUrl;
         return View("TempLink");
     }
     return RedirectToAction("Index", "Home");
 }
Ejemplo n.º 17
0
        public async Task AfterSave(Int64 UserId, Object beforeData, Object afterData)
        {
            var before = beforeData as ExpandoObject;
            var after  = afterData as ExpandoObject;

            var    userId      = after.Eval <Int64>("User.Id");
            var    pwd         = before.Eval <String>("User.Password");
            String tenantRoles = null;

            if (_host.IsMultiTenant)
            {
                tenantRoles = before.Eval <String>("User.TenantRoles");
                var afterUser = after.Get <ExpandoObject>("User");
                afterUser.Set("TenantRoles", tenantRoles);
            }

            var token = await _userManager.GeneratePasswordResetTokenAsync(userId);

            var ir = await _userManager.ResetPasswordAsync(userId, token, pwd);

            if (!ir.Succeeded)
            {
                String errors = String.Empty;
                foreach (var e in ir.Errors)
                {
                    errors += "\n" + e;
                }
                throw new SecurityException("Set password failed." + errors);
            }
            var user = await _userManager.FindByIdAsync(userId);

            user.EmailConfirmed = true;
            if (tenantRoles != null)
            {
                user.TenantRoles = tenantRoles;
            }
            user.SetModified(UserModifiedFlag.EmailConfirmed);
            await _userManager.UpdateAsync(user);

            if (_host.IsMultiTenant && _host.IsMultiCompany)
            {
                var update = new UpdateTenantCompanyHandler();
                update.Inject(_host, _dbContext);
                update.EnableThrow();
                update.DisableDtc();
                update.Invoke(UserId, 0);
            }
        }
Ejemplo n.º 18
0
        public async Task <ActionResult> ForgotPassword(string email)
        {
            AppUser user = await _userManager.FindByEmailAsync(email);

            if (!string.IsNullOrEmpty(email) && user != null)
            {
                string code = await _userManager.GeneratePasswordResetTokenAsync(user.Id);

                string callbackUrl = Url.Action("ResetPassword", "Account", new { code = code }, protocol: Request.Url.Scheme);
                _mailingRepository.ResetPasswordMail(user.Email, callbackUrl);
                return(PartialView("ForgotPasswordConfirmation"));
            }
            ModelState.AddModelError("", "User Not Found");
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return(PartialView());
        }
Ejemplo n.º 19
0
        public async Task ResetPasswordAsync_ShouldResetUserPassword()
        {
            // Arrange
            AppUserManager <User> userManager = _serviceProvider.GetService <AppUserManager <User> >();

            // Act
            //IdentityResult identityResult = await tokenStore.CreateRefreshTokenAsync(refreshToken, CancellationToken.None);
            User user = await userManager.FindByNameAsync("user1");

            string code = await userManager.GeneratePasswordResetTokenAsync(user);

            IdentityResult identityResult = await userManager.ResetPasswordAsync(user, code, "Test@1");

            // Assert
            Assert.True(identityResult.Succeeded);
        }
Ejemplo n.º 20
0
        public async Task <IHttpActionResult> ChangePasswordRequest(string username)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return(BadRequest("E-mail is required"));
            }

            try
            {
                var user = await this.AppUserManager.FindByNameAsync(username);

                if (user == null)
                {
                    return(BadRequest("No user with this email"));
                }


                //The call back URL is stored in the database. This makes it easy to switch between DEV/UAT/PROD
                DynamicParameters p = new DynamicParameters();
                p.Add("@Name", "CHANGE_PASSWORD_URL", dbType: DbType.String, direction: ParameterDirection.Input);

                AppSettings settings = DatabaseGet.GetSingle <AppSettings>(p, "dbo.sp_AppSettingsGetByName");
                if (settings == null)
                {
                    throw new ArgumentNullException("settings");
                }


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

                code = HttpUtility.UrlEncode(code);

                NameValueCollection queryString = HttpUtility.ParseQueryString(string.Empty);
                queryString["userId"] = user.Id;
                queryString["code"]   = code;
                string callbackUrl = settings.Value + queryString.ToString();
                await this.AppUserManager.SendEmailAsync(user.Id, "Password Reset", "Reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return(Ok());
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return(BadRequest(ModelState));
            }
        }
Ejemplo n.º 21
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordModel username)
        {
            var user = await AppUserManager.FindByEmailAsync(username.UserName);

            if (user == null)
            {
                return(BadRequest("Invalid email address"));
            }
            var token = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

            var callbackUrl = Request.RequestUri.Scheme + "://" + Request.RequestUri.Authority +
                              "/ResetPassword?userId=" + user.Id + "&code=" + HttpUtility.UrlEncode(token);
            await
            AppUserManager.SendEmailAsync(user.Id, "Password Reset",
                                          "Please reset your password by clicking " + callbackUrl);

            return(Ok());
        }
Ejemplo n.º 22
0
        public async Task <IHttpActionResult> RecoverPassword(string email)
        {
            var user = await AppUserManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(BadRequest("E-mail is not registered"));
            }

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

            string password = GetAutoGenPwd();

            var callbackUrl = new Uri(Url.Link("ResetPasswordRoute", new { userId = user.Id, code, password }));

            await AppUserManager.SendEmailAsync(user.Id, "KeetFit Password Recovery", "Please follow <a href=\"" + callbackUrl + "\">this</a> link to reset your password. Then you'll be able to use new generated password: '******' for login.");

            return(Ok());
        }
Ejemplo n.º 23
0
        public async Task <IHttpActionResult> SendForgotPassword(SendForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await AppUserManager.FindByNameAsync(model.UserName);

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

            //we need to do this otherwise the + in the string gets replaced with a space
            var urlCode = Uri.EscapeDataString(code);
            var url     = $"{Request.RequestUri.Scheme}://{Request.RequestUri.Authority}/auth/reset-password?userId={user.Id}&code={urlCode}";

            await AppUserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + url + "\">here</a>");

            return(Ok());
        }
Ejemplo n.º 24
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"));
                }

                // Now, get the birth year
                int    year       = user.Birthday.Year;
                String yearString = year.ToString();
                if (model.BirthYear != yearString)
                {
                    return(RedirectToAction("Error", "Home", new { ErrorMessage = "Incorrect birthyear" }));
                }

                // 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 provider = new DpapiDataProtectionProvider("333KProj");
                UserManager.UserTokenProvider = new DataProtectorTokenProvider <AppUser>(provider.Create("ForgotPassword"));

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

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

                // New Email code
                MailMessage m = new MailMessage(new MailAddress("*****@*****.**"), new MailAddress(model.Email));
                m.Subject    = "[Team 8] Reset Password";
                m.Body       = string.Format("Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                m.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient("smtp.gmail.com");
                smtp.Send(m);

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IHttpActionResult> RecoveryPassword(string email)
        {
            var user = await AppUserManager.FindByEmailAsync(email);

            if (user == null)
            {
                Logger.ServiceLog.Warn($"Пользователь с email {email} не зарегистрирован.");
                return(GetErrorFromModel("email", $"Пользователь с email {email} не зарегистрирован."));
            }
            var recoveryToken = AppUserManager.GeneratePasswordResetTokenAsync(user.Id);
            var code          = HttpUtility.UrlEncode(recoveryToken.Result);
            var password      = RandomPasswordService.Generate(6);
            var callBackUri   = new Uri(Url.Link("RecoveryPasswordRoute", new { userId = user.Id, code, newPassword = password }));

            await AppUserManager.SendEmailAsync(user.Id, "Восстановление пароля",
                                                "Ваш новый пароль: <strong>" + password + "</strong> <br> Для его подтверждения перейдите по ссылке <a href=\"" + callBackUri + "\">ССылка</a>");

            Logger.ServiceLog.Info($"Пользователю на email {email} успешно выслана инструкция по восстановдению пароля.");
            return(Ok("Инструкция по смене пароля выслана на почту"));
        }
Ejemplo n.º 26
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Use later when isEmailConfirmed implemented
            //if (user == null || !(await AppUserManager.IsEmailConfirmedAsync(user.Id)))
            var user = await AppUserManager.FindByEmailAsync(model.Email);

            //var role = await this.AppRoleManager.FindByIdAsync(Id);
            if (user == null)
            {
                // Don't reveal that the user does not exist or is not confirmed
                return(Ok());
            }


            string pcode = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

            System.Web.HttpUtility.UrlEncode(pcode);

            var callbackUrl = "http://rip-offnigeria.com/index.html#/resetpwd/" + user.Id + "/" + pcode;

            string response = "<h4>Reset password</h4>" +
                              "<p>" +
                              "<p>Dear " + user.Name + "," +
                              "<p>" +
                              "<p class=\"lead\">To get back into your rip-off Nigeria account,you'll need to create a new password.</p>" +
                              "<p class=\"lead\">Click the link below to open a secure browser window.</p>";


            await this.AppUserManager.SendEmailAsync(user.Id,
                                                     "Reset your password",
                                                     response + "<a href=\"" + callbackUrl + "\">Reset your password now</a>");

            // If we got this far, something failed, redisplay form
            return(Ok());
        }
Ejemplo n.º 27
0
        public async Task <HttpResponseMessage> ResetPassword(HttpRequestMessage request, AppUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userEmail = await AppUserManager.FindByEmailAsync(model.Email);

                if (userEmail == null)
                {
                    return(request.CreateErrorResponse(HttpStatusCode.NoContent, "Email không tồn tại"));
                }
                //Send an email with link
                string sendLink = await AppUserManager.GeneratePasswordResetTokenAsync(userEmail.Id);

                await AppUserManager.SendEmailAsync(userEmail.Id, "Reset password", "Click here ");

                return(request.CreateResponse(HttpStatusCode.OK, sendLink));
            }
            else
            {
                return(request.CreateErrorResponse(HttpStatusCode.NoContent, "Models không thỏa mãn yêu cầu"));
            }
        }
Ejemplo n.º 28
0
        public async Task <IHttpActionResult> PostForgotPassword(string email)
        {
            if (ModelState.IsValid)
            {
                var user = await AppUserManager.FindByNameAsync(email);

                if (user == null || !(await AppUserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return(Ok("Please check your Inbox to reset your password"));
                }
                string code = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = String.Format("{0}/passwordrecovery/?email={1}&token={2}", Request.RequestUri.GetLeftPart(UriPartial.Authority), email, HttpUtility.UrlEncode(code));
                var emailHtml   = ViewRenderer.RenderView("~/Views/Email/Forgot Password.cshtml",
                                                          new System.Web.Mvc.ViewDataDictionary {
                    { "Url", callbackUrl },
                });
                EmailSender.SendEmail(user.UserName, "right.now. - Reset your Password", emailHtml);
                return(Ok("Please check your Inbox to reset your password"));
            }
            return(Ok("Please check your Inbox to reset your password"));
        }
Ejemplo n.º 29
0
        public async Task <RepositoryResult <UserInterfaceModel> > ModifyUserAsync(int id, UserInterfaceModel modifiedUser)
        {
            try
            {
                if (id <= 0)
                {
                    return(new RepositoryResult <UserInterfaceModel>(HttpStatusCode.BadRequest));
                }

                using (DataContext dbContext = DataContext.Create())
                    using (DbContextTransaction tx = dbContext.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
                    {
                        modifiedUser.Id = id;
                        UserModel user = await AppUserManager.FindByIdAsync(modifiedUser.Id);

                        if (user == null)
                        {
                            tx.Rollback();
                            return(new RepositoryResult <UserInterfaceModel>(HttpStatusCode.NotFound));
                        }

                        IdentityResult result;
                        if (!string.IsNullOrEmpty(modifiedUser.NewPassword))
                        {
                            string code = await AppUserManager.GeneratePasswordResetTokenAsync(user.Id);

                            result = await AppUserManager.ResetPasswordAsync(user.Id, code, modifiedUser.NewPassword);

                            if (!result.Succeeded)
                            {
                                tx.Rollback();
                                return(new RepositoryResult <UserInterfaceModel>(HttpStatusCode.BadRequest)
                                {
                                    identityResult = result
                                });
                            }
                        }

                        ModifiedUserModel(user, modifiedUser);
                        result = await AppUserManager.UpdateAsync(user);

                        if (!result.Succeeded)
                        {
                            tx.Rollback();
                            return(new RepositoryResult <UserInterfaceModel>(HttpStatusCode.BadRequest)
                            {
                                identityResult = result
                            });
                        }

                        tx.Commit();
                        return(new RepositoryResult <UserInterfaceModel>(HttpStatusCode.OK)
                        {
                            identityResult = result
                        });
                    }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }