Exemplo n.º 1
0
        public async Task <ActionResult> ForgotLoginPassword(ForgotViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

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

                    var callbackUrl = Url.Action("ResetPassword", "Account",
                                                 new { code = code }, protocol: Request.Url.Scheme);
                    try
                    {
                        await UserManager.SendEmailAsync(user.Id,
                                                         "Восстановление данных",
                                                         "<p>Ваше имя для входа в систему: " + user.UserName + "</p><br/>" +
                                                         "<p>Для сброса вашего пароля необходимо проийти по следующей ссылке: " +
                                                         "<a target=\"_blank\" href=\"" + callbackUrl + "\">Cбросить</a></p>");
                    }
                    catch (SmtpException)
                    {
                        ModelState.AddModelError("", "Не удалось отправить письмо. Проверьте адрес или повторите попытку позже.");
                        return(PartialView("_ForgotModalPartial"));
                    }
                    return(JavaScript("window.location = '" + Url.Action("ForgotPasswordConfirmation", "Account") + "'"));
                }
                ModelState.AddModelError("", "Пользователь с таким адрессом электронной почты не существует или учетная запись не подтверждена.");
            }
            // If we got this far, something failed, redisplay form
            return(PartialView("_ForgotModalPartial"));
        }
Exemplo n.º 2
0
        public ForgotPassword()
        {
            var vm = new ForgotViewModel();

            this.BindingContext = vm;
            InitializeComponent();
        }
Exemplo n.º 3
0
 public PasswordForgotPage()
 {
     InitializeComponent();
     NavigationPage.SetHasNavigationBar(this, true);
     BindingContext = forgotViewModel = new ForgotViewModel(this);
     Title          = "Şifremi Unuttum";
 }
        public async Task <ActionResult> ForgotPassword(ForgotViewModel model)
        {
            //Mail Gönder
            var user = await UserManager.FindByEmailAsync(model.email);

            if (user != null)
            {
                var password     = Guid.NewGuid().ToString();
                var passwordHash = "";
                for (int i = 0; i < 7; i++)
                {
                    passwordHash += password[i].ToString();
                }
                user.PasswordHash = UserManager.PasswordHasher.HashPassword(passwordHash);
                var result = await UserManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    var b = await bll.Action().Add(new DataAccessLayer.Contexts.Actions
                    {
                        email        = model.email,
                        Message      = String.Format("HRP ARBIS SIFRENIZ {0}", passwordHash),
                        Is_Completed = 0
                    });

                    return(RedirectToAction("Login", "Account"));
                }
            }
            ModelState.AddModelError("", "Şifreniz Değiştirilemedi!");
            return(View());
        }
