public ActionResult ResetPasswordMail(string email) { CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (response.Success) { var member = db.Members.Where(x => x.Email == email).FirstOrDefault(); if (member != null) { char[] cr = "abcdefghijklmnopqrstuvwxyz0123456789".ToCharArray(); string result = string.Empty; Random r = new Random(); for (int i = 0; i < 8; i++) { result += cr[r.Next(0, cr.Length - 1)].ToString(); } HttpCookie cerez = new HttpCookie("reset_password_admin"); cerez.Values.Add("code", Server.UrlEncode(result)); cerez.Values.Add("reset_member_id", Server.UrlEncode(member.ID.ToString())); cerez.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(cerez); Session["password_id"] = result; Mail mail = new Mail(); mail.ForgotMyPassword(email, result); } return(RedirectToAction("NewPassword", "Admin", new { member_id = member.ID })); } else { ViewBag.error = "Robot testini geçmeniz gerekiyor."; } return(View()); }
private static string CAPTCHA_SECRET_KEY = @"6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe"; // WARNING: FAKE SECRET KEY // Thanks to http://www.thatsoftwaredude.com/content/6235/implementing-googles-no-captcha-recaptcha-in-aspnet public static bool checkCaptcha(System.Web.UI.Page page) { try { string url = @"https://www.google.com/recaptcha/api/siteverify"; WebRequest request = WebRequest.Create(url); string postData = string.Format("secret={0}&response={1}&remoteip={2}", CAPTCHA_SECRET_KEY, page.Request["g-recaptcha-response"], page.Request.UserHostAddress); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postData.Length; StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(postData); writer.Close(); StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()); string responseData = reader.ReadToEnd(); JavaScriptSerializer jss = new JavaScriptSerializer(); CaptchaResponse cResponse = jss.Deserialize <CaptchaResponse>(responseData); return(cResponse.success); } catch (WebException) { return(true); // TODO: Change to false when releasing } }
public async Task <ActionResult> Register(RegisterViewModel model) { CaptchaResponse response = CaptchaHelper.ValidateCaptcha(Request["g-recaptcha-response"]); if (!response.Success) { return(RedirectToAction("CaptchaInvalid", "Home")); } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { UserManager.AddToRole(user.Id, "Owner"); //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); this.RegisterOwner(user.Id, model.FirstName, model.LastName, model.Email); //await SendConfirmationEmailAsync(user.Id); await SendConfirmationEmailAsync(user.Id, model.FirstName, model.LastName, model.Email, model.Password); return(RedirectToAction("AccountRegistered")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public void ComposePrivateMessage(string subject, string body, string to, string captchaId = "", string captchaAnswer = "") { if (User == null) { throw new Exception("User can not be null."); } var request = WebAgent.CreatePost(ComposeMessageUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", subject, text = body, to, uh = User.Modhash, iden = captchaId, captcha = captchaAnswer }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(result); ICaptchaSolver solver = CaptchaSolver; // Prevent race condition if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null) { captchaId = json["json"]["captcha"].ToString(); CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(captchaId)); if (!captchaResponse.Cancel) // Keep trying until we are told to cancel { ComposePrivateMessage(subject, body, to, captchaId, captchaResponse.Answer); } } }
public bool validateCaptcha() { bool result; string captchaResponse = Request.Form["g-recaptcha-response"]; HttpWebRequest req = (HttpWebRequest)WebRequest.Create ("https://www.google.com/recaptcha/api/siteverify?secret=SECRETKEY &response=" + captchaResponse); try { using (WebResponse wResponse = req.GetResponse()) { using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream())) { string jsonResponse = readStream.ReadToEnd(); lb_gscore.Text = jsonResponse.ToString(); JavaScriptSerializer js = new JavaScriptSerializer(); CaptchaResponse jsonObject = js.Deserialize <CaptchaResponse>(jsonResponse); result = Convert.ToBoolean(jsonObject.Success); } } return(result); } catch { lb_finalmsg.Text = "Error in google captcha"; return(false); } }
public async Task <IActionResult> ValidateCaptchaToken(string captchaToken) { if (ModelState.IsValid) { string request = "siteverify"; request += "?secret=" + _appSettings.Authentication.reCAPTCHA.SecretKey; request += "&response=" + captchaToken.Trim().Clean(); request += "&remoteip=" + _httpContextAccessor.HttpContext.GetRemoteAddress().MapToIPv4().ToString(); JsonClient client = new JsonClient(" https://www.google.com/recaptcha/api/"); HttpStatusCode statusCode = await client.SendRequest(HttpMethod.Post, request, string.Empty); if (client.IsResponseSuccess) { CaptchaResponse response = client.GetResponseObject <CaptchaResponse>(); if (response.success) { if (response.action.Equals("submit", StringComparison.OrdinalIgnoreCase)) { if (response.score > 0.6) { return(Ok(client.GetResponseString())); } } } } return(BadRequest(client.GetResponseString())); } return(BadRequest("Invalid request")); }
public async Task <bool> IsValid(string captchaResponse) { try { var values = new Dictionary <string, string> { { "secret", secretKey }, { "response", captchaResponse } }; var resp = await http.PostAsync(url, new FormUrlEncodedContent(values)); var str = await resp.Content.ReadAsStringAsync(); CaptchaResponse response = JsonConvert.DeserializeObject <CaptchaResponse>(str); return(response.success); } catch (Exception) { return(false); } }
private async Task <Post> SubmitAsync(SubmitData data, ICaptchaSolver solver = null) { var json = await WebAgent.Post(SubmitLinkUrl, data).ConfigureAwait(false); if (json["errors"].Any() && json["errors"][0][0].ToString() == "BAD_CAPTCHA") { if (solver == null) { throw new CaptchaFailedException("Captcha required but not ICaptchaSolver provided"); } data.Iden = json["captcha"].ToString(); CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(data.Iden)); // We throw exception due to this method being expected to return a valid Post object, but we cannot // if we got a Captcha error. if (captchaResponse.Cancel) { throw new CaptchaFailedException("Captcha verification failed when submitting " + data.Kind + " post"); } data.Captcha = captchaResponse.Answer; return(await SubmitAsync(data, solver).ConfigureAwait(false)); } else if (json["errors"].Any() && json["errors"][0][0].ToString() == "ALREADY_SUB") { throw new DuplicateLinkException($"Post failed when submitting. The following link has already been submitted: {((LinkData)data).URL}"); } else if (json["errors"].Any()) { throw new Exception(json["errors"][0][0].ToString()); } return(new Post(WebAgent, json["data"])); }
public ActionResult Login(string Email, string Password) { CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (response.Success && ModelState.IsValid) { var user = db.Users.Where(x => x.Email == Email && x.Password == Password).FirstOrDefault(); if (user != null) { HttpCookie cerez = new HttpCookie("cerezim"); cerez.Values.Add("eposta", Server.UrlEncode(user.Email)); cerez.Values.Add("ad", Server.UrlEncode(user.Name)); cerez.Values.Add("soyad", Server.UrlEncode(user.Surname)); cerez.Values.Add("ID", user.ID.ToString()); cerez.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(cerez); } else { ModelState.AddModelError("LoginUserError", "Bilgilerinizi kontrol edin."); return(RedirectToAction("Login", "Account")); } Session["ad"] = user.Name; Session["soyad"] = user.Surname; Session["ID"] = user.ID.ToString(); return(RedirectToAction("Index", "Home")); } else { TempData["Status"] = "Lütfen robot olmadığınızı belirtmek için testi geçiniz."; return(RedirectToAction("Login", "Account")); } }
public async Task Register_ShouldReturnInfoMessageViewWithFilledViewBag_IfCreateAsyncIdentityResultReturnSuccess() { //Arrange var userManager = new UserManagerFake(isUserConfirmed: true, identityResult: IdentityResult.Success); var signInManager = new SignInManagerFake(_httpContextAccessor.Object, signInResult: Microsoft.AspNetCore.Identity.SignInResult.Failed); var captchaResponse = new CaptchaResponse { Success = "true" }; _mediatorMock.Setup(m => m.Send(It.IsAny <ValidateCaptchaQuery>(), It.IsAny <CancellationToken>())).ReturnsAsync(captchaResponse); var sut = new AccountController(userManager, signInManager, _emailSender.Object, _loggerFactoryWrapper.Object, _razorViewToString.Object, _mediatorMock.Object); sut.ControllerContext.HttpContext = new DefaultHttpContext(); sut.Url = _urlHelper.Object; //Act var result = (ViewResult)await sut.Register(A.New <RegisterViewModel>()); //Assert result.Should().NotBeNull(); result.Should().BeOfType <ViewResult>(); result.Should().NotBeNull(); result.ViewData.Should().NotBeEmpty(); result.ViewData.ContainsKey("InfoMessage").Should().BeTrue(); result.ViewData["InfoMessage"].Should().Be("RegistrationConfirmEmail"); }
public async Task <ActionResult> Register(RegisterViewModel model) { CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // 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 if (response.Success == true) //captcha worked, move on ahead { sendemail(user); return(RedirectToAction("Confirm", "Account", new { Email = user.Email })); } else { return(Content("Error From Google ReCaptcha : " + response.ErrorMessage[0].ToString())); } //captcha failed redirect. } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Create(ContactViewModel contactViewModel, bool isJavascriptEnabled) { CaptchaResponse captchaResult = await _mediator.Send(new ValidateCaptchaQuery()); if (captchaResult.Success != "true") { return(Json(new { status = "FailedTheCaptchaValidation" })); } if (!ModelState.IsValid) { return(View(contactViewModel)); } var contactWioutJavascript = _mapper.Map <ContactViewModel, Contact>(contactViewModel); await _mediator.Send(new AddNewContactCommand { Contact = contactWioutJavascript }); if (isJavascriptEnabled) { return(Json(new { Status = "Success" })); } return(View("Success")); }
/// <summary> /// Returns true if the captcha is successfully validated by google /// </summary> /// <param name="captchaCode"></param> /// <param name="userIpAddress"></param> /// <returns></returns> public static bool IsGoogleReCaptchaValid(string captchaCode, string userIpAddress) { try { WebClient client = new WebClient(); NameValueCollection collection = new NameValueCollection() { { "secret", "6LdpLA0TAAAAALj2bvRJr4OEnpTq8ATFwLxm5_YU" }, { "response", captchaCode }, { "remoteip", userIpAddress } }; byte[] resp = client.UploadValues("https://www.google.com/recaptcha/api/siteverify", collection); string output = System.Text.Encoding.UTF8.GetString(resp); //JObject o = JObject.Parse(output); JavaScriptSerializer jsonSerialiser = new JavaScriptSerializer(); CaptchaResponse response = jsonSerialiser.Deserialize <CaptchaResponse>(output); return(response.success == "True" ? true : false); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); return(false); } }
public ActionResult ForgetPassword(ForgetPasswordModel forgetPasswordModel) { CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (response.Success && ModelState.IsValid) { var result = userBusiness.ForgetPassword(forgetPasswordModel); if (!string.IsNullOrEmpty(result)) { //Gửi mail xác nhận thay đổi mật khẩu CommonFunctions.SendGmail(new MailModel { SenderAccount = "*****@*****.**", SenderPassword = "******", SenderName = "Pizza", Subject = "Đổi mật khẩu", Body = string.Format("<a href='http://*****:*****@Area = "Admin" })); } } return(View("ForgetPassword", forgetPasswordModel)); }
public async Task <CaptchaResponse> ValidateCaptchaResponseAsync(string captchaResponse, string clientIpAddress, User user = null) { var response = new CaptchaResponse { Success = false }; if (string.IsNullOrWhiteSpace(captchaResponse)) { return(response); } if (user != null && ValidateCaptchaBypassToken(captchaResponse, user)) { response.Success = true; return(response); } var httpClient = _httpClientFactory.CreateClient("HCaptchaValidationService"); var requestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("https://hcaptcha.com/siteverify"), Content = new FormUrlEncodedContent(new Dictionary <string, string> { { "response", captchaResponse.TrimStart("hcaptcha|".ToCharArray()) }, { "secret", _globalSettings.Captcha.HCaptchaSecretKey }, { "sitekey", SiteKey }, { "remoteip", clientIpAddress } }) }; HttpResponseMessage responseMessage; try { responseMessage = await httpClient.SendAsync(requestMessage); } catch (Exception e) { _logger.LogError(11389, e, "Unable to verify with HCaptcha."); return(response); } if (!responseMessage.IsSuccessStatusCode) { return(response); } using var hcaptchaResponse = await responseMessage.Content.ReadFromJsonAsync <HCaptchaResponse>(); response.Success = hcaptchaResponse.Success; var score = hcaptchaResponse.Score.GetValueOrDefault(); response.MaybeBot = score >= _globalSettings.Captcha.MaybeBotScoreThreshold; response.IsBot = score >= _globalSettings.Captcha.IsBotScoreThreshold; response.Score = score; return(response); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (response.Success && ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } } else { return(Content("Error from Google ReCaptcha: " + response.ErrorMessage[0].ToString())); } }
public async Task <ApiResponse> Post([FromBody] ContactFormData value) { CaptchaResponse response = await _captchaService.Validate(value.CaptchaToken); if (!response.Success) { return(new ApiResponse() { StatusCode = StatusCodes.Status401Unauthorized, ErrorMessage = "Application Error. Please try again later." }); } if (!ModelState.IsValid) { return(new ApiResponse() { StatusCode = StatusCodes.Status400BadRequest, ErrorMessage = "Form errors. Please input correct data" }); } //Save to mongoDb this._contactRepository.AddContact(new Contact() { FullName = value.FullName, Email = value.EmailAddress, Content = value.Message, Answered = false, Submitted = DateTime.Now }); return(new ApiResponse() { StatusCode = StatusCodes.Status200OK }); }
public async Task Register_ShouldCallSendEmailAsync_ExactlyOnce() { //Arrange var userManager = new UserManagerFake(isUserConfirmed: true, identityResult: IdentityResult.Success); var signInManager = new SignInManagerFake(_httpContextAccessor.Object, signInResult: Microsoft.AspNetCore.Identity.SignInResult.Failed); var captchaResponse = new CaptchaResponse { Success = "true" }; _mediatorMock.Setup(m => m.Send(It.IsAny <ValidateCaptchaQuery>(), It.IsAny <CancellationToken>())).ReturnsAsync(captchaResponse); var sut = new AccountController(userManager, signInManager, _emailSender.Object, _loggerFactoryWrapper.Object, _razorViewToString.Object, _mediatorMock.Object); sut.ControllerContext.HttpContext = new DefaultHttpContext(); sut.Url = _urlHelper.Object; //Act var result = (ViewResult)await sut.Register(A.New <RegisterViewModel>()); //Assert result.Should().NotBeNull(); result.Should().BeOfType <ViewResult>(); _emailSender.Verify(e => e.SendEmailAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.Once); }
public ActionResult Register(User user) { CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (response.Success && ModelState.IsValid) { try { user.IsActive = true; user.LastActivityDate = DateTime.Now; db.Users.Add(user); db.SaveChanges(); Mail mail = new Mail(); mail.NewUserMail(user.Email, user.Name, user.Surname); } catch (Exception e) { Console.WriteLine(e); throw; } } else { TempData["Status"] = "Lütfen robot olmadığınızı belirtmek için testi geçiniz."; return(RedirectToAction("Register", "Account")); } return(View()); }
/// <summary> /// Returns captcha for new user registration. /// </summary> /// <returns>Captcha object which contains captcha cookie and image.</returns> public async Task <CaptchaResponse> GetRegistrationCaptcha() { var client = this.httpClientFactory.CreateClient(); var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/simple_captcha.php")); return(await CaptchaResponse.Build(response)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (response.Success && result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // 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.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public CaptchaSolver(string GoogleCaptchaBasePath, string AudioFileUrl) { Result = new CaptchaResponse(); FileName = $"GoogleCaptcha_{DateTime.Now.Ticks}"; SrcInputFilePath = Path.Combine(GoogleCaptchaBasePath, "Input", $"{FileName}.mp3"); SrcOutputFilePath = Path.Combine(GoogleCaptchaBasePath, "Output", $"Converted_{FileName}.wav"); this.AudioFileUrl = AudioFileUrl; }
public ActionResult SubmitReportForm(RedYellowCardReportFormModel model) { //verify Google reCAPTCHA if (string.IsNullOrEmpty(Request["g-recaptcha-response"])) { ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA"); return(CurrentUmbracoPage()); } else { CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (!response.Success) { ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect!"); return(CurrentUmbracoPage()); } } if (!ModelState.IsValid) { return(CurrentUmbracoPage()); } // Look for multiple receivers on Umbraco page List <string> managerEmailList = new List <string>(); string managerEmail1 = CurrentPage.Parent.GetPropertyValue <string>("notifyEmail"); managerEmailList.Add(managerEmail1); string managerEmail2 = CurrentPage.Parent.GetPropertyValue <string>("notifyEmail2"); managerEmailList.Add(managerEmail2); string managerEmail3 = CurrentPage.Parent.GetPropertyValue <string>("notifyEmail3"); managerEmailList.Add(managerEmail3); string managerEmail = ""; for (int i = 0; i < managerEmailList.Count(); i++) { if ((managerEmailList[i].Trim() != "") && (i != managerEmailList.Count() - 1)) { managerEmail += managerEmailList[i] + ","; } if ((managerEmailList[i].Trim() != "") && (i == managerEmailList.Count() - 1)) { managerEmail += managerEmailList[i]; } } SendNotificationToManager(model, managerEmail); SendAutoResponder(model); return(CurrentUmbracoPage()); }
public ActionResult Registration(FormCollection f) { if (usemol.checkemail(f["txtemail"]) == true) { CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]); if (response.Success && ModelState.IsValid) { User use = new User(); use.Email = f["txtemail"]; use.HoTenDem = f["txthotendem"]; use.Ten = f["txtten"].ToString(); use.NgaySinh = Convert.ToDateTime(String.Format("{0:yyyy-MM-dd}", f["txtngaysinh"])); use.LoaiTaiKhoan = 0; use.XacThucEmail = false; use.GioiTinh = Convert.ToBoolean(Convert.ToInt32(f["txtgioitinh"])); use.DiaChi = f["txtdiachi"]; use.SDT = f["txtdienthoai"]; if (string.Compare(f["txtmatkhau"], f["txtnhaplaimatkhau"]) == 0) { MaHoa mh = new MaHoa(); use.PassWord = mh.md5(f["txtmatkhau"]); } else { ModelState.AddModelError("", "Mật khẩu không trùng khớp , vui lòng kiểm tra lại !"); return(View()); } use.ThoiGianDangKy = Convert.ToDateTime(String.Format("{0:yyyy-MM-dd}", DateTime.Now.ToString())); try { usemol.Create(use); ModelState.AddModelError("", "Đăng Ký thành công ! truy cập email của bạn để kích hoạt tài khoản "); return(View()); } catch { ModelState.AddModelError("", "Có lỗi xảy ra , vui lòng thử lại sau !"); return(View()); } } else { ModelState.AddModelError("", "Bạn phải xác thực Captcha"); return(View()); } } else { ModelState.AddModelError("", "Email đã tồn tại"); return(View()); } }
public async Task <IActionResult> Register(RegisterViewModel model) { CaptchaResponse captchaResult = await _mediator.Send(new ValidateCaptchaQuery()); if (captchaResult.Success != "true") { ViewData["FailedTheCaptchaValidation"] = "true"; return(View(model)); } if (!ModelState.IsValid) { return(View(model)); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, UserFullName = model.UserFullName, UserGender = model.UserGender, UserHowFindUs = model.UserHowFindUs }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); var htmlString = _razorViewToString.Render("EmailTemplates/IdentityTemplate", new IdentityTemplateViewModel { CallBackLink = callbackUrl, CallBackLinkText = "فعال سازی", EmailMessageHeader = "فعال سازی اکانت", EmailPreviewMessage = "", EmailMessageBody = "پیوستن شما به جمع کاربران وب برای ایران را تبریک میگوییم، برای فعال سازی نام کاربری خود فقط کافیست بر روی دکمه زیر کلیک کنید." }); await _emailSender.SendEmailAsync(model.Email, "فعال سازی نام کاربری - وب برای ایران", htmlString); _logger.LogInformation(3, "User created a new account with password."); ViewBag.InfoMessage = "RegistrationConfirmEmail"; return(View("InfoMessage")); } AddErrors(result); return(View(model)); }
public IActionResult SendSMS(SMSPublicModel model) { model.FormBehavior = new FormBehavior(); CaptchaResponse response = ValidateCaptcha(HttpContext.Request.Form["g-recaptcha-response"]); if (!response.Success) { ModelState.AddModelError(string.Empty, "Please click captcha for security purposes."); } else if (ModelState.IsValid) { try { var sms = new SMSModel { MobileNumber = model.MobileNumber, MessageBody = $"From: {model.SenderName}\n{model.MessageBody}\n\nDon't reply to this number." }; var record = _mapper.Map <SMSModel, ShortMessageService>(sms); record.SMSStatus = Enums.SMSStatus.Queue; _smsService.NewSMS(record, true); model.FormBehavior.Notification = new Notification { IsError = false, Message = "Message successfully queued.", Title = "SMS" }; model.MobileNumber = string.Empty; model.MessageBody = string.Empty; model.SenderName = string.Empty; ModelState.Clear(); } catch (Exception ex) { if (ex.Message.Contains("mobile number")) { ModelState.AddModelError(string.Empty, "Invalid format of mobile number."); } else if (ex.Message.Contains("unicode")) { ModelState.AddModelError(string.Empty, "Message body should not contain unicode characters (ex. emojis)"); } else { model.FormBehavior.Notification = new Notification { IsError = true, Message = ex.Message, Title = "SMS" }; } } } return(PartialView("_SendSMS", model)); }
private async Task <CaptchaResponse> GetReCaptchaResult(string response, string ip) { CaptchaResponse result = null; string secret = ConfigurationManager.AppSettings["RecaptchaSecretKey"].ToString(); string baseAddress = ConfigurationManager.AppSettings["BaseAddress"].ToString(); string uri = ConfigurationManager.AppSettings["RequestUri"].ToString(); string absUri = baseAddress + uri + "?secret=" + secret + "&response=" + response; result = await new WebTools().ServiceCall <CaptchaResponse>(absUri); return(result); }
public ActionResult Register(User u) { try { if (u.Username == null || u.Password == null || u.Email == null || u.Country == null) { throw new CustomException("Please fill all fields"); } else { UsersBL uBl = new UsersBL(); if (uBl.UserAlreadyExists(u.Username)) { throw new CustomException("Username Already Exists"); } else if (uBl.EmailAlreadyExists(u.Email)) { throw new CustomException("Email Already Exists"); } else { CaptchaResponse response = ValidateCaptcha(Request.Form["g-recaptcha-response"]); if (response.Success && ModelState.IsValid) //ModelState.isValid: if an input passed is not like the model it will return false //response.Success (captcha resposne) { uBl.Register(u); TempData["message"] = "Account Successfully Registered."; Logger.Log("Guest", Request.Path, "Registered as " + u.Username); return(RedirectToAction("Login", "Accounts")); } else { throw new CustomException("CAPTCHA Error: " + response.ErrorMessage[0].ToString()); } } } } catch (CustomException ex) { TempData["errormessage"] = ex.Message; Logger.Log(User.Identity.Name, Request.Path, ex.Message); return(View()); } catch (Exception ex) { TempData["errormessage"] = ex.Message; Logger.Log(User.Identity.Name, Request.Path, ex.Message); return(View()); } }
public IActionResult CreateShop(CreateShopViewModel model) { string EncodedResponse = Request.Form["g-recaptcha-response"]; var isCaptchaValid = CaptchaResponse.Validate(EncodedResponse); if (!ModelState.IsValid) { return(View(model)); } var user = this._context.Users.FirstOrDefault(u => u.Id == model.UserId); var userRole = this._context.UserRoles.FirstOrDefault(u => u.UserId == user.Id); if (isCaptchaValid) { if (userRole.Role != Role.ShopAdmin) { this._context.UserRoles.Add(new UserRole() { Id = Guid.NewGuid(), UserId = user.Id.Value, Role = Infrastructures.Domain.Enums.Role.ShopAdmin }); if (user != null) { Shop shop = new Shop() { BusinessContact = model.BusinessContact, BusinessEmailAddress = model.BusinessEmailAddress, BusinessLocation = model.BusinessLocation, BusinessName = model.BusinessName, BusinessType = model.BusinessType, OpenAt = model.OpenAt, CloseAt = model.CloseAt, Id = Guid.NewGuid(), UserId = model.UserId, Status = Infrastructures.Domain.Enums.Status.Active, BusinessDescription = model.BusinessDescription, OwnerShop = model.OwnerShop, IsPublished = true, }; this._context.Shops.Add(shop); this._context.SaveChanges(); } } } return(RedirectToAction("Welcome")); }
public ActionResult Cadastro(Cadastro cad) { CaptchaResponse captchaResponse = Funcoes.ValidateCaptcha(Request["g-recaptcha-response"]); if (captchaResponse.Success && ModelState.IsValid) { if (db.Usuario.Where(x => x.Email == cad.Email).ToList().Count > 0) { ModelState.AddModelError("", "E-mail já cadastrado"); return(View(cad)); } if (db.Usuario.Where(x => x.EmailRecuperacao == cad.EmailRecuperacao).ToList().Count > 0) { ModelState.AddModelError("", "E-mail de Recuperação já cadastrado"); return(View(cad)); } if (cad.Email == cad.EmailRecuperacao) { ModelState.AddModelError("", "O E-mail de Recuperação não pode ser igual ao E-mail"); return(View(cad)); } if (Funcoes.ValidateCPF(cad.Cpf) == false) { ModelState.AddModelError("", "O CPF não é válido"); return(View(cad)); } Usuario usu = new Usuario(); usu.Nome = cad.Nome; usu.Celular = cad.Celular; usu.DataNascimento = cad.DataNascimento; usu.Cpf = cad.Cpf; usu.Email = cad.Email; usu.EmailRecuperacao = cad.EmailRecuperacao; usu.Senha = Funcoes.HashTexto(cad.Senha, "SHA512"); usu.Biografia = ""; usu.Ativo = true; usu.Foto = cad.Nome.ToLower()[0] + ".svg"; db.Usuario.Add(usu); db.SaveChanges(); TempData["MSG"] = "success|Cadastro Concluído!"; return(RedirectToAction("Acesso")); } else if (captchaResponse.Success == false) { ModelState.AddModelError("", "reCAPTCHA Inválido"); return(View()); } return(View()); }