Example #1
0
        public async Task <IActionResult> Forgotpassword(ForgotPasswordVM forgotVm)
        {
            if (!ModelState.IsValid)
            {
                return(View(forgotVm));
            }

            User user = await userManager.FindByEmailAsync(forgotVm.Email);

            if (user == null)
            {
                ModelState.AddModelError("Email", "No account found to match the email you specified. Make sure you enter the correct email.");
                return(View(forgotVm));
            }
            string passwordResetToken = await userManager.GeneratePasswordResetTokenAsync(user);

            #region Sending Email Account Restoration Message
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.UseDefaultCredentials = false;
            client.EnableSsl             = true;
            client.Credentials           = new NetworkCredential(configuration["ConnectionStrings:SmtpClientCredentialEmail"], configuration["ConnectionStrings:SmtpClientCredentialPassword"]);

            MailMessage message = new MailMessage(configuration["ConnectionStrings:SmtpClientCredentialEmail"], forgotVm.Email);
            message.IsBodyHtml = true;
            message.Subject    = "Account recovery";
            message.Body       = $"<table style='width:100%;background-color:#292C34;padding:50px'><thead style ='width:100%;display:flex;justify-content:center;'><tr style ='width:100%;display:flex;justify-content:center;'><th style ='width:100%;color:#7e0f9a;font-family:Roboto, sans-serif;font-weight:400;font-size:50px'>Family Tree</th></tr><thead><tbody><tr><td style ='padding:30px 0px;color:white;font-family:Roboto Condensed, sans-serif;font-size:20px;text-align:center;'>Dear user, please click on the 'Restore Account' button below to restore your account.</td></tr><tr><td style ='font-family:Roboto Condensed, sans-serif;text-align:center;'><a href='https://localhost:44341/Account/ChangePassword?userId={user.Id}&passwordResetToken={passwordResetToken}' style ='text-decoration:none;padding:10px 30px;border-radius:3px;background-color:#8d11ff;color:black;font-weight:lighter;font-size:20px;cursor:pointer;'>Restore your account</a></td></tr></tbody></table>";
            await client.SendMailAsync(message);

            #endregion
            TempData["ForgotPassword"] = true;
            return(View());
        }
Example #2
0
        public async Task ForgotPassword(ForgotPasswordVM forgotPasswordVM)
        {
            // Validation
            if (forgotPasswordVM == null)
            {
                throw new ForgotPasswordFailedException("invalid");
            }

            // Retrieve user by email
            User user = await userManager.FindByEmailAsync(forgotPasswordVM.Email);

            if (user == null)
            {
                logger.LogWarning("User not found during forgot password", forgotPasswordVM.Email);

                throw new ForgotPasswordFailedException("invalid");
            }

            // For more information on how to enable account confirmation and password reset please
            // visit https://go.microsoft.com/fwlink/?LinkID=532713

            string code = await userManager.GeneratePasswordResetTokenAsync(user);

            logger.LogInformation("Password reset code:");
            logger.LogInformation(code);

            var callbackUrl = configuration.GetSection("Authentication").GetValue <string>("ResetPasswordURL");

            callbackUrl = callbackUrl.Replace("{{userId}}", user.Id.ToString().ToUpper());
            callbackUrl = callbackUrl.Replace("{{userEmail}}", user.Email.ToString().ToLower());
            callbackUrl = callbackUrl.Replace("{{code}}", Uri.EscapeDataString(code));

            await emailService.SendPasswordResetAsync(forgotPasswordVM.Email, callbackUrl);
        }
