public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                // If user has to activate his email to confirm his account, the use code listing below
                //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                //{
                //    return Ok();
                //}
                if (user == null)
                {
                    return(Ok());
                }
                var modelPassword = new SetPasswordBindingModel();
                modelPassword.NewPassword     = PasswordGeneratorService.GeneratePassword(6);
                modelPassword.ConfirmPassword = modelPassword.NewPassword;
                modelPassword.Code            = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var result = SetPassword(user, modelPassword);
                await UserManager.SendEmailAsync(user.Id, "Сброс пароля", $"Ваш новый пароль::" + modelPassword.NewPassword);

                return(Ok());
            }

            // If we got this far, something failed, redisplay form
            return(BadRequest(ModelState));
        }
Example #2
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordBindingModel bm)
        {
            if (bm == null)
            {
                return(BadRequest("The payload must not be null."));
            }

            if (string.IsNullOrWhiteSpace(bm.Email))
            {
                return(BadRequest("An email address is required."));
            }

            var user = await _userService.GetUserByEmail(bm.Email);

            if (user == null)
            {
                return(NotFound("A user with that email address doesn't exist."));
            }

            var token = Helpers.GenerateToken("email", bm.Email, 12);

            var email = EmailTemplates.GetForgotPasswordEmail(
                $"{Config.FrontEndUrl}/auth/reset-password?token={token}");
            await _emailService.SendAsync(bm.Email, "Forgot Password", email);

            _logger.LogInformation("Forgot password email sent successfully.");

            return(Ok("Your password reset email has been sent."));
        }
Example #3
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                //If user has to activate his email to confirm his account, the use code listing below
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return(Ok());
                }

                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var encodedCode = HttpUtility.UrlEncode(code);
                var callbackUrl = new Uri(@"http://localhost:49609/Account/ResetPassword?userid=" + user.Id + "&code=" + encodedCode);
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return(Ok());
            }

            // If we got this far, something failed, redisplay form
            return(BadRequest(ModelState));
        }
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                string body;
                var    user = await UserManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    string code        = UserManager.GeneratePasswordResetToken(user.Id);
                    var    callbackUrl = string.Format("https://bashbook.in/#/auth/reset-password?code={0}", code);

                    using (StreamReader reader =
                               new StreamReader(HostingEnvironment.MapPath("~/Content/Templates/Email/ForgotPassword.html")))
                    {
                        body = reader.ReadToEnd();
                    }

                    body = body.Replace("{{name}}", "User");
                    body = body.Replace("{{url}}", callbackUrl);

                    await UserManager.SendEmailAsync(user.Id, "Reset Password", body);

                    return(Ok());
                }

                return(BadRequest("Email not existed. Please contact admin"));
            }
            return(BadRequest("Invalid email. Please try again"));
        }
Example #5
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (this.ModelState.IsValid)
            {
                var user = await this.UserManager.FindByEmailAsync(model.Email);

                if (user == null || !(await this.UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    this.ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
                    return(this.BadRequest(this.ModelState));
                }

                var code = await this.UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = this.Url.Content("~/account/resetpassword?email=")
                                  + HttpUtility.UrlEncode(model.Email) + "&code=" + HttpUtility.UrlEncode(code);

                var notification = new AccountNotificationModel {
                    Url = callbackUrl, DisplayName = user.UserName
                };

                var body = ViewRenderer.RenderView("~/Views/Mailer/PasswordReset.cshtml", notification);
                await this.UserManager.SendEmailAsync(user.Id, "DurandalAuth reset password", body);

                return(this.Ok());
            }

            // If we got this far, something failed
            return(this.BadRequest(this.ModelState));
        }
Example #6
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                // If user has to activate his email to confirm his account, the use code listing below
                //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                //{
                //    return Ok();
                //}
                if (user == null)
                {
                    return(Ok());
                }

                // 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);

                string callbackUrl = Url.Link("ResetPassword", new { email = user.Email, code = code });
                await UserManager.SendEmailAsync(user.Id, "Reset Password - Employee List", $"Please reset your password by clicking <a href=\"{callbackUrl}\">here</a><br>Or copy link {callbackUrl}");

                return(Ok());
            }

            // If we got this far, something failed, redisplay form
            return(BadRequest(ModelState));
        }
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var user = await this.AppUserManager.FindByEmailAsync(model.Email);

                if (user == null && !(await this.AppUserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return(BadRequest(ModelState));
                }

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

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

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

                return(Ok());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }

                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return(BadRequest("Your email address has not yet been confirmed or doesn't exist in our system, so it cannot be used to reset your password."));
                }

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

                string newPass = Membership.GeneratePassword(6, 0);
                newPass = Regex.Replace(newPass, @"[^a-zA-Z0-9]", m => rnd.Next(0, 9).ToString());

                var result = await UserManager.ResetPasswordAsync(user.Id, code, newPass);

                await ServerUtils.SendEmail(user.Email, user.UserName, "Temporary Skin Selfie password", "Your temporary password is '" + newPass + "'. Please log into the Skin Selfie application using this password and change it to something memorable in the settings area.");

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.ToString()));
            }
        }