Exemplo n.º 5
0
        public async Task <ActionResult> ForgotPassword(ForgotViewModel 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
                    ViewBag.Message = null;
                    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.Email, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                var message = new IdentityMessage()
                {
                    Body = "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>", Destination = model.Email, Subject = "ResetPassword"
                };
                await UserManager.EmailService.SendAsync(message);

                ViewBag.Message = model.Email;
                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Cancel([FromBody] ForgotViewModel viewModel)
        {
            var query = new UserByEmail {
                Email = viewModel.Email
            };
            await DataHandler.Execute(query);

            if (query.Result != null && query.Result.IsActive &&
                (query.ResultTenant == null || query.ResultTenant.IsActive))
            {
                var config = query.ResultConfig;

                config.ResetAuth  = string.Empty;
                config.ResetCode  = string.Empty;
                config.ForgotCode = string.Empty;

                var persistConfig = new Persist <UserConfig>()
                {
                    Model = config
                };
                await DataHandler.Execute(persistConfig);

                if (persistConfig.Confirm.Success)
                {
                    await DataHandler.Commit();
                }

                return(Ok(true));
            }

            return(Ok(new FailViewModel {
                Message = "Email not found"
            }));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Forgot([FromBody] ForgotViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            if (user == null)
            {
                ModelState.AddModelError("Message", "Cannot find the user");
                return(BadRequest(ModelState));
            }

            string code = await _userManager.GeneratePasswordResetTokenAsync(user);

            byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(code);
            var    codeEncoded         = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);
            var    callbackUrl         = _frontEndOptions.Url + "admin/reset?code=" + codeEncoded + "&userId=" + user.Id;

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

            return(Ok());
        }
Exemplo n.º 8
0
        public ActionResult ForgotPassword(ForgotViewModel model)
        {
            if (model.Email != null)
            {
                var  user       = Membership.FindUsersByEmail(model.Email).Cast <MembershipUser>().FirstOrDefault();
                bool isUserFind = false;
                if (user != null)
                {
                    var CoreManager = new CoreManager();
                    model.Password = user.GetPassword();
                    model.UserName = user.UserName;
                    string body = RenderRazorViewToString("Mail", model);

                    try
                    {
                        CoreManager.SendEmail(user.Email, "Восстановление пароля", body);
                        ViewBag.res = "Пароль выслан на вашу почту";
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", "Произошла ошибка при отправке на почту");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Пользователя с таким E-mail не найдено");
                }
            }
            return(View());
        }
        public void TestForgotViewModel()
        {
            ForgotViewModel viewModel = new ForgotViewModel
            {
                Email = "*****@*****.**"
            };

            viewModel.Should().NotBeNull();
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Code([FromBody] ForgotViewModel viewModel)
        {
            var query = new UserByEmail {
                Email = viewModel.Email
            };
            await DataHandler.Execute(query);

            if (query.Result != null && query.Result.IsActive &&
                (query.ResultTenant == null || query.ResultTenant.IsActive))
            {
                var config = query.ResultConfig;

                if (config.ForgotCounter < 10)
                {
                    config.ForgotCode     = StringHelper.GenerateCode(12);
                    config.ResetAuth      = Convert.ToString(EncryptHelper.Randomizer(100000, 999999));
                    config.ForgotCounter += 1;

                    var persist = new Persist <UserConfig>()
                    {
                        Model = config
                    };
                    await DataHandler.Execute(persist);

                    if (persist.Confirm.Success)
                    {
                        await DataHandler.Commit();
                    }

                    var notify = new SimpleNotify
                    {
                        CloudHandler = CloudHandler,
                        DataHandler  = DataHandler,
                        CurrentUser  = query.Result,
                        LogicHandler = LogicHandler,
                        Model        = persist.Model,
                        TemplateName = "forgot"
                    };

                    await LogicHandler.Execute(notify);

                    return(Ok(new ForgotCodeViewModel()
                    {
                        Email = viewModel.Email, Code = config.ForgotCode, Success = true
                    }));
                }

                return(Ok(new FailViewModel {
                    Message = "Too many Forgot Password attempts -> " + config.ForgotCounter
                }));
            }

            return(Ok(new FailViewModel {
                Message = "Email not found"
            }));
        }
Exemplo n.º 11
0
        public async Task <ActionResult> ResendEmail(ForgotViewModel model)
        {
            var user = UserManager.FindByEmail(model.Email);
            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href='" + callbackUrl + "'>here</a><br/><br/> Thanks,<br/>Izenda Engineering");

            return(View("Login"));
        }
Exemplo n.º 12
0
        public static RespuestaTransaccion RecuperarClave(ForgotViewModel recuperar)
        {
            try
            {
                try
                {
                    //validar si existe el registro
                    Usuario usuarioActual = db.Usuario.Where(u => u.MailCorporativo == recuperar.Login).First();

                    //obtener la clave
                    Random random = new Random();
                    String numero = "";
                    for (int i = 0; i < 9; i++)
                    {
                        numero += Convert.ToString(random.Next(0, 9));
                    }

                    var clave = Cryptography.Encrypt(numero);

                    usuarioActual.Clave      = clave;
                    usuarioActual.ResetClave = true;

                    // Por si queda el Attach de la entidad y no deja actualizar
                    var local = db.Usuario.FirstOrDefault(f => f.IdUsuario == usuarioActual.IdUsuario);
                    if (local != null)
                    {
                        db.Entry(local).State = EntityState.Detached;
                    }

                    db.Entry(usuarioActual).State = EntityState.Modified;
                    db.SaveChanges();

                    ////enviar correo
                    //db.EnviarCorreoUsuarioResetClave(usuarioActual.IdUsuario, numero);
                    //db.SaveChanges();

                    return(new RespuestaTransaccion {
                        Estado = true, Respuesta = Mensajes.MensajeRecuperacionClave, EntidadID = long.Parse(numero)
                    });
                }
                catch (Exception ex)
                {
                    ex.ToString();
                    return(new RespuestaTransaccion {
                        Estado = false, Respuesta = Mensajes.MensajeUsuarioNoExiste
                    });
                }
            }
            catch (Exception ex)
            {
                return(new RespuestaTransaccion {
                    Estado = false, Respuesta = Mensajes.MensajeTransaccionFallida + " ;" + ex.Message.ToString()
                });
            }
        }
Exemplo n.º 13
0
        public void Setters_ShouldSetPropertiesCorrectly()
        {
            // Arrange
            var expected = this.Fixture.Create <string>();
            var sut      = new ForgotViewModel();

            // Act
            sut.Email = expected;
            // Assert
            Assert.AreSame(expected, sut.Email);
        }
Exemplo n.º 14
0
        public void ForgotViewModel_Tests()
        {
            ForgotViewModel view = new ForgotViewModel()
            {
                Email = "*****@*****.**"
            };

            var str = view.Email;

            Assert.IsTrue(true, str);
        }
        public void ForgotViewModel_ShouldSetAllPropertiesCorrectly()
        {
            // Arrange
            var forgotViewModel = new ForgotViewModel();

            // Act
            forgotViewModel.Email = "*****@*****.**";

            // Assert
            Assert.AreEqual("*****@*****.**", forgotViewModel.Email);
        }
Exemplo n.º 16
0
        public void Models_ForgotViewModel_Default_Instantiate_Should_Pass()
        {
            //arrange
            var test        = new ForgotViewModel();
            var expectEmail = "*****@*****.**";

            //act
            test.Email = expectEmail;

            //assert
            Assert.AreEqual(expectEmail, test.Email, TestContext.TestName);
        }
 public ActionResult Index(ForgotViewModel model)
 {
     if (!ModelState.IsValid)
     {
         var errMessage = string.Join(", ", ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage));
         return(Json(new { status = false, message = errMessage }, JsonRequestBehavior.AllowGet));
     }
     else
     {
         return(Json(new { status = false, message = "There was a problem. Please try again later." }, JsonRequestBehavior.AllowGet));
     }
 }
Exemplo n.º 18
0
        public void EmailProp_WhenValidParametersArePasedToId_ShouldSetCorerectly()
        {
            // Arrange
            var viewModel = new ForgotViewModel();
            var testEmail = "*****@*****.**";

            // Act
            viewModel.Email = testEmail;

            // Assert
            Assert.AreEqual(testEmail, viewModel.Email);
        }
        public async Task <ActionResult> ForgotPassword(ForgotViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var    password = Guid.NewGuid().ToString();
                    string hash     = "";
                    for (int i = 0; i < 7; i++)
                    {
                        hash += password[i].ToString();
                    }
                    user.PasswordHash = UserManager.PasswordHasher.HashPassword(hash);
                    var request = await UserManager.UpdateAsync(user);

                    if (request.Succeeded)
                    {
                        var a = await Bll.DB_Action().Add(new DataAccessLayer.AdoModel.Action
                        {
                            User_Id   = user.Id,
                            Message   = hash,
                            Completed = false
                        });

                        if (a.success)
                        {
                            ModelState.AddModelError("", "Şifreniz Güncellendi! Size Mail Olarak Gönderilecektir.");
                        }
                        else
                        {
                            ModelState.AddModelError("", "Şifreniz Güncellendi! Fakat Mail Gönderilemiyor. Yönetici İle İletişime Geçiniz!");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Kullanıcı Bulunamadı!");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Kullanıcı Bulunamadı!");
                }
            }
            else
            {
                ModelState.AddModelError("", "Şifreniz Değiştirilemedi!");
            }
            return(View());
        }