Example #3
0
        public async Task <IActionResult> ResetujLozinku(ForgotPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                var user = await userMgr.FindByEmailAsync(model.Email);

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

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

                    PosaljiMail(user, "Resetuj lozinku",
                                "<h3 style=\"color:green; font-weight:bold\"> Resetuj lozinku </h3>" +
                                "Kliknite na link ispod kako biste unijeli vašu novu lozinku. <br/><br/>" +
                                "<a href=\"" + passwordResetLink + "\"> Resetuj lozinku </a><br/>");

                    @TempData["sucess"] = "E-mail je poslan na vašu adresu";
                    @ViewBag.ErrorMsg   = "Provjerite e-mail inbox i potvrdite promjenu vaše lozinke";

                    return(PartialView("RegistrationMessage"));
                }
                @TempData["sucess"] = "Dogodila se greška";
                @ViewBag.ErrorMsg   = "Vaš račun nije aktivan. Prvo morate potvrditi vaš račun!";
                return(PartialView("RegistrationMessage"));
            }

            return(View("ForgotPassword", model));
        }
Example #4
0
        public async Task <ResponseVM> ResetPassword(ForgotPasswordVM forgotPasswordVM)
        {
            using (_userManager)
            {
                var user = await _userManager.FindByNameAsync(forgotPasswordVM.UserName);

                if (user == null)
                {
                    return(new ResponseVM("reset password", false, "User", "User not found."));
                }

                // hashes the answer and compares to the saved in database
                var answerHash = ComputeSha256Hash(forgotPasswordVM.Answer);
                if (answerHash == user.Answer)
                {
                    await _userManager.RemovePasswordAsync(user);

                    await _userManager.AddPasswordAsync(user, forgotPasswordVM.NewPassword);

                    return(new ResponseVM("reset password", true, "User", "You can now login with your new password."));
                }
                else
                {
                    return(new ResponseVM("reset password", false, "User", "Wrong answer!"));
                }
            }
        }
Example #5
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM forgotPasswordVM)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(forgotPasswordVM.Email);

                if (user != null && await _userManager.IsEmailConfirmedAsync(user))
                {
                    var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                    var callBackUrl = Url.Action("ResetPassword", "Auth", new { email = forgotPasswordVM.Email, code = code }, protocol: HttpContext.Request.Scheme);

                    MailMessage mailMessage = new MailMessage();

                    mailMessage.From = new MailAddress("*****@*****.**", "Admin");
                    mailMessage.To.Add(new MailAddress(forgotPasswordVM.Email));
                    mailMessage.Subject    = "Reset Password";
                    mailMessage.IsBodyHtml = true;
                    mailMessage.Body       = $"For reseting password click here: <a href='{callBackUrl}'>link</a>";

                    SmtpClient smtpClient = new SmtpClient("smtp.google.com");

                    smtpClient.Port = 587;
                    smtpClient.UseDefaultCredentials = true;
                    smtpClient.EnableSsl             = true;
                    smtpClient.Credentials           = new NetworkCredential("*****@*****.**", "devilprince2012");
                    smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    smtpClient.Send(mailMessage);

                    return(View("ForgotPasswordConfirmation"));
                }
                //return View("ForgotPasswordConfirmation");
            }
            return(View(forgotPasswordVM));
        }