Example #9
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _appUserManager.FindByEmailAsync(model.Email);

                if (user == null || !(await _appUserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist
                    return(BadRequest("Something is wrong,please try again later"));
                }

                string generatedCode = await _appUserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = string.Format(@"{0}/{1}", model.ResetURL, HttpUtility.UrlEncode(generatedCode));

                string bodyHtmlEmail = Helpers.CreateBodyemailForgotPassword(user, callbackUrl);

                await _appUserManager.SendEmailAsync(user.Id, "Reset Password", bodyHtmlEmail);

                return(Ok(new JsonResponse {
                    Success = true, Message = "Please check your email to reset your password."
                }));
            }

            return(BadRequest(ModelState));
        }
Example #10
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (this.ModelState.IsValid)
            {
                var user = await this.userManager
                           .FindByEmailAsync(model.Email);

                if (user == null || !(await this.userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(this.RedirectToAction(nameof(this.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 this.userManager
                           .GeneratePasswordResetTokenAsync(user);

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

                await this.emailSender
                .SendEmailAsync(model.Email,
                                AccountConstants.ResetPassword,
                                string.Format(AccountConstants.ResetPasswordLink, callbackUrl));


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

            // If we got this far, something failed, redisplay form
            return(this.View(model));
        }
Example #11
0
        [Route("ForgotPassword")] //  this is NEW
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            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(Ok("ForgotPasswordConfirmation"));
                }

                try
                {
                    // use AccessFailedCount user property to store the change password attempts
                    ForgotPassword rec = fpctr.GetForgotPasswordByUserid(user.Id);
                    if (rec == null || rec.createdDt.Day != DateTime.Today.Day)
                    {
                        string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                        string resetpasswordurl = WebConfigurationManager.AppSettings["ResetPasswordUrl"];
                        string callbackUrl      = resetpasswordurl + "?code=" + code;
                        string body             = "Please confirm your identity by clicking on this: <a href=\"" + callbackUrl + "\">Link</a>. Confirmation email will be sent to you.";

                        IdentityMessage messageIdentity = new IdentityMessage();
                        messageIdentity.Body        = body;
                        messageIdentity.Destination = user.Email;
                        messageIdentity.Subject     = "Reset Password";

                        UserManager.EmailService = new EmailService(UserManager, user);
                        await UserManager.EmailService.SendAsync(messageIdentity);

                        return(Ok("ForgotPasswordConfirmation"));
                    }
                    else
                    {
                        if (rec.createdDt.Day == DateTime.Today.Day)
                        {
                            ModelState.AddModelError("Message", "Changing password multiple times in a day is not permitted!");
                            return(BadRequest(ModelState));
                        }
                    }
                }
                catch (Exception ex)
                {
                    string str = ex.InnerException.Message;
                }
                return(BadRequest(ModelState));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Example #12
0
        public Task <MessageViewModel> ForgotPassword(string emailAddress)
        {
            var bm = new ForgotPasswordBindingModel
            {
                EmailAddress = emailAddress
            };

            return(_authService.ForgotPassword(bm));
        }
Example #13
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = await UserManager.FindByNameAsync(model.Email);

            return(Ok(user));
        }
Example #14
0
        public async Task <HttpResponseMessage> ForgotPassword(ForgotPasswordBindingModel model)
        {
            string UserId = string.Empty;

            //For checking Static Email For Sending Mail
            bool isStaticEmailStatus = Convert.ToBoolean(WebConfigurationManager.AppSettings["UseStaticEmailForSendingMail"]);

            if (ModelState.IsValid)
            {
                var user = await _accountApplicationService.FindUserByEmailAsync(model.Email);

                if (user == null || !(await _accountApplicationService.IsEmailConfirmedAsync(user.Id)))
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, new ApplicationResultModel()
                    {
                        Success = false, Error = ResourceStrings.EmailValidCheck
                    }));
                }

                try
                {
                    UserId = user.Id;

                    var token = await _accountApplicationService.GeneratePasswordResetTokenAsync(user.Id);

                    var activationLink = string.Format(WebConfigurationManager.AppSettings["WebURL"] + "forgotPassword?emailId=" + HttpUtility.UrlEncode(user.UserName) + "&token=" + HttpUtility.UrlEncode(token));

                    List <string> attachments = new List <string>();
                    string        subject     = "Reset Password";

                    //  return Request.CreateResponse(HttpStatusCode.OK, await _forgotPasswordApplicationService.SendForgetPasswordLinkAsync(user.Email, user.UserName, subject, activationLink.ToString(), isStaticEmailStatus));
                    return(Request.CreateResponse(HttpStatusCode.OK, new ApplicationResultModel()
                    {
                        Success = true, Result = null
                    }));
                }
                catch (Exception ex)
                {
                    // _logger.Error("Error For {UserId} and {OrgId}", UserId, (int)(await _userApplicationService.GetUserDetailsByUserIdAsync(UserId)).Result);
                    return(Request.CreateResponse(HttpStatusCode.InternalServerError, new ApplicationResultModel()
                    {
                        Success = false
                    }));
                }
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new ApplicationResultModel()
                {
                    Success = false, Error = ResourceStrings.EmailValidCheck
                }));
            }
        }
