public virtual IActionResult CreateMember([FromBody] Member newMember) { if (Request.Headers.ContainsKey("recaptchaToken")) { string EncodeResponse = Request.Headers["recaptchaToken"]; if (EncodeResponse == null) { return(this.NotFound()); } if (!Recaptcha.Validate(EncodeResponse, reCaptcha)) { return(this.NotFound()); } } else { return(this.NotFound()); } newMember.PassWord = BCrypt.Net.BCrypt.HashPassword(newMember.PassWord); if (repository.Add(newMember) != null) { return(this.Created($"[controller]", newMember)); } return(this.NotFound()); }
async Task <(bool res, object ob)> Verify(string recaptchaKey, string IP, int expires, string hash) { #region Проверка параметров if (string.IsNullOrWhiteSpace(recaptchaKey)) { return(false, new Text("recaptchaKey == null")); } if (string.IsNullOrWhiteSpace(IP)) { IP = HttpContext.Connection.RemoteIpAddress.ToString(); } if (hash != md5.text($"{IP}:{expires}:{PasswdTo.salt}")) { return(false, new Text("hash error")); } #endregion // Проверяем reCAPTCHA if (await Recaptcha.Verify(recaptchaKey, jsonDB.Security.reCAPTCHASecret)) { return(true, null); } // Ошибка return(false, new Text("Verify == false")); }
async public Task <JsonResult> LimitRequest(string recaptchaKey, string IP, int ExpiresToMinute, string hash) { if (string.IsNullOrWhiteSpace(recaptchaKey)) { return(Json(new Text("recaptchaKey == null"))); } if (hash != md5.text($"{IP}{ExpiresToMinute}:{PasswdTo.salt}")) { return(Json(new Text("hash error"))); } // Проверяем reCAPTCHA if (await Recaptcha.Verify(recaptchaKey, jsonDB.Base.reCAPTCHASecret)) { // Создаем кеш memoryCache.Set(KeyToMemoryCache.LimitRequestToreCAPTCHA(IP), (0, ExpiresToMinute), TimeSpan.FromMinutes(ExpiresToMinute)); // Отдаем ответ return(Json(new TrueOrFalse(true))); } // Ошибка return(Json(new Text("Verify == false"))); }
public bool ValidReCaptcha() { string response = Request["g-recaptcha-response"]; string url = Recaptcha.GetURL(response); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); try { using (WebResponse wResponse = request.GetResponse()) { using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream())) { string json = readStream.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); Recaptcha data = js.Deserialize <Recaptcha>(json); return(Convert.ToBoolean(data.Success)); } } } catch (WebException exception) { Utility.Log(exception); } return(false); }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult chall = bindingContext.ValueProvider.GetValue("recaptcha_challenge_field"); ValueProviderResult resp = bindingContext.ValueProvider.GetValue("recaptcha_response_field"); if (chall != null && resp != null && !string.IsNullOrEmpty(chall.AttemptedValue) && !string.IsNullOrEmpty(resp.AttemptedValue)) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName + ".recaptcha_challenge_field", chall); bindingContext.ModelState.SetModelValue(bindingContext.ModelName + ".recaptcha_response_field", resp); Recaptcha rec = new Recaptcha { recaptcha_challenge_field = ((string[])chall.RawValue)[0], recaptcha_response_field = ((string[])resp.RawValue)[0] }; try { if (!rec.Verify()) bindingContext.ModelState.AddModelError(bindingContext.ModelName, "You typed the pictured text incorrectly, please try again"); } catch { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "We could not validate you typed the pictured words correctly, please try again"); } return rec; } else { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Please type the pictured text into the box underneath it"); return null; } }
public RecaptchaService(IOptions <Recaptcha> recaptcha, HttpClient httpClient) { _httpClient = httpClient; _recaptcha = recaptcha.Value; _retryPolicy = Policy.Handle <HttpRequestException>().RetryAsync(3); }
public async Task <dynamic> CreateUser([FromBody] dynamic request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } string responseRecaptcha = request.responseRecaptcha; if (!Recaptcha.IsValid(responseRecaptcha, _env, _config)) { var createResponse = new { isValid = false, error = "Invalid captcha validation" }; return(createResponse); } using (var httpClient = new HttpClient()) { using (var content = new StringContent(JsonConvert.SerializeObject(request), System.Text.Encoding.UTF8, "application/json")) { content.Headers.Clear(); content.Headers.Add("Content-Type", "application/json"); var response = await httpClient.PostAsync(this._config["AppApiDomain"] + "/api/user", content); dynamic token = JsonConvert.DeserializeObject <dynamic>(await response.Content.ReadAsStringAsync()); return(token); } } }
public async Task <ActionResult> ContactUs([FromServices] DataContext dataContext, ContactUsViewModel data) { if (ModelState.IsValid) { if (!Recaptcha.Validate(Request.Form["g-recaptcha-response"])) { ModelState.AddModelError("ReCaptchaValid", "ReCaptcha failed please try again"); } else { ContactSubmission contactSubmission = ContactSubmission.CreateFromViewModel(data); contactSubmission.EmailedTo = Settings.Emails.ToAddresses; dataContext.ContactSubmissions.Add(contactSubmission); dataContext.SaveChanges(currentUserName); Response resp = await EmailFacade.SendAsync(contactSubmission); SimpleNotifier noty = notifier(); if (resp.StatusCode == HttpStatusCode.Accepted) { noty.AddMessage(MsgTypes.Success, "Thanks for getting in contact, we will reply in due course"); return(Redirect("/")); } else { noty.AddMessage(MsgTypes.Warning, "Problems sending sending your message, please try again."); return(View(data)); } } } return(View(data)); }
async public Task <JsonResult> Base(string recaptchaKey, int HourCacheToUser, string hash) { if (string.IsNullOrWhiteSpace(recaptchaKey)) { return(Json(new Text("recaptchaKey == null"))); } if (hash != md5.text($"{HourCacheToUser}:{PasswdTo.salt}")) { return(Json(new Text("hash error"))); } // Проверяем reCAPTCHA if (await Recaptcha.Verify(recaptchaKey, jsonDB.Base.reCAPTCHASecret)) { // Валидные куки string cookie = Engine.core.AntiBot.GetValidCookie(HourCacheToUser, HttpContext.Connection.RemoteIpAddress.ToString()); // Отдаем ответ return(Json(new { result = true, cookie = cookie, HourToCookie = HourCacheToUser })); } // Ошибка return(Json(new Text("Verify == false"))); }
public ActionResult NewComment(CommentAttributes commentAttributes) { // Get item url var itmUrl = new UriBuilder(LinkManager.GetItemUrl(Context.Database.GetItem(commentAttributes.BlogPostId), new UrlOptions { AlwaysIncludeServerUrl = true })); BlogpostId = commentAttributes.BlogPostId; Recaptcha recaptcha = new Recaptcha(); GetSettings objGetSettings = new GetSettings(); var setting = objGetSettings.GetSetting(BlogpostId); commentAttributes.CaptchaResponse = Request["g-recaptcha-response"]; try { Comment cmt = new Comment { PostId = commentAttributes.BlogPostId, Author = commentAttributes.AuthorName, Email = commentAttributes.AuthorEmail, Date = DateTime.Now, Body = commentAttributes.AuthorComment }; if (setting.SiteKey.IsNullOrEmpty()) { // Insert comment in comment in mongodb database. _objRepository.Insert(cmt); SendMailToAdmin(BlogpostId); var uri = AddQuery(itmUrl, "status", "success"); Response.Redirect(uri.ToString()); } if (!setting.SiteKey.IsNullOrEmpty()) { if (recaptcha.Validate(commentAttributes.CaptchaResponse, BlogpostId)) { // Insert comment in comment in mongodb database. _objRepository.Insert(cmt); SendMailToAdmin(BlogpostId); var uri = AddQuery(itmUrl, "status", "success"); Response.Redirect(uri.ToString()); } else { Log.Error("Captcha not filled", this); var errorUri = AddQuery(itmUrl, "status", "captchaerror"); Response.Redirect(errorUri.ToString()); } } } catch (Exception ex) { Log.Error(ex.Message, this); var errorUri = AddQuery(itmUrl, "status", "error"); Response.Redirect(errorUri.ToString()); } return(Json("ok", JsonRequestBehavior.AllowGet)); }
public ActionResult ProcessRecaptcha(string captchaResponse) { var recaptcha = new Recaptcha(); var result = recaptcha.Verify(captchaResponse); return(Json(result)); }
public async Task <ActionResult> TutorRegister(TutorRegisterViewModel model) { if (ModelState.IsValid) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (Recaptcha.Validate(EncodedResponse) == "true" ? true : false); if (IsCaptchaValid) { var check = Utility.CheckUserAge(model.Birthday); if (check == false) { ViewData["Message"] = "You are too young!"; return(View(model)); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var user2 = UserManager.FindByEmail(model.Email); new TutorRepository().SaveTutor( new Tutor() { Name = model.Name, Email = user2.Email, Birthday = model.Birthday, Address = model.Address, Postcode = model.Postcode, NiN = model.NiN, MobileNumber = model.MobileNumber, UserId = user2.Id }); new RolesRepository().UserManger().AddToRoles(user2.Id, "Tutor"); string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account"); ViewBag.Message = "Check your email and confirm your account, you must be confirmed " + "before you can log in."; ViewBag.UserId = user.Id; return(View("Info")); } ViewData["Message"] = "User already exist!"; AddErrors(result); } else { TempData["recaptcha"] = "Please verify that you are not a robot!"; } } // If we got this far, something failed, redisplay form return(View(model)); }
bool CheckRecaptcha(string email, Info info, out double score) { score = 0; Recaptcha.Token token; // Val ReCaptchaV3: Since 1st login Posts to this page your can't use ReCaptcha if (!Recaptcha.IsValidV3(Request.Form["g-recaptcha-responsev3"], true, out token)) { return(false); // Can't throw error (above) } score = token.Score; // SQL Save Human Score if (_sql.State == ConnectionState.Closed) { _sql.Open(); } // SQL Make sure there is a day change to submit ---------------------- var com = new SqlCommand("SELECT TOP 1 [dateTime] FROM [HumanScore] WHERE [userid]=@userid ORDER BY [dateTime] DESC", _sql); com.Parameters.AddWithValue("@userid", info.id); var reader = com.ExecuteReader(); bool add; // Make sure it is a different day if (reader.Read()) { add = Data.DateTimeValue(DateTime.Now) != (int)reader["dateTime"]; } else { add = true; } reader.Close(); // SQL: Insert HumanScore if true -------------------------------------- if (add) { com = new SqlCommand("INSERT INTO [HumanScore] ([userid],[humanScore],[dateTime],[page]) VALUES (@userid,@humanScore,@dateTime,@page)", _sql); com.Parameters.AddWithValue("@userid", info.id); com.Parameters.AddWithValue("@humanScore", (float)token.Score); com.Parameters.AddWithValue("@dateTime", Data.DateTimeValue(DateTime.Now)); com.Parameters.AddWithValue("@page", "Login"); if (com.ExecuteNonQuery() == 0) { throw new Exception("Could Not insert HumanScore. email: " + info.Email); } } // SQL: Delete Older data of 50+ --------------------------------------- com = new SqlCommand("DELETE FROM [HumanScore] WHERE [id] IN " + "(SELECT [id] FROM (SELECT [id],ROW_NUMBER() OVER(ORDER BY [dateTime] DESC) AS rw FROM [HumanScore] WHERE [userid]=@userid)" + "res WHERE res.rw > @max)", _sql); com.Parameters.AddWithValue("@userid", info.id); com.Parameters.AddWithValue("@max", 5); com.ExecuteNonQuery(); // Ok, if No rows updated // Return return(true); }
public RegisterModel(ForumDbContext context, CommonUtils utils, IConfiguration config, IHttpClientFactory httpClientFactory, LanguageProvider languageProvider, UserService userService) { _context = context; _utils = utils; _config = config; _recaptchaOptions = _config.GetObject <Recaptcha>(); _gClient = httpClientFactory.CreateClient(_recaptchaOptions.ClientName); LanguageProvider = languageProvider; _userService = userService; }
public ActionResult Index(string name) { var recaptchaResponse = Recaptcha.Verify(); if (!recaptchaResponse.Success) { ModelState.AddModelError("Recaptcha", "Informe que você não é um robô clicando no quadro do reCAPTCHA"); } return(View()); }
bool CheckRecaptcha(string email) { Recaptcha.Token token; // Val ReCaptchaV2 Checkbox if (!Recaptcha.IsValidV3(Request.Form["g-recaptcha-response"], false, out token)) { lbErrorMsg.Text = "Please check the ReCaptcha checkbox at the bottom and follow the prompt if need be. Additionally, check the checkbox before clicking the submit button."; return(false); } // Return true return(true); }
// Re-Captcha bool CheckRecaptcha(string email, out double score) { Recaptcha.Token token; score = 0; // Val ReCaptchaV3 if (!Recaptcha.IsValidV3(Request.Form["g-recaptcha-responsev3"], true, out token)) { throw new Exception("ReCaptchaV3 was unsuccessful. email: " + email); } score = token.Score; return(token.Success); }
public async Task <ClientToken> GetClientToken([FromBody] ClientLoginRequest request, Boolean?mock = false) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (!Recaptcha.IsValid(request.responseRecaptcha, _env, _config)) { ClientToken ct = new ClientToken(); ct.error = "Invalid captcha validation"; ct.error_description = "Invalid captcha validation"; return(ct); } var BaseURL = this._config["AppApiDomain"] + "/api/user/authenticate"; if (mock.HasValue && mock.Value) { BaseURL = "http://" + this.Request.Host.Value + ("/mocks/get-token.json"); return(new ClientToken { access_token = "token" }); } var postData = new List <KeyValuePair <string, string> >(); postData.Add(new KeyValuePair <string, string>("client_id", this._config["client_id"])); postData.Add(new KeyValuePair <string, string>("client_secret", this._config["client_secret"])); postData.Add(new KeyValuePair <string, string>("client_type", "webclient")); postData.Add(new KeyValuePair <string, string>("grant_type", "password")); postData.Add(new KeyValuePair <string, string>("username", request.username)); postData.Add(new KeyValuePair <string, string>("password", request.password)); postData.Add(new KeyValuePair <string, string>("TwoFactorAuthentication", request.twoFactorAuthentication)); postData.Add(new KeyValuePair <string, string>("client_ip", this.Request.HttpContext.Connection.RemoteIpAddress.ToString())); using (var httpClient = new HttpClient()) { using (var content = new FormUrlEncodedContent(postData)) { content.Headers.Clear(); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); var response = await httpClient.PostAsync(BaseURL, content); var stringResponse = await response.Content.ReadAsStringAsync(); var token = JsonConvert.DeserializeObject <ClientToken>(stringResponse); return(token); } } }
public ActionResult ReplyComment(ReplyCommentAttributes commentAttributes) { BlogpostId = commentAttributes.CurrentItem; Recaptcha recaptcha = new Recaptcha(); GetSettings objGetSettings = new GetSettings(); var setting = objGetSettings.GetSetting(BlogpostId); try { Comment cmt = new Comment { PostId = commentAttributes.CurrentItem, CommentId = Guid.NewGuid().ToString(), ParentId = commentAttributes.hfParentCommentId, Author = commentAttributes.Name, Email = commentAttributes.Email, Date = DateTime.Now, Body = commentAttributes.Comment }; if (setting.SiteKey.IsNullOrEmpty()) { // Insert comment in comment in mongodb database. _objRepository.Insert(cmt); SendMailToAdmin(BlogpostId); return(Json("success", JsonRequestBehavior.AllowGet)); } if (!setting.SiteKey.IsNullOrEmpty()) { if (recaptcha.Validate(commentAttributes.captchaResponse, BlogpostId)) { // Insert comment in comment in mongodb database. _objRepository.Insert(cmt); SendMailToAdmin(BlogpostId); return(Json("success", JsonRequestBehavior.AllowGet)); } else { Log.Error("Captcha not filled", this); return(Json("captchaerror", JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { Log.Error(ex.Message, this); return(Json("error", JsonRequestBehavior.AllowGet)); } return(Json("ok", JsonRequestBehavior.AllowGet)); }
public ActionResult ThumbUp(String itemKey, string captchaChallenge, string captchaResponse) { if (!string.IsNullOrEmpty(captchaChallenge) && !string.IsNullOrEmpty(captchaResponse)) { var validCaptcha = Recaptcha.Validate(captchaChallenge, captchaResponse, Request.UserHostAddress); if (!validCaptcha) { return(this.EmptyHtml()); } } else if (string.IsNullOrEmpty(captchaResponse) && !string.IsNullOrEmpty(captchaChallenge)) { return(this.EmptyHtml()); } AddDatasetVote(1, itemKey); return(this.GetRefreshedRatesHtml(itemKey)); }
bool CheckRecaptcha(string email, out double score) { Recaptcha.Token token; score = 0; // Val ReCaptchaV2 Checkbox if (!Recaptcha.IsValidV3(Request.Form["g-recaptcha-response"], false, out token)) { lbErrorMsg.Text = "Please check the ReCaptcha checkbox at the bottom and follow the prompt if need be. Additionally, check the checkbox before clicking the submit button."; return(false); } // Val ReCaptchaV3 if (!Recaptcha.IsValidV3(Request.Form["g-recaptcha-responsev3"], true, out token)) { throw new Exception("ReCaptchaV3 was unsuccessful. email: " + email); } score = token.Score; return(token.Success); }
public void ValidateCaptchaKey(object sender, EventArgs e) { Recaptcha recaptcha = new Recaptcha(); string CaptchaResponse = Request["g-recaptcha-response"]; if (recaptcha.Validate(CaptchaResponse) && !siteKey.IsNullOrEmpty()) { InsertNewComment(); } else { lblInfoText.Text = "Captcha not filled or not match"; } if (siteKey.IsNullOrEmpty()) { InsertNewComment(); } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (Recaptcha.Validate(EncodedResponse) == "True" ? true : false); if (IsCaptchaValid == true) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, DOB = model.DOB }; 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 http://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 (IsCaptchaValid == false) { CaptchaError(); Dispose(true); return(View(model)); } } // If we got this far, something failed, redisplay form return(View(model)); }
// Method:POST \\ public bool ValidateUserResponse(string recaptcha_response) { string secret = ConfigurationManager.AppSettings["SecretKEY"]; //Get Secret from Web.config recaptcha_response = "response=" + recaptcha_response; //Create Client RestClient client = new RestClient(Url + secret + "&" + recaptcha_response); //Build A Request For The Api RestRequest request = new RestRequest(Method.POST); //Execute Request var response = client.Execute(request).Content; //Desirialise Response(JSON) To Model Recaptcha recaptcha = JsonConvert.DeserializeObject <Recaptcha>(response); return(recaptcha.success); }
public IActionResult PhaseThree(PhaseThreePostViewModel model) { string EncodedResponse = Request.Form["g-recaptcha-response"]; var isCaptchaValid = Recaptcha.Validate(EncodedResponse); if (!ModelState.IsValid) { return(View(model)); } var user = this._context.Users.FirstOrDefault(u => u.Id == model.UserId); var booking = this._context.Bookings.FirstOrDefault(b => b.Id == model.BookingId); if (isCaptchaValid) { if (user != null) { if (booking != null) { booking.UserName = user.UserName; booking.PhoneNumber = model.PhoneNumber; booking.Email = model.Email; booking.Time = model.Time; booking.BookingAddress = model.Address; this._context.Bookings.Update(booking); this._context.SaveChanges(); } } } else { ModelState.AddModelError("", "Error From Google ReCaptcha :" + isCaptchaValid); return(View()); } //return Content(@"/home/service-book/" + model.UserId); //return Content(@"/feedback/user-feedbacks/" + model.UserId + "/" + model.ServiceId ); return(Content(@"/booking/book-review/" + booking.Id)); }
public ActionResult SubmitQuery(Query query) { if (!ModelState.IsValid) { return(View("Index")); } var response = Request["g-recaptcha-response"]; //string secretKey = "6LfV1HkUAAAAAPUeSeHOzVvqQvbdPrl0J8f87qwE"; var client = new WebClient(); string encodedResponse = Request["g-recaptcha-response"]; bool isCaptchaValid = (Recaptcha.Validate(encodedResponse) == "true" ? true : false); if (!isCaptchaValid) { TempData["recaptcha"] = "Please verify that you are not a robot"; return(View("Index")); } else { //subjectTitle string subjectTitle = "You have a query from " + query.firstName + " " + query.lastName; //emailBody string emailBody = "Name: " + query.firstName + " " + query.lastName + "<br />" + "Email: " + query.email + "<br />" + "Mobile: " + query.mobile + "<br />" + "Company Name: " + query.companyName + "<br />" + "Company Turnover: " + query.turnOver + "<br />" + "Message: " + query.message; sendMail(subjectTitle, emailBody); //send success msg to Action TempData["successMsg"] = "Your query has been received. We will contact you soon."; return(RedirectToAction("Index", "Home")); } }
protected void BtnGetResult_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(WebAccessCodeTextBox.Text)) { this.ErrorLabel.Text = GetLocalResourceObject("ErrorLabelText").ToString(); } else { if (Convert.ToInt32(Session["numberIncorrectPassword"]) >= 5) { if (String.IsNullOrEmpty(Recaptcha.Response)) { this.ErrorLabel.Text = GetLocalResourceObject("CaptchaNullOrEmpty").ToString(); } else { RecaptchaVerificationResult result = Recaptcha.Verify(); if (result == RecaptchaVerificationResult.Success) { Session["numberIncorrectPassword"] = 0; this.Recaptcha.Style["display"] = "none"; this.ErrorLabel.Text = null; GetResult(); } if (result == RecaptchaVerificationResult.IncorrectCaptchaSolution) { this.ErrorLabel.Text = GetLocalResourceObject("CaptchaIncorrect").ToString(); } else { GetResult(); } } } else { GetResult(); } } }
public ActionResult Add(string name, string subject, string comment, string email, string type, bool notify, string datasetId, string datasetName, string parentType, string container, string captchaChallenge, string captchaResponse) { var validCaptcha = Recaptcha.Validate(captchaChallenge, captchaResponse, Request.UserHostAddress); if (!validCaptcha || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(comment) || string.IsNullOrEmpty(datasetId)) { return(EmptyHtml()); } var result = new Comment { Subject = subject, Body = comment, Posted = DateTime.Now, Email = email, Type = type, Status = "New", Notify = notify && !string.IsNullOrEmpty(email), ParentName = datasetId, ParentType = parentType, Author = name, ParentContainer = container, }; CommentRepository.AddComment(result); string linkToParent = Request.UrlReferrer.AbsoluteUri; var ni = new NotifyInfo { CommentEntry = result, Link = linkToParent, DatasetName = datasetName, }; Action <NotifyInfo> notification = SendNotification; notification.BeginInvoke(ni, null, null); return(View("Comment", result)); }
protected void btnlogin_Click(object sender, EventArgs e) { var username = usernametxt.Text; var password = passwordtxt.Text; var rememberMe = chkRememberMe.Checked; var EncodedResponse = Request.Form["g-Recaptcha-Response"]; var IsCaptchaValid = Recaptcha.Validate(EncodedResponse) == "true" ? true : false; //if (IsCaptchaValid) //{ if (Page.IsValid) { //string username = usernametxt.Text; //string password = passwordtxt.Text; //bool rememberMe = chkRememberMe.Checked; // Login the user User u = OneDB.Users.SingleOrDefault( x => x.Username == username && x.Password == Security.GetHash(password) ); if (u != null) { //FormsAuthentication.RedirectFromLoginPage(u.Username, rememberMe); Session["email"] = u.Email; Session["id"] = u.Id; Session["username"] = u.Username; Session["role"] = u.role; Security.LoginUser(u.Username, u.role, rememberMe); Response.Redirect("~/Home.aspx"); } else { Label2.Text = "Username or Password incorrect"; } } }
public ActionResult Index(FormCollection collection) { Contact contact = new Contact(); TryUpdateModel(contact); contact.BestTimeToCall = ConvertTimeInput(collection["Hour"], collection["Minute"], collection["Meridiem"]); bool success = false; Dictionary <String, String> disclaimers = new Dictionary <string, string>(); string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = EncodedResponse != null ? (Recaptcha.Validate(EncodedResponse)) : false; Dictionary <String, List <String> > validationErrors = ContactValidation.Validate(contact); ViewData["ValidationErrors"] = validationErrors; if (validationErrors.Count == 0) { if (IsCaptchaValid) { using (var db = new ContactUsEntities()) { db.Contacts.Add(contact); db.SaveChanges(); success = true; disclaimers.Add("success", "Your form has been successfully submitted!"); } } else { disclaimers.Add("warning", "ReCAPTCHA is invalid. Please try reCAPTCHA again!"); } } ViewData["Disclaimers"] = disclaimers; return(success ? View(EmptyContact()) : View(contact)); }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult chall = bindingContext.ValueProvider.GetValue("recaptcha_challenge_field"); ValueProviderResult resp = bindingContext.ValueProvider.GetValue("recaptcha_response_field"); if (chall != null && resp != null && !string.IsNullOrEmpty(chall.AttemptedValue) && !string.IsNullOrEmpty(resp.AttemptedValue)) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName + ".recaptcha_challenge_field", chall); bindingContext.ModelState.SetModelValue(bindingContext.ModelName + ".recaptcha_response_field", resp); Recaptcha rec = new Recaptcha { recaptcha_challenge_field = ((string[])chall.RawValue)[0], recaptcha_response_field = ((string[])resp.RawValue)[0] }; try { if (!rec.Verify()) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "You typed the pictured text incorrectly, please try again"); } } catch { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "We could not validate you typed the pictured words correctly, please try again"); } return(rec); } else { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Please type the pictured text into the box underneath it"); return(null); } }
public override System.Web.Mvc.JsonResult Index(Recaptcha.MvcModel.RecaptchaValidationModel model) { var callInfo = new T4MVC_JsonResult(Area, Name, ActionNames.Index); ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "model", model); return callInfo; }