Example #6
0
        public IActionResult ForgotPassword(ForgotPasswordVM forgotPasswordVM)
        {
            var Email      = forgotPasswordVM.Email;
            var Get        = employeeRepository.GetAll();
            var CheckLogin = Get.FirstOrDefault(e => e.Email == forgotPasswordVM.Email);

            if (CheckLogin != null)
            {
                Guid newPassword = Guid.NewGuid();

                Account account = new Account
                {
                    NIK      = CheckLogin.NIK,
                    Password = newPassword.ToString("N").Substring(0, 8)
                };

                accountRepository.ChangePassword(CheckLogin.NIK, account.Password);

                SendEmailService.GantiPassword(Email, account.Password);

                return(Ok(new { status = HttpStatusCode.OK, message = "New Password Sent" }));
            }
            else
            {
                return(NotFound(new { status = HttpStatusCode.NotFound, message = "No account has this email" }));
            }
        }
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordVM model)
        {
            if (string.IsNullOrWhiteSpace(model.Email))
            {
                return(BadRequest());
            }

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

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

            if (!user.EmailConfirmed)
            {
                return(BadRequest("EmailNotConfirmed"));
            }

            await _userManager.UpdateSecurityStampAsync(user);                      // Generate new security stamp

            var temporaryPwd        = Guid.NewGuid().ToString("n").Substring(0, 6); // Generate a temporary password
            var passwordRequirement = "P" + temporaryPwd + "n1";                    // 숫자, 대소문자 requirement
            var token = await _userManager.GeneratePasswordResetTokenAsync(user);

            var result = await _userManager.ResetPasswordAsync(user, token, passwordRequirement); // Temporary password is now the user's current password

            var emailTemplateVM = new EmailTemplateVM(user.Email, _appSettings.Environment.Equals("Live") ? "https://talchoseon.com/" : "http://*****:*****@talchoseon.com", user.Email, emailFormat.Item1, null, emailFormat.Item2);

            return(new OkResult());
        }
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM thisModel)
        {
            System.Threading.Thread.Sleep(2000);
            ViewBag.Message = "";
            if (ModelState.IsValid)
            {
                ViewBag.Message = "Please check your email to reset your password.";
                var user = await _userManager.FindByEmailAsync(thisModel.Email);

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

                // 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.Link("Default", new { Controller = "AccountRecovery", Action = "ResetPassword", code = code });

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

                return(View("ForgotPassword"));
            }
            return(View("ForgotPassword"));
        }
        public ActionResult SendNewPassword(ForgotPasswordVM model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var mail      = new MailMessage();
                    var loginInfo = new NetworkCredential("*****@*****.**", "Lufthansa224$");
                    mail.From = new MailAddress(model.Email);
                    mail.To.Add(new MailAddress("*****@*****.**"));
                    mail.Subject = "Password reinitialisation";
                    Random r    = new Random();
                    int    code = r.Next(1000, 9999);
                    mail.IsBodyHtml = true;
                    mail.Body       = "Your new password is : " + "<b>" + code + "</b>" + "<br>" + "Use it to sign in";

                    var smtpClient = new SmtpClient("smtp.gmail.com", 587);
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.EnableSsl             = true;
                    smtpClient.Credentials           = loginInfo;
                    smtpClient.Send(mail);

                    // update Aspnetuser
                    var user = UserManager.Users.Where(u => u.Email == model.Email).FirstOrDefault();
                    var newHashedPassword = UserManager.PasswordHasher.HashPassword(code.ToString());
                    user.PasswordHash = newHashedPassword;
                    UserManager.Update(user);
                    appDbContext.SaveChanges();
                    // Change password to our DB
                    Company company = this.db.Companies.Where(c => c.Email == model.Email).FirstOrDefault();
                    if (company != null)
                    {
                        company.Password = code.ToString();
                        db.SaveChanges();
                    }
                    else
                    {
                        Candidate candidate = this.db.Candidates.Where(c => c.Email == model.Email).FirstOrDefault();
                        if (candidate != null)
                        {
                            candidate.Password = code.ToString();
                            db.SaveChanges();
                        }
                        else
                        {
                            return(View());
                        }
                    }
                }
                else
                {
                    return(View());
                }
            }
            catch
            {
                return(View());
            }
            return(View());
        }
Example #10
0
        public async Task <IActionResult> SendPasswordResetLink(ForgotPasswordVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View("ForgotPassword"));
            }
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError(nameof(model.Email), "Nie ma użytkownika o podanym emailu");
                return(View("ForgotPassword"));
            }

            var tokeN = await _userManager.GeneratePasswordResetTokenAsync(user);

            var link = Url.Action("ResetPassword", "Account", new ResetPasswordVM {
                UserId = user.Id, Token = tokeN
            }, protocol: HttpContext.Request.Scheme);
            var res = await _emailSender.SendEmailAsync(user.Email, link, "Reset Password");

            if (!res)
            {
                return(View("ForgotPassword"));
            }

            return(RedirectToAction("Index", "Home"));
        }