Example #15
0
        public ActionResult ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(
                new KeyValuePair <string, string>("Email", model.Email));

            var encodedParameters = new FormUrlEncodedContent(parameters);

            var httpClient = new HttpClient();

            var response = httpClient
                           .PostAsync("http://localhost:64310/api/account/forgotpassword",
                                      encodedParameters)
                           .Result;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(RedirectToAction("ForgotPasswordSuccess"));
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                var data = response.Content.ReadAsStringAsync().Result;

                var errors = JsonConvert.DeserializeObject <Error>(data);

                foreach (var key in errors.ModelState)
                {
                    foreach (var error in key.Value)
                    {
                        ModelState.AddModelError(key.Key, error);
                    }
                }

                return(View(model));
            }
            else
            {
                //Create a log for the error message

                ModelState.AddModelError("", "Sorry. An unexpected error has occured. Please try again later");
                return(View(model));
            }
        }
Example #16
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    return(NotFound());
                }
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href='http://localhost:65255/account/resetpassword?code=" + code + "'>here</a>");

                return(Ok(model));
            }
            return(Ok(model));
        }
Example #17
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    return(NotFound());
                }
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by " + code);

                return(Ok(model));
            }
            return(Ok(model));
        }
Example #18
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            emailService = DIContainerST.GetInstance().Resolve <IEmailService>();
            string email1 = "*****@*****.**";

            if (user != null)
            {
                string link = string.Format("http://localhost:6251/index.html#!/resetpassword?username={0}", model.Email);
                emailService.SendEmail(/*model.Email*/ email1, Const.EmailForgotPasswordSubject, string.Format(Const.EmailForgotPasswordBody, link));
            }

            return(Ok());
        }
Example #19
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordBindingModel bm)
        {
            if (bm == null)
            {
                return(BadRequest("The payload must not be null."));
            }

            if (string.IsNullOrWhiteSpace(bm.Email))
            {
                return(BadRequest("An email address is required."));
            }

            var user = await _userService.GetUserByEmail(bm.Email);

            if (user == null)
            {
                return(NotFound("A user with that email address doesn't exist."));
            }

            var token = Helpers.GetToken(user, 12, TokenType.Reset);

            var email = EmailTemplates.GetForgotPasswordEmail(
                $"{Config.FrontEndUrl}/auth/reset-password?token={token}");
            var response = await _emailService.SendAsync(bm.Email, "Forgot Password", email);

            if (response.IsSuccessful)
            {
                _logger.LogInformation("Forgot password email sent successfully.");
                return(Ok(new GenericViewModel
                {
                    Message = "Your password reset email has been sent."
                }));
            }

            _logger.LogError("The email was not sent successfully.");
            _logger.LogError(response.ErrorException, response.ErrorMessage);
            return(StatusCode((int)HttpStatusCode.InternalServerError, new GenericViewModel
            {
                Message = "An error occurred when sending the recovery email."
            }));
        }
Example #20
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var participant = await UserManager.FindByEmailAsync(model.Email);

            if (participant != null)
            {
                if (participant.SecurityStamp == null)
                {
                    var ir = await UserManager.UpdateSecurityStampAsync(participant.Id);

                    if (!ir.Succeeded)
                    {
                        throw new FieldAccessException("Could not UpdateSecurityStampAsync - following errors:" + string.Join("\r\n", ir.Errors));
                    }
                }
                var resetEmail = new ForgotPasswordTemplate
                {
                    Token    = await UserManager.GeneratePasswordResetTokenAsync(participant.Id),
                    UserId   = participant.Id,
                    UserName = participant.UserName
                };

                using (var mail = new MailMessage())
                {
                    mail.To.Add(model.Email);
                    mail.CreateHtmlBody(resetEmail);
                    using (var client = new SmtpClient())
                    {
                        client.Send(mail);
                    }
                }
            }
            //return GetErrorResult(result);

            return(Ok());
        }
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            var user = await UserManager.FindByNameAsync(model.UserEmail);

            if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            {
                return(BadRequest("The user doesn't exist"));
            }
            string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

            code = HttpUtility.UrlEncode(code);
            var callbackUrl = this.Url.Link("DefaultApi", new { Controller = "Account/ResetPasswordPre", userEmail = model.UserEmail, code = code });
            await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

            return(Ok(new
            {
                UserEmail = model.UserEmail,
                UserId = user.Id,
                Code = code
            }));
        }
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            {
                ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
                return(BadRequest(ModelState));
            }

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

            _correspondenceService.SendPasswordReset(user.Email, code);

            return(Ok());
        }