Exemplo n.º 20
0
        public ActionResult GetEmail(ForgotViewModel model)
        {
            if (model.Email == null)
            {
                return(View());
            }
            var user  = _DbContext.Users.Single(c => c.Email == model.Email);
            var user1 = new ForgotViewModel
            {
                Email    = user.Email,
                Question = user.Question
            };

            return(View("Forgot", user1));
        }
Exemplo n.º 21
0
        public async Task <IActionResult> ForgotPost([FromServices] Mailgun mailgun)
        {
            var request  = HttpContext.Request;
            var formData = await request.ReadFormAsync();

            var forgotUser = formData["forgot-user"].FirstOrDefault() ?? string.Empty;

            bool isEmail = forgotUser.Contains('@');
            var  user    = isEmail ?
                           await _userManager.FindByEmailAsync(forgotUser) :
                           await _userManager.FindByNameAsync(forgotUser);

            var model = new ForgotViewModel {
                PreviousUserName = forgotUser
            };

            if (user is null)
            {
                var word = isEmail ? "email" : "user";
                model.Error = $"Unable to find user associated with '{forgotUser}'.";
            }
            else
            {
                var token = await _userManager.GeneratePasswordResetTokenAsync(user);

                // https://stackoverflow.com/a/38311283
                // https://stackoverflow.com/a/43412134
                var path  = Url.Action(nameof(Reset), new { userId = user.Id, token = token });
                var host  = request.Scheme + "://" + request.Host;
                var url   = host + path;
                var email = new Email
                {
                    From     = mailgun.DefaultSender,
                    To       = ImmutableArray.Create(user.Email),
                    Bcc      = mailgun.DefaultBcc,
                    Subject  = $"DEJARIX - Reset password for {user.UserName}",
                    TextBody = "Visit this URL to reset your password at DEJARIX: " + url,
                    HtmlBody = $"<h2>DEJARIX Password Reset</h2><p>Click <a href='{url}'>here</a> to reset your password.</p>"
                };

                var response = await mailgun.SendEmailAsync(email);

                model.Success = "An email has been sent!";
            }

            return(View("Forgot", model));
        }