Example #11
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Email);

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

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                //Send an email with this link
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

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

                return(View("ForgotPasswordConfirmation"));
            }


            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                var user = await _accountService.FindUserByEmailAsync(model.Email);

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

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713

                var code = await _accountService.GeneratePasswordResetTokenAsync(user);

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

                await _notificationService.SendForgotPasswordNotificationAsync(user, callbackUrl);

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            var user = await userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                List <string> roles = await userManager.GetRolesAsync(user) as List <string>;

                var rol = roleManager.Roles.FirstOrDefault(x => x.Name == roles[0]);

                if (rol.IsExternal)
                {
                    string resetToken = await userManager.GeneratePasswordResetTokenAsync(user);

                    string tokenEncode = System.Web.HttpUtility.UrlEncode(resetToken);

                    CreateModal("exito", "Terminado", "Se ha enviado correo electrónico para completar el proceso.", "Continuar", null, "Redirect('/')", null);
                    return(View(model));
                }
                else
                {
                    CreateModal("error", "Error", "No es posible realizar la operación.", "Continuar", null, "Redirect('/')", null);
                    return(View(model));
                }
            }
            else
            {
                CreateModal("error", "Error", "No se encontró usuario asociado al email", "Continuar", null, "Redirect('/')", null);
                return(View(model));
            }
        }
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordVM vm)
        {
            var user = await _userManager.FindByEmailAsync(vm.Email);

            if (user == null)
            {
                return(BadRequest("Cannot find email"));
            }
            var resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

            //email token to user
            var apiKey           = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
            var client           = new SendGridClient(apiKey);
            var from             = new EmailAddress("*****@*****.**", "Example User");
            var subject          = "You are now registered!";
            var to               = new EmailAddress(user.Email, user.FirstName);
            var plainTextContent = "Reset token: " + resetToken;
            var htmlContent      = "Reset token : " + resetToken;
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response         = await client.SendEmailAsync(msg);

            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                return(Ok("Verified"));
            }
            else
            {
                return(BadRequest(response.StatusCode));
            }
        }
Example #15
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

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

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                await _emailSender.SendEmailAsync(model.Email, "Reset Password",
                                                  $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #16
0
        public IActionResult SendConfirmation(ForgotPasswordVM model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("ForgotPassword"));
            }

            User user = con.Users.SingleOrDefault(i => i.Email == model.Email);

            if (user == null)
            {
                TempData["errorMessage"] = "Email address doesn't exist. Make sure that you enter a valid email address.";
                return(RedirectToAction("ForgotPassword"));
            }
            ChangePasswordCode changepw = con.ChangePasswords.SingleOrDefault
                                              (i => i.UserId == user.Id);

            if (changepw != null)
            {
                if ((DateTime.Now - changepw.Created).TotalHours < 24)
                {
                    TempData["errorMessage"] = "Email has been already sent to this email address";

                    return(RedirectToAction("ForgotPassword"));
                }
                else
                {
                    con.ChangePasswords.Remove(changepw);
                    con.SaveChanges();
                }
            }

            string value = RandomString.GetString(30);

            string link =
                $"{ this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/Login/ChangePassword?value=" + value;

            string message = "Visit this link for password change: \n" + link +
                             "\nIf you don't change your password in next 24 hours this link will disappear " +
                             "will be invalid.";

            EmailSettings.SendEmail(_configuration, user.Username, user.Email, "Change password", message);

            ChangePasswordCode passwordRequest = new ChangePasswordCode
            {
                Value   = value,
                UserId  = user.Id,
                Created = DateTime.Now
            };

            con.ChangePasswords.Add(passwordRequest);

            con.SaveChanges();

            TempData["successMessage"] = "Email for password confirmation is successfully sent. Check your inbox.";

            return(RedirectToAction("Index"));
        }
Example #17
0
        public async Task <string> GenerateResetPasswordTokenAsync(ForgotPasswordVM model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                return(await _userManager.GeneratePasswordResetTokenAsync(user));
            }
            return(null);
        }
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM forgotPasswordVM)
        {
            var response = await httpClient.PostAsJsonAsync("Account/ForgotPassword", forgotPasswordVM);

            string apiResponse = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <ResponseVM <ForgotPasswordVM> >(apiResponse);

            return(new JsonResult(result));
        }