Example #23
0
        public ActionResult ForgotPassword(ForgotPasswordBindingModel formData)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var email = formData.Email;

            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("email", email));
            var response = RequestHelper.SendGetRequest(parameters, "Account"
                                                        , nameof(AccountController.ForgotPassword), null);

            if (response.IsSuccessStatusCode)
            {
                return(View("ForgotPasswordConfirmation"));
            }

            if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
            {
                return(View("Error"));
            }

            if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                var data    = RequestHelper.ReadResponse(response);
                var erroMsg = JsonConvert.DeserializeObject <MsgModelState>(data);
                erroMsg.ModelState.ToList().ForEach(p =>
                {
                    p.Value.ToList().ForEach(b =>
                    {
                        ModelState.AddModelError(string.Empty, $"{b}");
                    });
                });
            }

            return(View());
        }
Example #24
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());
        }
Example #25
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordBindingModel model)
        {
            var user = await _userRepository.FindAsync(x => x.Email == model.Email);

            if (user == null)
            {
                return(BadRequest(new BadRequestResponseModel(ErrorMessages.AuthenticatinError, "Sorry! We can't find an account with this email!")));
            }

            var resetLink   = $"{Url.Action(action: "Reset", "")}?token={Guid.NewGuid()}&email={user.Email}";
            var messageBody = new StringBuilder();

            messageBody.Append("<br>");
            messageBody.Append($"Please click this <a href=\"{resetLink}\">reset password</a> link reset your password.");
            messageBody.Append("<br><br>Thank you!");

            await _emailService.SendEmailAsync(user.Username, user.Email, "Retrieve your password.", messageBody.ToString());

            _logger.Info($"Password reset link is sent to {user.Username}");

            return(Ok());
        }
Example #26
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            {
                return(NotFound());
            }

            var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

            var callbackUrl = string.Format("{0}?token={1}", model.CallbackUrl, token.Base64ForUrlEncode());

            await UserManager.SendEmailAsync(user.Id, "Reset your password", "Please confirm your reset password by clicking <br/> <a href=\"" + callbackUrl + "\">here</a>");

            return(Ok());
        }
Example #27
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Please enter valid email address");
                return(BadRequest(ModelState));
            }

            ApplicationUser user = await UserManager.FindByNameAsync(model.Email);

            //for security purpose don't show the user id
            if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            {
                return(Ok());
            }

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

            var callbackUrl = string.Format("http://localhost:8267/#/confirm-email/{0}/{1}", user.Id, HttpUtility.UrlEncode(code).Replace("%2f", "%252F"));
            await UserManager.SendEmailAsync(user.Id, "Reset your password", callbackUrl);

            return(Ok());
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Username);

                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 https://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));
        }
Example #29
0
        public String ForgotPassword(ForgotPasswordBindingModel model)
        {
            String Subject = "Mini-CRM Password Reset Token";

            if (!ModelState.IsValid)
            {
                return("Invalid Request");
            }
            var user = _adminLog.GetByEmail(model.Email);

            if (user == null)
            {
                return("Sorry! No record is linked to that Email.");
            }
            String Passwordtoken = RandomPassword();

            //Creating a SMTP client to send/receive emails
            SmtpClient client = new SmtpClient("smtp.gmail.com");

            client.Host                  = "smtp.gmail.com";
            client.Port                  = 587;
            client.EnableSsl             = true;
            client.UseDefaultCredentials = false;
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "det@1234567@9");

            MailMessage message = new MailMessage();

            message.From = new MailAddress("*****@*****.**", "Jay Joshi");
            message.To.Add(new MailAddress(model.Email, "Jay Joshi"));
            message.Subject      = Subject;
            message.Body         = Passwordtoken;
            message.BodyEncoding = UTF8Encoding.UTF8;
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
            client.Send(message);
            return("Mail has been sent with a code to reset your password.");
        }
Example #30
0
        public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

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

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

                var encodedCode = HttpUtility.UrlEncode(code);

                var url = $"http://localhost:49648/account/resetpassword?code={encodedCode}";

                await UserManager.SendEmailAsync(user.Id, "Reset Password", $"Please <a href='{url}'>click here</a> to reset your password");

                return(Ok());
            }

            return(BadRequest(ModelState));
        }