public ActionResult ForgotPassword(ForgotPassword model) { if (ModelState.IsValid) { //get user by email address using (RavenSession.GetCachingContext()) { var user = RavenSession.Query<User>().SingleOrDefault(x => x.Email == model.Email && !x.IsDeleted); //if no matching user, error if (user == null) { ModelState.AddModelError("Invalid User Email", "A user could not be found with that email address"); return View(model); } // Create token and send email var token = new PasswordRetrieval(user, Guid.NewGuid()); RavenSession.Store(token); RavenSession.SaveChanges(); Metrics.Increment(Metric.Users_SendPasswordResetEmail); // TODO: Send email with password token return View("ForgotPasswordConfirmation"); } } return View(model); }
private void SubmitBtn2_Click(object sender, EventArgs e) { if (db.ConfirmDetails(Email_TxtBox1.Text, Uname_TxtBox2.Text)) { var forgotPwordForm = new ForgotPassword(Email_TxtBox1.Text); forgotPwordForm.Show(); Close(); } }
public ActionResult ForgotPassword(ForgotPassword tt) { try { if (Request.UrlReferrer == null || Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1] == "") { return(RedirectToAction("Login", "Login")); } string body = string.Empty; string Username = ""; string Password = ""; MembershipUser mu = Membership.GetUser(tt.UserName); //GetIPAddress(); if (mu != null) { if (mu.UserName != null || mu.UserName != string.Empty) { Password = mu.GetPassword("ok"); Username = tt.UserName; //using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailFormat/ForgotPassword.html"))) //{ // body = reader.ReadToEnd(); //} //string Email = dbUser.GetUserByUserName(tt.UserName).Email;//db.HRMS_UserMst_ST.Where(x => x.UserName == tt.Username).Select(x => x.Email).FirstOrDefault(); //body = body.Replace("{Username}", tt.UserName); //body = body.Replace("{Password}", Password); //utility.sendMail(Email, "Forgot Password", body); string strMessage = "Password has been successfully. Password is " + Password + ""; return(Json(new { success = true, response = strMessage })); } else { return(Json(new { success = false, response = "Username is invalid." })); } } else { return(Json(new { success = false, response = "Username is invalid." })); } } catch (Exception ex) { Log.LogWrite("Forgot Password Faild : " + ex.Message, "Forgot Password Failed", ex); return(Json(new { success = false, response = "Forgot password failed. Please contact your administrator." })); throw; } }
public IActionResult SendPasswordResetLink(ForgotPassword model) { try { if (String.IsNullOrEmpty(model.EmailAddress)) { TempData["ErrorMessage"] = "Please enter email address."; return(RedirectToAction("Index", "ForgotPassword")); } var user = _userService.GetUserByEmail(model.EmailAddress); if (user.Result.Data == null) { TempData["ErrorMessage"] = "Please enter valid email address."; return(RedirectToAction("Index", "ForgotPassword")); } if (user.Result.Data.EmailAddress == null) { TempData["ErrorMessage"] = "Please enter valid email address."; return(RedirectToAction("Index", "ForgotPassword")); } if (user.Result.Data.IsAdmin != 1) { TempData["ErrorMessage"] = "Unauthorized admin email address."; return(RedirectToAction("Index", "ForgotPassword")); } var token = _tokenService.TokenGenerateByEmail(model.EmailAddress); var resetLink = Url.Action("AdminResetPassword", "ForgotPassword", new { token = token }, protocol: HttpContext.Request.Scheme); //var isTokenUpdate = _userRepository.UpdateUserTokenAsync(user.Result.Result.user_id, token); if (token != "0") { var emailBody = CreateEmailBody(resetLink); _emailService.SendEmailAsync(model.EmailAddress, "Reset password.", emailBody, null); TempData["SuccessMessage"] = "Password reset link has been sent to your email address!"; } else { TempData["ErrorMessage"] = "Something went to wrong Please try again."; } } catch (Exception ex) { TempData["ErrorMessage"] = ex.Message.ToString(); } return(RedirectToAction("Index", "ForgotPassword", new { area = "Admin" })); //return View("Notification"); }
public void TestSetUp() { this.driver = new ChromeDriver(); this.login = new LoginMain(this.driver); this.register = new Register(this.driver); this.forgotpass = new ForgotPassword(this.driver); this.utilities = new UtilitiesMain(this.driver); utilities.ReportSetup(); }
/// <summary> /// It will auto generate new random password and send to user on his email. /// </summary> /// <param name="forgotPassword"></param> /// <returns></returns> public MDTTransactionInfo ForgotPassword(ForgotPassword forgotPassword) { MDTTransactionInfo mdt = new MDTTransactionInfo(); ErrorInfoFromSQL eInfo = null; try { List <SqlParameter> prm = new List <SqlParameter>(); SqlParameter email = new SqlParameter("@email", forgotPassword.Email); prm.Add(email); SqlParameter status = new SqlParameter("@Status", 0); status.Direction = ParameterDirection.Output; prm.Add(status); int StatusValue = 0; DataSet ds = DatabaseSettings.GetDataSet(APIHelper.forgotPassword, out StatusValue, prm); DataTable dt = ds.Tables[0]; if (StatusValue == 1) { dt = ds.Tables[0]; if (dt.Rows.Count > 0) { SendMailRequest sendMailRequest = new SendMailRequest(); sendMailRequest.recipient = dt.Rows[0]["Email"].ToString(); sendMailRequest.subject = "MDT Password Reset"; sendMailRequest.body = "Dear User," + Environment.NewLine + "Your password has been reset successfully. please login with new password given below " + Environment.NewLine + "New Password : "******"New Password"].ToString(); IMessager messager = new Email(); var Notification = new Notification(messager); if (Notification.DoNotify(sendMailRequest)) { mdt.status = HttpStatusCode.OK; mdt.msgCode = MessageCode.Success; mdt.message = "Password has been reset and sent to your registered email."; } else { mdt.status = HttpStatusCode.BadGateway; mdt.msgCode = MessageCode.Failed; mdt.message = "Password has been reset but unable to send an email due some technical issue, please contact to administrator"; } } } else if (StatusValue == 5 || StatusValue == 6) { mdt = DatabaseSettings.GetTransObject(null, StatusValue, "", ds); } } catch (Exception ex) { mdt.status = HttpStatusCode.ExpectationFailed; mdt.msgCode = MessageCode.TechnicalError; mdt.message = "Technical Error in the system, please contact to administrator"; } return(mdt); }
public async Task <IAccountResponse> ForgotPass(ForgotPassword view) { try { logger.Info($"{ GetType().Name} { ExtensionUtility.GetCurrentMethod() } input : {view.ToJsonString()} UserIPAddress: { _userIPAddress.GetUserIP().Result }"); var userInfo = await _appDbContext.UserInfos.Include(k => k.User).FirstOrDefaultAsync(x => x.Email == view.Email); ViewModels.ValidateOtp validateOtp = new ViewModels.ValidateOtp(); if (userInfo == null) { return(new AccountResponse(new ViewModels.UserRegistration { Success = false, CustomStatusCode = CustomStatusCode.NotRegisteredEmailID, Message = ClientMessageConstant.NotRegisteredEmailId })); } else { var profileInfo = await _appDbContext.Profiles.FirstOrDefaultAsync(x => x.Id == userInfo.Id); var userName = view.LanguageType == LanguageType.EN ? userInfo.User.NameEn : userInfo.User.NameAr; var emailResult = await _emailService.SendResetPasswordEmailAsync(userInfo.Email, userName, view.LanguageType); validateOtp.UserId = userInfo.UserId; validateOtp.Otp = userInfo.OTP; userInfo.OTP = emailResult.OTP; userInfo.Modified = DateTime.Now; _appDbContext.UserInfos.Update(userInfo); await _appDbContext.SaveChangesAsync(); return(new AccountResponse(new ViewModels.UserRegistration { Id = userInfo.UserId, FirstName = profileInfo.FirstNameEn, LastName = profileInfo.LastNameEn, Success = true, CustomStatusCode = CustomStatusCode.Success, Message = ClientMessageConstant.Success })); } } catch (System.Exception ex) { //Message = $"An error occurred when resetting password: {ex.Message}"; return(new AccountResponse(new ViewModels.UserRegistration { Success = false, CustomStatusCode = CustomStatusCode.FunctionalError, Message = ClientMessageConstant.WeAreUnableToProcessYourRequest }, ex)); } }
public HttpResponseMessage GetPasswordResetToken(ForgotPassword model) { var user = UserManager.FindByEmail(model.Email); var token = UserManager.GeneratePasswordResetTokenAsync(user.UserId).Result; ForgotPasswordToken passwordToken = new ForgotPasswordToken(); passwordToken.UserId = user.UserId; passwordToken.Token = token; return(Request.CreateResponse(HttpStatusCode.OK, passwordToken)); }
public IHttpActionResult ForgotPassword(string newPassword, string userId) { ForgotPassword forgotPassword = null; FactoryFacade factory = new FactoryFacade(); domainModel = factory.DomainModelFactory.CreateDomainModel(typeof(ForgotPassword)); domainModel.Fill(HashHelper.ForgotPassword(newPassword, userId)); domainService = factory.DomainServiceFactory.CreateDomainService(typeof(AccountsDomainService)); return(Ok(((ForgotPassword)domainService.Update(domainModel, CareHub.Factory.Enumerations.DomainModelEnum.FORGOT_PASSWORD)).ResponseMessage)); }
public ActionResult SendForgotPasswordNotification(string EmailTo) { var sharedFunctions = new SharedFunctions(); var forgotPasswordModel = new ForgotPassword(); forgotPasswordModel.Email = EmailTo; var result = sharedFunctions.SendEmail(EmailTo, Convert.ToString(EmailTemplates.ForgotPassword), "Synoptek : Reset your password", forgotPasswordModel); return(Json(result, JsonRequestBehavior.AllowGet)); }
private void ForgotPassword(object sender, RoutedEventArgs e) { ForgotPassword forgotWindow = new ForgotPassword(); //forgotWindow.Visibility = Visibility.Visible; ////forgotWindow.Show(); ////this.Close(); //this.Visibility = Visibility.Collapsed; forgotWindow.Show(); }
public ForgotPassword GetForgotPasswordByUserid(string userId) { ForgotPassword forgotPassword = db.ForgotPasswords.Find(userId); if (forgotPassword == null) { return(null); } return(forgotPassword); }
public ActionResult Index(ForgotPassword forgotPassword) { int userId = (new UserAccess()).getUserId(forgotPassword.Email); // if user doesn't exist if (userId == 0) { // pass error message and return the page ViewBag.ErrorMsg = "User Account not exists"; return(View()); } string userName = (new UserAccess()).retreiveUserByUserId(userId).UserName; try { // generate token forgotPassword.token = forgotPassword.GenerateRandomString(30); // save it to db bool isUpdate = (new forgotPasswordTokenAccess()).updateToken(userId, forgotPassword.token); // if error exist, when save the detail pass the error message if (!isUpdate) { ViewBag.ErrorMsg = "Updating Failed"; return(View()); } // send it to the user's email account Email email = new Email(forgotPassword.Email); int isSuccess = email.SendMail("Hi " + userName + " ! <br><br>We recieved a request to reset your password.<br><br> Click here to Reset Your password : <a href='" + string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~")) + "ForgotPassword/ConfirmAccount?userId=" + userId + "&token=" + forgotPassword.token + "'>Link</a><br> If you don't want to change your password, you can ignore this email.<br><br> Thanks,<br> The Futunet Net Team", "Account - Help (Reset Your Password)"); // if sending failed -- return the page with error if (isSuccess == 0) { ViewBag.errorMsg = "Sending Mail Failed"; return(View()); } } catch (Exception ex) { throw ex; } // return the page with success ViewBag.Message = "Instructions on how to reset Your Password have been sent to your inbox"; return(View()); }
public string CheckSecurityQuestionAnswer(string answer, int questionId, string userId) { FactoryFacade factory = new FactoryFacade(); ForgotPassword forgotPassword = null; domainModel = factory.DomainModelFactory.CreateDomainModel(typeof(ForgotPassword)); domainModel.Fill(HashHelper.CheckSecurityQuestion(questionId, answer.ToLower(), userId)); domainService = factory.DomainServiceFactory.CreateDomainService(typeof(AccountsDomainService)); forgotPassword = (ForgotPassword)domainService.Query(domainModel, DomainModelEnum.CHECK_SECURITY_QUESTION_ANSWER); return(forgotPassword.ResponseMessage); }
public async Task ForgetPasswordReturnsErrorIfNoEmail() { var forgotPassword = new ForgotPassword { Email = string.Empty }; var controller = CreateController(); var res = await controller.ForgotPassword(forgotPassword); res.Should().BeIsBlankResultForPath("email"); }
public async Task <IActionResult> ForgotPassAsync([FromBody] ForgotPassword view) { if (!ModelState.IsValid) { return(BadRequest(ModelState.GetErrorMessages())); } var result = await _service.ForgotPass(view); return(Ok(result.User)); }
public void ForgotPasswordView_Template_Test() { var template = new ForgotPassword(new SmartAppInfo { Id = ApplicationId }); var output = template.TransformText(); Assert.NotNull(output); Assert.NotEmpty(output); Assert.Contains($"@model {ApplicationId}.Backend.Models.ForgotPasswordViewModel", output); }
public JunkCar.DataModel.Models.Sec_Password_Question GetSecurityQuestion(string userId) { FactoryFacade factory = new FactoryFacade(); ForgotPassword forgotPassword = null; domainModel = factory.DomainModelFactory.CreateDomainModel(typeof(ForgotPassword)); domainModel.Fill(HashHelper.GetSecurityQuestion(userId)); domainService = factory.DomainServiceFactory.CreateDomainService(typeof(AccountsDomainService)); forgotPassword = (ForgotPassword)domainService.Query(domainModel, DomainModelEnum.GET_SECURITY_QUESTION); return(forgotPassword.SecurityQuestion); }
public void Task_Forgot_Password_Return_Ok() { var controller = new AccountsController(userBL, configuration); var data = new ForgotPassword() { Email = "*****@*****.**" }; var expected = controller.ForgotPassword(data); Assert.IsType <OkObjectResult>(expected); }
public UserDto ResetPassword(ForgotPassword request) { try { return(_userLogic.ResetPassword(request.Email, request.Password).Map()); } catch (Exception e) { return(null); } }
public UserDto Forgot(ForgotPassword request) { try { return(_userLogic.ForgotPwd(request.Email).Map()); } catch (Exception e) { return(null); } }
public ActionResult Forgot_Password([Bind(Include = "EMAIL")] ForgotPassword MailForgot, ProjectHeart.Models.MailModel _objModelMail) { if (ModelState.IsValid) { var resultado = db.Accounts.AsNoTracking().Where(p => p.EMAIL == MailForgot.EMAIL).Select(p => new { SENHA = p.SENHA, EMAIL = p.EMAIL }); //popular o corpo do e-mail _objModelMail.To = MailForgot.EMAIL; _objModelMail.From = "*****@*****.**"; _objModelMail.Subject = "Reset senha - Medilab Plus"; //LOGIC para enviar senho no corpo o email, se email exist no DB foreach (var item in resultado) { if (item.EMAIL == MailForgot.EMAIL) { var AmOuPm = DateTime.Now.TimeOfDay; if (AmOuPm.Hours <= 12) { _objModelMail.Body = "Boa " + "dia,"; } else { _objModelMail.Body = "Boa " + "tarde,"; } } _objModelMail.Body += "<br /><br /> Usuário: " + item.EMAIL; _objModelMail.Body += "<br /><br /> Senha: " + item.SENHA; } //Instância classe email MailMessage mail = new MailMessage(); mail.To.Add(_objModelMail.To); mail.From = new MailAddress(_objModelMail.From); mail.Subject = _objModelMail.Subject; string Body = _objModelMail.Body; mail.Body = Body; mail.IsBodyHtml = true; //Instância smtp do servidor, neste caso o gmail. SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.UseDefaultCredentials = true; smtp.Credentials = new System.Net.NetworkCredential ("*****@*****.**", "mar142536");// Login e senha do e-mail. smtp.EnableSsl = true; smtp.Send(mail); return(View("Index")); } else { return(View()); } }
public string CheckVerificationCode(int verificationCode) { FactoryFacade factory = new FactoryFacade(); ForgotPassword forgotPassword = null; domainModel = factory.DomainModelFactory.CreateDomainModel(typeof(ForgotPassword)); domainModel.Fill(HashHelper.CheckVerificationCode(verificationCode)); domainService = factory.DomainServiceFactory.CreateDomainService(typeof(AccountsDomainService)); forgotPassword = (ForgotPassword)domainService.Query(domainModel, DomainModelEnum.CHECK_VERIFICATION_CODE); return(forgotPassword.ResponseMessage); }
public async Task ForgotPassword_ShouldReturnBadRequest_WhenEmailIsNotValid() { var forgotPassword = new ForgotPassword { Email = "nonExisting" }; var response = await _client.PostAsJsonAsync("api/account/forgotpassword", forgotPassword); response.StatusCode.ShouldBe(HttpStatusCode.BadRequest); }
public string ResetPassword(string newPassword, string userId) { FactoryFacade factory = new FactoryFacade(); ForgotPassword forgotPassword = null; domainModel = factory.DomainModelFactory.CreateDomainModel(typeof(ForgotPassword)); domainModel.Fill(HashHelper.ResetPassword(userId, newPassword)); domainService = factory.DomainServiceFactory.CreateDomainService(typeof(AccountsDomainService)); forgotPassword = (ForgotPassword)domainService.Query(domainModel, DomainModelEnum.RESET_PASSWORD); return(forgotPassword.ResponseMessage); }
public async Task <IActionResult> GetQuestion([FromBody] ForgotPassword model) { var question = await _service.GetQuestion(model.Email); if (question == null) { return(Ok(new { message = "No user found with related email." })); } return(Ok(new { question = question })); }
public void Task_Forgot_Password_Return_BadRequest_If_Email_Is_Incorrect() { var controller = new AccountsController(userBL, configuration); var data = new ForgotPassword() { Email = "vinitathopte1@gmailcom" }; var expected = controller.ForgotPassword(data); Assert.IsType <BadRequestObjectResult>(expected); }
public async Task forgotpassword_command_fails_when_user_does_not_exist() { var email = "*****@*****.**"; var command = new ForgotPassword(email); // Check if exception is thrown _commandHandler .Awaiting(c => c.HandleAsync(command)) .Should().Throw <InvalidEmailException>(); }
public void GivenValidPostRequest_SendsEmail() { var model = new ForgotPassword { Email = User.Email }; Controller.ForgotPassword(model); MailController.Verify(x => x.ForgotPassword(It.Is <ViewModels.Mail.ForgotPassword>(m => m.To == User.Email)), Times.Once()); }
public Task <MdiResponse> ForgotPassword(ForgotPassword payload) { try { return(_userService.ForgotPassword(payload)); } catch (Exception e) { return(null); } }
public ForgotViewModel(INavigation navigation) { Navigation = navigation; UserForgotPassword = new ForgotPassword(); SendCodeToEmailcommand = new Command(() => SendEmail()); ValidateCodeCommand = new Command(async() => await GoChangePasswordPage() ); }
public async Task<HttpResponseMessage> Forgot(ForgotPassword model) { if(!ModelState.IsValid) { return Request.CreateErrorResponse( HttpStatusCode.BadRequest, ModelState); } var userName = model.Email.ToLowerInvariant(); var token = forgotPassword(userName); if(!string.IsNullOrWhiteSpace(token)) { await mailer.ForgotPasswordAsync(userName,token); } return Request.CreateResponse(HttpStatusCode.NoContent); }
public async Task<HttpResponseMessage> Forgot(ForgotPassword model) { if (!ModelState.IsValid) { return Request.CreateErrorResponse( HttpStatusCode.BadRequest, ModelState); } var email = model.Email.ToLower(CultureInfo.CurrentCulture); var token = await membershipService.ForgotPassword(email); if (!string.IsNullOrWhiteSpace(token)) { await mailer.ForgotPasswordAsync(email, token); } return Request.CreateResponse(HttpStatusCode.NoContent); }
partial void UpdateForgotPassword(ForgotPassword instance);
public ActionResult RecoverPassword(ForgotPassword model) { if (ModelState.IsValid) { log.Info("Received recover password request from {0}", model.UsernameOrEmail); bool success = forgotPassword.ResetPassword(model.UsernameOrEmail); if (!success) { ModelState.AddModelError("System", string.Format("Could not send reset password email for {0}", model.UsernameOrEmail)); return View(model); } } return View("RecoverPasswordSuccess"); }
partial void InsertForgotPassword(ForgotPassword instance);
partial void DeleteForgotPassword(ForgotPassword instance);
protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { if (!captcha.Decide()) { captcha.message = "پاسخ اشتباه است!"; } else { if (txtEmail.Text.Trim() != "") { Literal1.Text = ""; string email = txtEmail.Text.Trim(); var query = context.Users.Where(u => u.Email == email).FirstOrDefault(); if (query != null) { int UserId = query.UserId; var query1 = context.ForgotPasswords.Where(s => s.UserId == UserId).FirstOrDefault(); if (query1 == null) { VCode = Convert.ToString(Guid.NewGuid()); ForgotPassword fp = new ForgotPassword(); fp.UserId = UserId; fp.Email = email; fp.VerificationCode = VCode; fp.SubmitDate = DateTime.Now; context.ForgotPasswords.InsertOnSubmit(fp); context.SubmitChanges(); } else if (query1 != null) { VCode = query1.VerificationCode; } string urlBase = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath; string RegUrl = "ChangePassword.aspx?VCode=" + VCode; string fullUrl = urlBase + RegUrl; string AppPath = Request.PhysicalApplicationPath; StreamReader sr = new StreamReader(AppPath + "EmailTemplates/ForgotPassword.txt"); MailMessage mail = new MailMessage(); mail.Subject = "Forgot Password "; mail.IsBodyHtml = true; mail.Body = sr.ReadToEnd(); sr.Close(); mail.Body = mail.Body.Replace("<%UserName %>", query.FirstName); mail.Body = mail.Body.Replace("<%ChangePasswordURL%>", fullUrl); mail.To.Add(new MailAddress(email)); MailAddress m = new MailAddress("*****@*****.**"); mail.From = m; SmtpClient sc = new SmtpClient(); sc.Host = "WebMail.salestan.ir"; sc.Port = 25; sc.EnableSsl = false; NetworkCredential c = new NetworkCredential("*****@*****.**", "$users12345"); sc.Credentials = c; sc.Send(mail); lblSucces.Visible = true; ImageOk.Visible = true; } else { LabelError.Visible = true; } } else { Literal1.Text = "<p class='FormValidation'>پست الکترونیکی خود را وارد نمایید!</p>"; } } }
public async Task<ActionResult> ForgotPassword(ForgotPassword formModel) { var user = await _commerceCoreApi.StorefrontSecurityGetUserByNameAsync(formModel.Email); if (user != null) { string callbackUrl = Url.Action("ResetPassword", "Account", new { UserId = user.Id, Code = "token" }, protocol: Request.Url.Scheme); await _commerceCoreApi.StorefrontSecurityGenerateResetPasswordTokenAsync(user.Id, WorkContext.CurrentStore.Id, WorkContext.CurrentLanguage.CultureName, callbackUrl); } else { ModelState.AddModelError("form", "User not found"); } return StoreFrontRedirect("~/account/login#recover"); }
private static ForgotPassword GetFPInfo(object forgotPwd) { var objPwd = new ForgotPassword(); var tmp = (Dictionary<string, object>)forgotPwd; object objEmail = null; if (tmp.TryGetValue("RegisteredEmail", out objEmail)) objPwd.RegisteredEmail = objEmail.ToString(); return objPwd; }