Example #19
0
        public IActionResult ForgotPassword(ForgotPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                User email = _newscontext.Users.FirstOrDefault(x => x.EMail == model.Email && x.IsActive == true);

                if (email != null)
                {
                    string resetcode = Guid.NewGuid().ToString();

                    email.ResetCode = resetcode;

                    _newscontext.SaveChanges();

                    string reseturl = "http://sportsnewsprojectapp.herokuapp.com./Login/Reset/" + resetcode;

                    MimeMessage message = new MimeMessage();

                    MailboxAddress from = new MailboxAddress("SportsNewsTeam", "*****@*****.**");
                    message.From.Add(from);

                    MailboxAddress to = new MailboxAddress(email.Name, email.EMail);
                    message.To.Add(to);

                    message.Subject = "Reset Password";

                    BodyBuilder bodyBuilder = new BodyBuilder();
                    bodyBuilder.TextBody = "Lütfen şifrenizi sıfırlamak için linke tıklayın: " + reseturl;

                    message.Body = bodyBuilder.ToMessageBody();

                    SmtpClient client = new SmtpClient();

                    client.Connect("smtp.gmail.com", 465, true);
                    client.Authenticate("*****@*****.**", "$Rdot3PxrtV9QQpYFzVYA#w%RpU2!BGC5UN8cSXNhAs@iq@GvZ");


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

                    return(RedirectToAction("Login", "Login"));
                }
                else
                {
                    ModelState.AddModelError("Email", "Girmiş olduğunuz Email adresi sistemimizde kayıtlı değil!");
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }
Example #20
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordVM forgotPasswordVM)
        {
            // Validation
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await this.bll.ForgotPassword(forgotPasswordVM);

            return(Ok());
        }
Example #21
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            var user = await userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                List <string> roles = await userManager.GetRolesAsync(user) as List <string>;

                var rol = roleManager.Roles.FirstOrDefault(x => x.Name == roles[0]);

                if (rol.IsExternal)
                {
                    string resetToken = await userManager.GeneratePasswordResetTokenAsync(user);

                    string tokenEncode = System.Web.HttpUtility.UrlEncode(resetToken);

                    ConfirmationEmail confirmEmail = new ConfirmationEmail {
                        Email = user.Email
                    };
                    confirmEmail.CallBack = Url.Action("RecoverPassword", "Account", new
                    {
                        area  = "Identity",
                        token = tokenEncode,   // reset token
                        u     = user.Id        // user token, use GUID user id or Usuario.PublicToken
                    }, protocol: Request.Scheme);

                    Boolean emailSent = EmailComm.SendEmailRecoverPassword(confirmEmail);

                    if (emailSent)
                    {
                        CreateModal("exito", "Terminado", "Se ha enviado correo electrónico para completar el proceso.", "Continuar", null, "Redirect('/')", null);
                        return(View(model));
                    }
                    else
                    {
                        CreateModal("error", "Error", "No se ha podido enviar el email, intente de nuevo mas tarde.", "Continuar", null, "Redirect('/')", null);
                        return(View(model));
                    }
                }
                else
                {
                    CreateModal("error", "Error", "No es posible realizar la operación.", "Continuar", null, "Redirect('/')", null);
                    return(View(model));
                }
            }
            else
            {
                CreateModal("error", "Error", "No se encontró usuario asociado al email", "Continuar", null, "Redirect('/')", null);
                return(View(model));
            }
        }