Exemplo n.º 22
0
        public async Task <ActionResult> ResendEmailConfirmation(ForgotViewModel model)
        {
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user != null)
            {
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

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

            return(RedirectToAction("ConfirmationSent"));
        }
Exemplo n.º 23
0
        public async Task <ActionResult> ForgotPassword(ForgotViewModel model)
        {
            var user = this.modelContext
                       .Users
                       .FirstOrDefault(x => x.EmailConfirmed == true && x.Email == model.Email);

            if (user == null || !user.EmailConfirmed)
            {
                // Don't reveal that the user does not exist or is not confirmed
                return(View("ForgotPasswordConfirmation"));
            }
            user.resetPassToken = UniqueKeyUtil.GetUniqueKey(16);
            await EnviarMailRecuperoPassword(user);

            this.modelContext.SaveChanges();
            return(View("ForgotPasswordConfirmation"));
        }
Exemplo n.º 24
0
        public async Task <ActionResult> Forgot(ForgotViewModel model)
        {
            ApplicationDbContext          context     = new ApplicationDbContext();
            UserStore <ApplicationUser>   store       = new UserStore <ApplicationUser>(context);
            UserManager <ApplicationUser> UserManager = new UserManager <ApplicationUser>(store);
            var user = UserManager.FindByEmail(model.Email);

            if (model.Question == user.Question && model.Answer == user.Answer)
            {
                String          hashedNewPassword = UserManager.PasswordHasher.HashPassword("123456");
                ApplicationUser cUser             = await UserManager.FindByIdAsync(user.Id);

                await store.SetPasswordHashAsync(cUser, hashedNewPassword);

                await store.UpdateAsync(cUser);
            }
            return(RedirectToAction("Index", "Home"));
        }
        public async Task <IActionResult> ForgotPassword(ForgotViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByEmailAsync(model.Email);

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

                    var PasswordResetLink = Url.Action("ResetPassword", "Account", new { Email = model.Email, token = tokens }, Request.Scheme);
                    logger.Log(LogLevel.Warning, PasswordResetLink);
                    return(View("ForgotPasswordConfirmation"));
                }
                return(View("ForgotPasswordConfirmation"));
            }
            return(View(model));
        }
Exemplo n.º 26
0
 public ActionResult HandleForgotPass(ForgotViewModel model)
 {
     if (ModelState.IsValid)
     {
         var user = UserDatabaseHelper.Instance.GetUserByEmail(model.Email);
         if (user != null)
         {
             var chars       = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
             var random      = new Random();
             var newPassword = new string(
                 Enumerable.Repeat(chars, 8)
                 .Select(s => s[random.Next(s.Length)])
                 .ToArray());
             string passHash  = EventZoneUtility.Instance.HashPassword(newPassword);
             var    isUpdated = UserDatabaseHelper.Instance.ResetPassword(model.Email, passHash);
             if (isUpdated)
             {
                 MailHelpers.Instance.SendMailResetPassword(model.Email, newPassword);
                 return(Json(new
                 {
                     state = 1,
                     message = "Reset Password Successfully"
                 }));
             }
             return(Json(new
             {
                 state = 0,
                 message = "Something Wrong! Please Try Again Later"
             }));
         }
         return(Json(new
         {
             state = 0,
             message = "We Couldn't Find Your Email in Our Database"
         }));
     }
     return(Json(new
     {
         state = 0,
         message = "The E-mail format is wrong !"
     }));
 }
Exemplo n.º 27
0
        public ActionResult RecoveryPassword(ForgotViewModel formulario)
        {
            try
            {
                Resultado = UsuarioDAL.RecuperarClave(formulario);
                string enlace = GetUrlSitio(Url.Action("Index", "Login"));

                string body = GetEmailTemplate("TemplateResetClaveUsuario");
                body = body.Replace("@ViewBag.EnlaceDirecto", enlace);
                body = body.Replace("@ViewBag.EnlaceSecundario", enlace);
                body = body.Replace("@ViewBag.Usuario", formulario.Login);
                body = body.Replace("@ViewBag.Contrasenia", Resultado.EntidadID.ToString());


                if (Resultado.Estado)
                {
                    var notificacion = NotificacionesDAL.CrearNotificacion(new Notificaciones
                    {
                        NombreTarea                  = "Reset Clave",
                        DescripcionTarea             = "El usuario olvidó su contraseña.",
                        NombreEmisor                 = nombreCorreoEmisor,
                        CorreoEmisor                 = correoEmisor,
                        ClaveCorreo                  = claveEmisor,
                        CorreosDestinarios           = formulario.Login,
                        AsuntoCorreo                 = "RECUPERAR CLAVE",
                        NombreArchivoPlantillaCorreo = TemplateNotificaciones,
                        CuerpoCorreo                 = body,
                        AdjuntosCorreo               = "",//ruta,
                        FechaEnvioCorreo             = DateTime.Now,
                        Empresa = "",
                        Canal   = CanalNotificaciones,
                        Tipo    = "USUARIO",
                    });
                }
                return(Json(new { Resultado }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Resultado.Respuesta = Resultado.Respuesta + ";" + ex.Message;
                return(Json(new { Resultado }, JsonRequestBehavior.AllowGet));
            }
        }
Exemplo n.º 28
0
        public IActionResult ForgotPassword(ForgotViewModel forgotView)
        {
            if (!ModelState.IsValid)
            {
                return(View(forgotView));
            }
            string fixemail = FixText.FixEmail(forgotView.Email);
            User   user     = _userService.GetUserByEmail(fixemail);

            if (user == null)
            {
                ModelState.AddModelError("Email", "کاربری یافت نشد");
                return(View(forgotView));
            }
            string body = _viewRenderService.RenderToStringAsync("_ForgotPasswordEmail", user);

            SendEmail.Send(user.Email, "تغییر کلمه عبور", body);
            ViewBag.IsSuccess = true;
            return(View());
        }
        public IActionResult Forgot(ForgotViewModel vm)
        {
            ViewData["status"] = "";

            if (ModelState.IsValid)
            {
                try
                {
                    SalesforceService.Response emailResponse = SalesforceService.SendEmail(_sfdcTokenManager.instance_url, _sfdcTokenManager.access_token, vm.EmailAddress).Result;
                    _logger.LogInformation("Email Response Code: {0}", emailResponse.code);

                    ViewData["status"] = (emailResponse.code == "10008" ? "Password reset email has been sent" : "Something went wrong");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                }
            }

            return(View(vm));
        }
Exemplo n.º 30
0
        public ActionResult ForgotPassword(ForgotViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = repositoryUser.UserIEmum.Where(p => p.Email.Equals(model.Email)).FirstOrDefault();
                if (user != null)
                {
                    //Send Email with password
                    EMailPasswordSender(user.Email, user.Password);
                    return(View("ForgotPasswordConfirmation"));
                }
                else
                {
                    ModelState.AddModelError("", "Your Email is not exists");
                    return(View());
                }
            }


            // If we got this far, something failed, redisplay form
            return(View(model));
        }