Example #22
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new { status = false, message = "Parameters are not correct" }));
            }
            try
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    //check if associated account is confirmed by linked email/phone number
                    if ((!_userManager.IsEmailConfirmedAsync(user).Result) || (!_userManager.IsPhoneNumberConfirmedAsync(user).Result))
                    {
                        return(Ok(new { status = false, message = "Account is not verified." }));
                    }
                    int otpCode = GlobalMethods.GenerateOTP();
                    user.OTP            = otpCode;
                    user.EmailConfirmed = false;

                    IdentityResult result = await _userManager.UpdateAsync(user);

                    if (!result.Succeeded)
                    {
                        return(BadRequest(new { status = false, message = result.Errors.First().Description }));
                    }
                    //send otp via email

                    //----------SendGrid to be implemented----------//

                    ResponseData responseData = new ResponseData();


                    //----------EndSendGridLogic----------//

                    MessageSender messageSender = new MessageSender();

                    return(Ok(new { status = true, message = "OTP sent to your registered Email" }));
                }
                else
                {
                    return(Ok(new { status = false, message = "Sorry,Could not found the account with " + model.Email }));
                }
            }
            catch (Exception ae)
            {
                return(BadRequest(new { status = false, message = ae.Message.ToString() }));
            }
        }
        public async Task <ActionResult> ForgotPassword([FromBody] ForgotPasswordVM model)
        {
            // This is called when the user clicks "forgot my password", and then submits an email address
            if (!ModelState.IsValid)
            {
                return(BadRequest("There is something wrong with the request payload")); // TODO: Return friendlier validation errors
            }

            try
            {
                var user = await _userManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    return(BadRequest("Could not find the specified email"));
                }

                // Rely on the injected user manager to generate a token
                string passwordResetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

                // In a bigger app, the SPA and the API should be independent and the API can't't know where
                // the SPA is and the setup below would have to change, but for our purposes this is fine for
                // now and a lot easier as the SPA is available and already comes with all the styling
                string uri = $"https://{Request.Host}/{Request.PathBase}reset-password";

                uri = QueryHelpers.AddQueryString(uri, "userId", user.Id);
                uri = QueryHelpers.AddQueryString(uri, "passwordResetToken", passwordResetToken);

                // Prepare the email content
                string htmlEmail = Util.Util.BSharpEmailTemplate(
                    message: "To reset your password please click below",
                    hrefToAction: uri,
                    hrefLabel: "Reset My Password");

                // Send the email using injected sender
                await _emailSender.SendEmail(
                    destinationEmailAddress : model.Email,
                    subject : "Password Reset Link",
                    htmlEmail : htmlEmail);

                // All good
                return(Ok());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.StackTrace);
                return(BadRequest(ex.Message));
            }
        }
Example #24
0
        public ActionResult ForgotPassword(ForgotPasswordVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (!AccountService.HasSameEmail(model.Email))
            {
                ModelState.AddModelError("", ErrorCode.FORGOTPWDNOEMAIL.ToDescription());
                return(View(model));
            }

            SendResetPasswordLink(model.Email);
            return(RedirectToAction("ForgotPasswordConfirm"));
        }
Example #25
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    //// Don't reveal that the user does not exist
                    //return Ok();

                    // For CRM purposes
                    return(NotFound("email-not-found"));
                }

                // Check if email is confirmed, if required in Startup settings
                // In startup: options.SignIn.RequireConfirmedEmail = true;
                if (!(await userManager.IsEmailConfirmedAsync(user)))
                {
                    //// Don't reveal that the user does not exist
                    //return Ok();

                    // OR

                    return(NotFound("email-not-confirmed"));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713

                var code = await userManager.GeneratePasswordResetTokenAsync(user);

                //var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                var callbackUrl = configuration.GetSection("EmailSettings").GetValue <string>("PasswordResetURL");
                callbackUrl = callbackUrl.Replace("{{userId}}", user.Id.ToString().ToLower());
                callbackUrl = callbackUrl.Replace("{{userEmail}}", user.Email.ToString().ToLower());
                callbackUrl = callbackUrl.Replace("{{code}}", Uri.EscapeDataString(code));

                await emailSender.SendEmailAsync(model.Email, "Reset Password",
                                                 $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");

                return(Ok());
            }

            // If we got this far, something failed
            return(BadRequest());
        }
Example #26
0
        public async Task <IActionResult> Index(ForgotPasswordVM model)
        {
            logger.Trace("POST Index()");
            if (!ModelState.IsValid)
            {
                logger.Trace("Model is not valid - displaying form");
                return(View(model));
            }

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

            if (user == null)
            {
                logger.Trace("User {0} does not exist - pretending to send notification", model.Email);
                ViewBag.CallbackUrl = "/";
                return(View("CheckEmail"));
            }
            if (!(await userManager.IsEmailConfirmedAsync(user)))
            {
                logger.Trace("User {0} has not confirmed yet - redirecting to registration", model.Email);
                return(RedirectToAction("Index", "RegisterAccount"));
            }

            logger.Trace("Generating code for password reset");
            var code = await userManager.GeneratePasswordResetTokenAsync(user);

            logger.Trace("Code = {0}", code);
            var callbackUrl = Url.Action("Callback", "ForgotPassword",
                                         new { userId = user.Id, code = code, area = "Account" },
                                         protocol: Context.Request.Scheme);

            logger.Trace("Callback URL = {0}", code);
            if (!WebConfiguration.Instance.DevelopmentMode)
            {
                logger.Trace("In Prod Mode - initiating email confirmation");
                var notified = await Notifier.Instance.SendResetPasswordLinkAsync(user, callbackUrl);

                if (!notified.Successful)
                {
                    logger.Error("Notification to {0} failed", model.Email);
                    ModelState.AddModelError("", "Could not send reset password link");
                    return(View(model));
                }
            }
            ViewBag.CallbackUrl = callbackUrl;
            return(View("CheckEmail"));
        }
Example #27
0
        public async Task <ForgotPasswordVM> GetSecurityQuestion(string username)
        {
            using (_userManager)
            {
                var user = await _userManager.FindByNameAsync(username);

                ForgotPasswordVM forgotPasswordVM = null;
                if (user != null)
                {
                    forgotPasswordVM = new ForgotPasswordVM
                    {
                        UserName = user.UserName,
                        Question = user.Question
                    };
                }
                return(forgotPasswordVM);
            }
        }
Example #28
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //Validates existense of user
            var user = await _userMngr.FindByEmailAsync(model.EmailAddress);

            if (user == null)
            {
                ModelState.AddModelError("", $"User with email address {model.EmailAddress} does not exist!");
                return(View(model));
            }

            //Generates password recovery token
            var token = _userMngr.GeneratePasswordResetTokenAsync(user);

            //Generates an action link to route a user to a recovery page with token
            var resetLink = Url.Action("ResetPassword", "Account", new { token, user.Email }, Request.Scheme);

            //sends the reset link as a mail to the user
            var mailDetails = new MailDetails
            {
                MessageTitle = "PASSWORD RESET",
                MessageBody  = $"Click the link to reset your password. {resetLink}",
                Recievers    = new List <string> {
                    user.Email
                }
            };

            try
            {
                _mailService.SendMail(mailDetails);
                ViewBag.SuccessMsg = "Email sent. Check your inbox";
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
            }

            return(View());
        }
        public async Task <ActionResult <ResponseVM> > ResetPassword([FromBody] ForgotPasswordVM forgotPasswordVM)
        {
            if (ModelState.IsValid)
            {
                var res = await userService.ResetPassword(forgotPasswordVM);

                if (res.IsSuccess)
                {
                    return(Ok(res));
                }
                else
                {
                    return(BadRequest(res));
                }
            }
            else
            {
                return(BadRequest("Something went wrong"));
            }
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await _account.ForgotPasswordAsync(model.Email);

                    return(View("ForgotPasswordConfirmation", model));
                }
                catch (Exception ex)
                {
                    Logger.GetLogger().Error("ForgotPassword failed.", ex);
                    ModelState.AddModelError("", ex);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
 public ActionResult forgotpassword(ForgotPasswordVM model)
 {
     try
     {
         if (ModelState.IsValid)
         {
             var result = accountManager.ProcessPasswordRecovery(model.Email);
             if (result != null)
             {
                 return RedirectToAction("forgotpasswordemailsent");
             }
             ModelState.AddModelError("", "We do not see an account with that email address!");
             return View();
         }
     }
     catch (Exception ex)
     {
         ModelState.AddModelError("", "Error in processing the your request");
     }
     return View(model);
 }
        public async Task<ActionResult> ForgotPassword(ForgotPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

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

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