protected void LogIn(object sender, EventArgs e) { if (!ReCaptcha.Validate(CaptchaSecret, Request.Form["g-recaptcha-response"])) { FailureText.Text = "reCAPTCHA error"; ErrorMessage.Visible = true; } else if (IsValid) { // Validate the user password var manager = new UserManager(); ApplicationUser user = manager.Find(UserName.Text, Password.Text); if (user != null) { IdentityHelper.SignIn(manager, user, RememberMe.Checked); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }
protected void captcha_validate(object source, ServerValidateEventArgs args) { //captcha start var encodedResponse = Request.Form["g-Recaptcha-Response"]; System.Diagnostics.Debug.WriteLine(encodedResponse); var isCaptchaValid = ReCaptcha.Validate(encodedResponse); System.Diagnostics.Debug.WriteLine(isCaptchaValid); //done at the customvalidator side if (!isCaptchaValid) { System.Diagnostics.Debug.WriteLine("Captcha failure"); args.IsValid = false; // E.g. Return to view or set an error message to visible } else { args.IsValid = true; } //captcha end }
public void AssertTestWillConectAndFailInvalidUserAnswer() { ReCaptcha.Configure(SiteKey, SecretKey); Assert.Throws <ReCaptchaException>(() => ReCaptcha.ValidateCaptcha("resposta-fajuta")); }
public void WrongSecretKeyArgumentException() { Assert.Throws <ArgumentNullException>(() => ReCaptcha.Configure("something", null)); }
public void ExceptionWhenNotConfigured() { Assert.Throws <ReCaptchaException>(() => ReCaptcha.GetCaptcha()); }
public async Task <ActionResult> Apply(SoulWorkerViewModel model) { if (ModelState.IsValid) { //Get Captcha Response string userResponse = Request["g-recaptcha-response"]; /* Previous formatting for Discord markdown (wasn't in a code block) * * string application = "__**Application**__\n\n**"+ Request["Q1"] + "**\n" + model.CharacterName + * "\n\n**" + Request["Q2"] + "**\n" + model.Class + * "\n\n**" + Request["Q3"] + "**\n" + model.Location + * "\n\n**" + Request["Q4"] + "**\n" + model.Experience + * "\n\n**" + Request["Q5"] + "**\n" + model.Preference + * "\n\n**" + Request["Q6"] + "**\n" + model.Voice + * "\n\n**" + Request["Q7"] + "**\n" + model.Playtime + * "\n\n**" + Request["Q8"] + "**\n" + model.PlayerType + * "\n\n**" + Request["Q9"] + "**\n" + model.PrevGuilds + * "\n\n**" + Request["Q10"] + "**\n" + model.LookingFor + * "\n\n**" + Request["Q11"] + "**\n" + model.PrevMMOs + * "\n\n**" + Request["Q12"] + "**\n" + model.Contribute + "\n\n\n"; */ //Build String to send to Discord Webhook string application = "```ini\n[" + Request["Q1"] + "]\n" + model.CharacterName + "\n\n[" + Request["Q2"] + "]\n" + model.Class + "\n\n[" + Request["Q3"] + "]\n" + model.CharacterLevel + "\n\n[" + Request["Q4"] + "]\n" + model.Location + "\n\n[" + Request["Q5"] + "]\n" + model.Experience + "\n\n[" + Request["Q6"] + "]\n" + model.Preference + "\n\n[" + Request["Q7"] + "]\n" + model.Voice + "\n\n[" + Request["Q8"] + "]\n" + model.Playtime + "\n\n[" + Request["Q9"] + "]\n" + model.PlayerType + "\n\n[" + Request["Q10"] + "]\n" + model.PrevGuilds + "\n\n[" + Request["Q11"] + "]\n" + model.LookingFor + "\n\n[" + Request["Q12"] + "]\n" + model.PrevMMOs + "\n\n[" + Request["Q13"] + "]\n" + model.Contribute + "\n\n[" + Request["Q14"] + "]\n" + model.DiscordHandle + "\n\n[" + Request["Q15"] + "]\n" + model.TwitchHandle + "\n\n[" + Request["Q16"] + "]\n" + model.YouTubeHandle + "```\n"; /*Build XML to put in Answers column, Q[n] are questions from * hidden inputs to store what the questions were at the time in DB */ XElement xml = new XElement("Application", new XElement("Answer", new XAttribute("Question", Request["Q2"]), model.Class), new XElement("Answer", new XAttribute("Question", Request["Q3"]), model.CharacterLevel), new XElement("Answer", new XAttribute("Question", Request["Q4"]), model.Location), new XElement("Answer", new XAttribute("Question", Request["Q5"]), model.Experience), new XElement("Answer", new XAttribute("Question", Request["Q6"]), model.Preference), new XElement("Answer", new XAttribute("Question", Request["Q7"]), model.Voice), new XElement("Answer", new XAttribute("Question", Request["Q8"]), model.Playtime), new XElement("Answer", new XAttribute("Question", Request["Q9"]), model.PlayerType), new XElement("Answer", new XAttribute("Question", Request["Q10"]), model.PrevGuilds), new XElement("Answer", new XAttribute("Question", Request["Q11"]), model.LookingFor), new XElement("Answer", new XAttribute("Question", Request["Q12"]), model.PrevMMOs), new XElement("Answer", new XAttribute("Question", Request["Q13"]), model.Contribute), new XElement("Answer", new XAttribute("Question", Request["Q14"]), model.DiscordHandle), new XElement("Answer", new XAttribute("Question", Request["Q15"]), model.TwitchHandle), new XElement("Answer", new XAttribute("Question", Request["Q16"]), model.YouTubeHandle)); //If Captcha is valid, proceed bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (validCaptcha) { //Send string to Discord Webhook DiscordWebhook.Webhook hook = new DiscordWebhook.Webhook("https://discordapp.com/api/webhooks/436045068197953536/YrzV8IBv51P0YOpN5HOreei4-fU9crjsyofjo_0MGyCYbA6cTtHLzT8BcmxdPc8C9q2Q"); await hook.Send(application, "Website Application", "https://tsubasa.kr/Images/logo.png"); //DB connection var connection = ConfigurationManager.ConnectionStrings["TsubasaDB"]; //Store application in database using (SqlConnection conn = new SqlConnection(connection.ConnectionString)) { using (SqlCommand command = new SqlCommand() { CommandType = System.Data.CommandType.StoredProcedure, CommandText = "Apply", Connection = conn }) { conn.Open(); command.Parameters.AddWithValue("@CharacterName", model.CharacterName); command.Parameters.AddWithValue("@Game", "SoulWorker"); command.Parameters.AddWithValue("@Answers", xml.ToString()); command.ExecuteNonQuery(); } } return(RedirectToAction("Confirm", "SoulWorker")); } else { return(RedirectToAction("Apply", "SoulWorker")); } } return(View()); }
protected void ilan_ver_Click(object sender, EventArgs e) { var encodedResponse = Request.Form["g-Recaptcha-Response"]; var isCaptchaValid = ReCaptcha.Validate(encodedResponse); var connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); //Insert float ucretInt = float.Parse(ucret.Text, System.Globalization.CultureInfo.InvariantCulture); //string queryInsert = "INSERT INTO [dbo].[Bike]([Brand],[Category],[Picture],[Description],[Transmission],[AdsHeader],[Price],[Currency],[Availability],[AddingDate])"; //File and attributes HttpPostedFile postedFile = resim_yukle.PostedFile; string fileName = Path.GetFileName(postedFile.FileName); string fileExtension = Path.GetExtension(fileName); int fileSize = postedFile.ContentLength; //Current Project path string projectPath = AppDomain.CurrentDomain.BaseDirectory; //Full path to upload string fileUploadPath = projectPath + "\\BikePic\\" + fileName; //Upload the file to project resim_yukle.SaveAs(fileUploadPath); //data base path string fileDowloadPath = "~/BikePic/" + fileName; if (isCaptchaValid) { if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".bmp") { connection.Open(); try { if (connection.State == ConnectionState.Open && sozlesme.Checked) { SqlCommand cmd = new SqlCommand("BikeInsert", connection); cmd.CommandType = CommandType.StoredProcedure; SqlParameter paramOwner = new SqlParameter() { ParameterName = "@owner", Value = Convert.ToInt32(Session["kullaniciID"]) }; cmd.Parameters.Add(paramOwner); SqlParameter paramMarka = new SqlParameter() { ParameterName = "@marka", Value = marka.Text }; cmd.Parameters.Add(paramMarka); SqlParameter paramTur = new SqlParameter() { ParameterName = "@tur", Value = tur.SelectedValue }; cmd.Parameters.Add(paramTur); SqlParameter paramImage = new SqlParameter() { ParameterName = "@image", Value = fileDowloadPath }; cmd.Parameters.Add(paramImage); SqlParameter paramAciklama = new SqlParameter() { ParameterName = "@aciklama", Value = ilan_aciklama.Text }; cmd.Parameters.Add(paramAciklama); SqlParameter paramVites = new SqlParameter() { ParameterName = "@vites", Value = vites.SelectedValue }; cmd.Parameters.Add(paramVites); SqlParameter paramBaslik = new SqlParameter() { ParameterName = "@baslik", Value = ilan_baslik.Text }; cmd.Parameters.Add(paramBaslik); SqlParameter paramUcret = new SqlParameter() { ParameterName = "@ucret", Value = ucretInt }; cmd.Parameters.Add(paramUcret); SqlParameter paramBirim = new SqlParameter() { ParameterName = "@birim", Value = parabirim.SelectedValue }; cmd.Parameters.Add(paramBirim); SqlParameter paramUlasik = new SqlParameter() { ParameterName = "@ulasik", Value = 1 }; cmd.Parameters.Add(paramUlasik); SqlParameter paramDate = new SqlParameter() { ParameterName = "@datee", Value = dateTime }; cmd.Parameters.Add(paramDate); SqlParameter paramCity = new SqlParameter() { ParameterName = "@city", Value = ilBike.SelectedValue }; cmd.Parameters.Add(paramCity); SqlParameter paramCounty = new SqlParameter() { ParameterName = "@county", Value = ilceBike.SelectedValue }; cmd.Parameters.Add(paramCounty); cmd.ExecuteNonQuery(); errorbox.Text = "İlan başarıyla verildi."; } else { errorbox.Text = "Bilinmeyene hata. Yazdığınız bilgileri kontrol ediniz."; } } catch (Exception ex) { Response.Write(ex); } } } else { errorbox.Text = "İlan başarıyla verilmedi."; } connection.Close(); }
void cmdUpdate_Click(object sender, EventArgs e) { if (_hasUpdatePermission) { try { //warning message of validation has failed var warningMessage = string.Empty; warningMessage = _editControls.Values.Where(edit => !edit.IsValid()) .Aggregate(warningMessage, (current, edit) => current + string.Format( "<li><b>{0}</b><br />{1}</li>", edit.FieldTitle, edit.ValidationMessage)); if (CaptchaNeeded() && !_ctlCaptcha.IsValid) { warningMessage += string.Format("<li><b>{0}</b><br />{1}</li>", Localization.GetString("Captcha.Text", LocalResourceFile), Localization.GetString("CaptchaError.Text", LocalResourceFile)); } if (ModuleContext.PortalSettings.UserId == -1 && Settings.ForceCaptchaForAnonymous && Settings.PreferReCaptcha) { string encodedResponse = Request.Form["g-recaptcha-response"]; if (!ReCaptcha.Validate(encodedResponse, Settings.ReCaptchaSecretKey)) { warningMessage += string.Format("<li><b>{0}</b><br />{1}</li>", Localization.GetString("ReCaptcha.Text", LocalResourceFile), Localization.GetString("ReCaptchaError.Text", LocalResourceFile)); } } if (warningMessage == string.Empty) { //'Save values for every field separately foreach (var edit in _editControls.Values) { var value = edit.Value; CurrentRow[edit.FieldTitle] = value; } UdtController.UpdateRow(Data); RecordUpdated(); switch (Settings.ListOrForm) { case "List": Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); break; case "FormAndList": case "ListAndForm": var url = IsNewRow ? Request.RawUrl : Globals.NavigateURL(ModuleContext.TabId); Response.Redirect(url, true); break; case "Form": switch (Settings.UponSubmitAction) { case "Text": divForm.Visible = false; ShowUponSubmit(); break; case "Form": Response.Redirect( Globals.NavigateURL(ModuleContext.TabId, "", string.Format("OnSubmit={0}", ModuleId)), true); break; default: var strRedirectUrl = Settings.UponSubmitRedirect ?? Globals.NavigateURL(ModuleContext.TabId); Response.Redirect(Globals.LinkClick(strRedirectUrl, ModuleContext.TabId, ModuleContext.ModuleId)); break; } break; } } else { var moduleControl = (PortalModuleBase)(((Parent.Parent) is PortalModuleBase) ? Parent.Parent : this); UI.Skins.Skin.AddModuleMessage(moduleControl, string.Format("<ul style=\"padding-left:1.6em;padding-bottom:0;\">{0}</ul>", warningMessage), ModuleMessage.ModuleMessageType.RedError); } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } if (ModuleId == HrDbData.ListOfHrsModuleId) { UpdateActiveHRsInVacancies(); UpdateActiveHRsInCamps(); } } }
public JsonResult Checkout(List <UserProducts> productsList, Order order) { bool isGet = false; string message = "Упс, щось пішло не так. Спробуйте пізніше..."; string products = String.Empty; int productId; Product product; bool captcha = ReCaptcha.ValidateCaptcha(Request["g-recaptcha-response"]); for (int i = 0; i < productsList.Count; i++) { productId = productsList[i].Id; product = db.Products.Include(p => p.Category).FirstOrDefault(t => t.Id == productId); products += $"Товар - {Request.Url.Scheme}{Uri.SchemeDelimiter}{Request.Url.Authority}/{product.Category.Name}/{product.ProductCode}, кількість - {productsList[i].Quantity}\n"; } if (String.IsNullOrWhiteSpace(products)) { message = "Ваш кошик порожній!"; } else { if (String.IsNullOrWhiteSpace(order.Name) || String.IsNullOrWhiteSpace(order.Phone) || String.IsNullOrWhiteSpace(order.Email)) { message = "Заповніть контактні дані!"; } else { if (order.Payment == "1") { if (order.Delivery == "1") { if (captcha) { try { EmailService.SendEmail("*****@*****.**", "Нове замовлення", $"--- Інформація по замовленню ---\n\nІм'я: {order.Name}\nТелефон: {order.Phone}\nПошта: {order.Email}\n\nСпосіб доставки: Самовивіз з магазину\nСпосіб оплати: Оплата при отриманні\n\nСписок товарів:\n{products}"); EmailService.SendEmail($"{order.Email}", "Дякуємо за замовлення!", "Дякуємо за інтерес до товарів Online Store. Ваше замовлення отримано і надійде в обробку найближчим часом."); isGet = true; message = "Дякуємо за замовлення! Незабаром ми з вами зв'яжемось для підтвердження замовлення."; } catch (Exception ex) { isGet = false; message = ex.ToString(); } } else { message = "Ви не пройшли перевірку ReCaptcha!"; } } else if (order.Delivery == "2") { if (String.IsNullOrWhiteSpace(order.PIB) || String.IsNullOrWhiteSpace(order.DeliveryCity) || String.IsNullOrWhiteSpace(order.DeliveryWarehouse)) { message = "Заповніть дані для доставки"; } else { if (captcha) { try { EmailService.SendEmail("*****@*****.**", "Нове замовлення", $"--- Інформація по замовленню ---\n\nІм'я: {order.Name}\nТелефон: {order.Phone}\nПошта: {order.Email}\n\nСпосіб доставки: Нова Пошта\nМісто: {order.DeliveryCity}\nНомер відділення: {order.DeliveryWarehouse}\nСпосіб оплати: Оплата при отриманні\n\nСписок товарів:\n{products}"); EmailService.SendEmail($"{order.Email}", "Дякуємо за замовлення!", "Дякуємо за інтерес до товарів Online Store. Ваше замовлення отримано і надійде в обробку найближчим часом."); isGet = true; message = "Дякуємо за замовлення! Незабаром ми з вами зв'яжемось для підтвердження замовлення."; } catch (Exception ex) { message = $"Помилка: {ex.Message}"; } } else { message = "Ви не пройшли перевірку ReCaptcha!"; } } } else { message = "Оберіть спосіб доставки!"; } } else if (order.Payment == "2") { if (order.Delivery == "1") { if (captcha) { try { EmailService.SendEmail("*****@*****.**", "Нове замовлення", $"--- Інформація по замовленню ---\n\nІм'я: {order.Name}\nТелефон: {order.Phone}\nПошта: {order.Email}\n\nСпосіб доставки: Самовивіз з магазину\nСпосіб оплати: Оплата на картку ПриватБанку\n\nСписок товарів:\n{products}"); EmailService.SendEmail($"{order.Email}", "Дякуємо за замовлення!", "Дякуємо за інтерес до товарів Online Store. Ваше замовлення отримано і надійде в обробку найближчим часом."); isGet = true; message = "Дякуємо за замовлення! Незабаром ми з вами зв'яжемось для підтвердження замовлення."; } catch (Exception ex) { isGet = false; message = ex.ToString(); } } else { message = "Ви не пройшли перевірку ReCaptcha!"; } } else if (order.Delivery == "2") { if (String.IsNullOrWhiteSpace(order.PIB) || String.IsNullOrWhiteSpace(order.DeliveryCity) || String.IsNullOrWhiteSpace(order.DeliveryWarehouse)) { message = "Заповніть дані для доставки"; } else { if (captcha) { try { EmailService.SendEmail("*****@*****.**", "Нове замовлення", $"--- Інформація по замовленню ---\n\nІм'я: {order.Name}\nТелефон: {order.Phone}\nПошта: {order.Email}\n\nСпосіб доставки: Нова Пошта\nМісто: {order.DeliveryCity}\nНомер відділення: {order.DeliveryWarehouse}\nСпосіб оплати: Оплата на картку ПриватБанку\n\nСписок товарів:\n{products}"); EmailService.SendEmail($"{order.Email}", "Дякуємо за замовлення!", "Дякуємо за інтерес до товарів Online Store. Ваше замовлення отримано і надійде в обробку найближчим часом."); isGet = true; message = "Дякуємо за замовлення! Незабаром ми з вами зв'яжемось для підтвердження замовлення."; } catch (Exception ex) { message = $"Помилка: {ex.Message}"; } } else { message = "Ви не пройшли перевірку ReCaptcha!"; } } } else { message = "Оберіть спосіб доставки!"; } } else { message = "Оберіть спосіб оплати!"; } } } return(Json(new { IsGet = isGet, Message = message, JsonRequestBehavior.AllowGet })); }
protected void btnRegister_Click(object sender, EventArgs e) { try { string username = tbUsernameRegister.Text.Trim(); string email = tbEmailRegister.Text.Trim(); string password = tbPasswordRegister.Text.Trim(); string password2 = tbPassword2Register.Text.Trim(); DataTable check_username = Models.User.recieveUserDataByUserName(username); if (username.Length == 0 && email.Length == 0 && password.Length == 0 && password2.Length == 0) { throw new Exception("Fill in the required fields."); } if (check_username.Rows.Count != 0) { throw new Exception("Username already exists."); } if (hasSpecialChar(username)) { throw new Exception("Username cannot contain special characters."); } if (username.Length > 20 || username.Length < 3) { throw new Exception("The length of the name must comprise between 3 and 20 characters."); } DataTable check_email = Models.User.recieveUserDataByEmail(email); if (check_email.Rows.Count != 0) { throw new Exception("Email already registered."); } if (!IsValidEmail(email)) { throw new Exception("Invalid email."); } if (CheckingPasswordStrength(password) == PasswordScore.Blank || CheckingPasswordStrength(password) == PasswordScore.Weak || CheckingPasswordStrength(password) == PasswordScore.VeryWeak) { throw new Exception($"Password {CheckingPasswordStrength(password)}"); } if (password != password2) { throw new Exception("Passwords don't match."); } if (fuImage.HasFile == false) { throw new Exception("Image not found."); } if (fuImage.PostedFile.ContentType != "image/jpeg" && fuImage.PostedFile.ContentType != "image/jpg" && fuImage.PostedFile.ContentType != "image/png") { throw new Exception("The image file format is not supported. (Only jpeg/jpg)"); } if (fuImage.PostedFile.ContentLength == 0 || fuImage.PostedFile.ContentLength > 5000000) { throw new Exception("The file size is not valid."); } var respRecatcha = Request.Form["g-Recaptcha-Response"]; var captchavalidate = ReCaptcha.Validate(respRecatcha); if (!captchavalidate) { throw new Exception("Recaptcha's error."); } Models.User user = new Models.User(username, email, password); int id = user.add(); string file = Server.MapPath(@"~\Public\Images\Users\"); file += id + ".jpg"; fuImage.SaveAs(file); } catch (Exception error) { lbMessageRegister.Text = error.Message; lbMessageRegister.CssClass = "alert alert-danger"; } }
public async Task <ActionResult> SendEmail(ContactUsModel c) { try { c.recaptcharesponse = Request.Form["g-recaptcha-response"]; if (string.IsNullOrEmpty(c.recaptcharesponse)) { ViewBag.SentMessage = "Please tell me if you are a robot or not, thank you."; return(View("index", c)); } using (var httpc = new HttpClient()) { httpc.BaseAddress = new System.Uri(appSet.GOOGLEBASEURL); httpc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string requrl = appSet.RECAPTCHAAPI + "?secret=" + Environment.GetEnvironmentVariable("GOOGLE_RECAPTCHA") + "&response=" + c.recaptcharesponse; HttpResponseMessage resp = httpc.PostAsync(requrl, new StringContent("")).Result; if (resp.StatusCode == System.Net.HttpStatusCode.OK) { ReCaptcha r = JsonConvert.DeserializeObject <ReCaptcha>(resp.Content.ReadAsStringAsync().Result); if (!r.success) { ViewBag.SentMessage = "google failed: " + r.errorcodes; return(View("index", c)); } } else { ViewBag.SentMessage = "You are a robot or google failed please try again."; return(View("index", c)); } } string Body = string.Empty; var msg = new SendGridMessage(); msg.SetFrom(new EmailAddress(c.Email, c.Name)); var recipients = new List <EmailAddress> { new EmailAddress(Environment.GetEnvironmentVariable("EMAILADDRESS"), Environment.GetEnvironmentVariable("EMAILNAME")), }; msg.AddTos(recipients); msg.SetSubject("Web-email: " + c.Subject); StringBuilder sb = new StringBuilder("<html><body><table border='0' cellspacing='0' cellpadding='0'>"); sb.Append("<tr><td width='8%'><b>Phone:</b></td><td width='92%'>"); sb.Append(c.Phone); sb.Append("</td></tr></table><p>"); sb.Append(c.Message); sb.Append("</p></body></html>"); msg.AddContent(MimeType.Html, sb.ToString()); var client = new SendGridClient(Environment.GetEnvironmentVariable("SENDGRID_APIKEY")); var response = await client.SendEmailAsync(msg); if (response.StatusCode == System.Net.HttpStatusCode.Accepted) { ViewBag.SentMessage = "Your email was sent, we will answer you shortly!!"; } else { ViewBag.SentMessage = "There was and error Sending the email please email " + Environment.GetEnvironmentVariable("EMAILADDRESS"); } } catch (Exception ex) { ViewBag.SentMessage = "There was and error Sending the email please email " + Environment.GetEnvironmentVariable("EMAILADDRESS") + ex.Message; } return(View("index", c)); }
public HomeController(IWebHostEnvironment webHostEnvironment, EmailSender emailSender, NaniWebContext naniWebContext, ReCaptcha reCaptcha, SettingsKeeper settingsKeeper) { _webHostEnvironment = webHostEnvironment; _emailSender = emailSender; _naniWebContext = naniWebContext; _reCaptcha = reCaptcha; _settingsKeeper = settingsKeeper; }
protected void Button1_Click1(object sender, EventArgs e) { if (Page.IsValid) { System.Diagnostics.Debug.WriteLine("testing"); // Response.Redirect("errorxss.aspx", false); //captcha start :) var encodedResponse = Request.Form["g-Recaptcha-Response"]; System.Diagnostics.Debug.WriteLine(encodedResponse); var isCaptchaValid = ReCaptcha.Validate(encodedResponse); System.Diagnostics.Debug.WriteLine(isCaptchaValid); //done at the customvalidator side if (!isCaptchaValid) { System.Diagnostics.Debug.WriteLine("Captcha failure"); // E.g. Return to view or set an error message to visible } //captcha end :( //String a = TextBox1.Text; //String c = Text1.Value.ToString(); //System.Diagnostics.Debug.WriteLine("testing 1 " + a); //System.Diagnostics.Debug.WriteLine("testing 1 " + c); System.Diagnostics.Debug.WriteLine("testing"); System.Diagnostics.Debug.WriteLine("Password is: " + TextBox1.Text); System.Diagnostics.Debug.WriteLine("Salt value: " + HiddenFieldForSalt.Value); System.Diagnostics.Debug.WriteLine("Cipher received from first name: " + HiddenFieldFirstNameEncrypted.Value); System.Diagnostics.Debug.WriteLine("Cipher received from last name: " + HiddenFieldLastNameEncrypted.Value); System.Diagnostics.Debug.WriteLine("Cipher received from address: " + HiddenFieldAddressEncrypted.Value); System.Diagnostics.Debug.WriteLine("Cipher received from birthday: " + HiddenFieldBirthdayEncrypted.Value); System.Diagnostics.Debug.WriteLine("Cipher received from nric: " + HiddenFieldNricEncrypted.Value); string uUsername = Server.HtmlEncode(Username.Text); string uPasswordhash = TextBox1.Text; string uPasswordSalt = HiddenFieldForSalt.Value; string uFirstName = HiddenFieldFirstNameEncrypted.Value; string uLastName = HiddenFieldLastNameEncrypted.Value; string uPhoneNo = Server.HtmlEncode(phoneNumberInput.Text); string uAddress = HiddenFieldAddressEncrypted.Value; string uEmail = Server.HtmlEncode(emailInput.Text); string uBirthday = HiddenFieldBirthdayEncrypted.Value; string uemailverified = "false"; string uphoneVerified = "false"; string uNric = HiddenFieldNricEncrypted.Value; //hash on server side SHA512Managed hashing = new SHA512Managed(); string finalHashval; string serverhashwithSaltText = uPasswordhash + uPasswordSalt; System.Diagnostics.Debug.WriteLine("combining salt" + serverhashwithSaltText); byte[] serverHashwithSaltHashed = hashing.ComputeHash(Encoding.UTF8.GetBytes(serverhashwithSaltText)); System.Diagnostics.Debug.WriteLine("Server hashed value before convert" + serverHashwithSaltHashed); finalHashval = Convert.ToBase64String(serverHashwithSaltHashed); System.Diagnostics.Debug.WriteLine("Server hashed value " + finalHashval); // System.Diagnostics.Debug.WriteLine("DEBUGGING__???"); // // string teststring = "hello"; // // byte[] encodedteststring = hashing.ComputeHash(Encoding.UTF8.GetBytes(teststring)); // // string resultingtest = Convert.ToBase64String(encodedteststring); // // System.Diagnostics.Debug.WriteLine("test hash val " + resultingtest); //todo look into this for rfc2928 for key derivation byte[] salttoByte = Convert.FromBase64String(uPasswordSalt); System.Diagnostics.Debug.WriteLine(" "); System.Diagnostics.Debug.Write("Salt in byte array: "); for (int i = 0; i < salttoByte.Length; i++) { System.Diagnostics.Debug.Write(salttoByte[i]); } //metd for encrypot string encryptedPhone = encryptData(uPhoneNo, uPasswordhash, salttoByte); string enryptedAddress = encryptData(uAddress, uPasswordhash, salttoByte); string encryptedFirstName = encryptData(uFirstName, uPasswordhash, salttoByte); string encryptedLastName = encryptData(uLastName, uPasswordhash, salttoByte); string encryptedEmail = encryptData(uEmail, uPasswordhash, salttoByte); string encryptedBirthday = encryptData(uBirthday, uPasswordhash, salttoByte); string encryptedNric = encryptData(uNric, uPasswordhash, salttoByte); Session["nextPageUserRegEMail"] = uEmail; Session["nextPageUserRegPhone"] = uPhoneNo; Session["nextPageUserReg"] = uUsername; UserCustomer newuser = new UserCustomer(uUsername, finalHashval, uPasswordSalt, encryptedPhone, enryptedAddress, encryptedFirstName, encryptedLastName, encryptedEmail, encryptedBirthday, uemailverified, uphoneVerified, encryptedNric, HiddenFieldForsavingHashOfForget.Value.Trim()); newuser.CustomerInsert(); Fund fd = new Fund(uUsername, 0.0); fd.FundInsertNewUserOnly(); Response.Redirect("userRegisterInputConf.aspx"); } }
public bool ValidateCaptcha() { return(ReCaptcha.Validate(privateKey: "6Lcc58YSAAAAANpVZwOBTg1q1E2lj2VJ7ULpnANy")); }
public async Task <ActionResult> Register(RegisterViewModel model, string returnUrl) { try { if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"])) { if (model.Role == "0" && model.UserType == "professional") { ModelState.AddModelError("", "Select user type"); } if (ModelState.IsValid) { //SendOtp(model.PhoneNumber); // TempData["regmodel"] = model; //return RedirectToAction("ConfirmRegistration", "Account"); var user = new ApplicationUser { UserName = model.Email, Email = model.Email, LastName = model.LastName, FirstName = model.FirstName, LastIpAddress = "192.168.225.1", IsEmailUnsubscribed = false, IsPhoneNumberUnsubscribed = true, LastLoginDateUtc = DateTime.UtcNow, CreatedOnUtc = DateTime.UtcNow, PhoneNumber = model.PhoneNumber, TwoFactorEnabled = true }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (model.UserType == "professional") { await this.UserManager.AddToRoleAsync(user.Id, model.Role); var doctor = new Doctor { DoctorId = user.Id, RegistrationNumber = model.RegistrationNumber }; _doctorService.AddDoctor(doctor); } await SignInManager.SignInAsync(user, false, false); return(RedirectToAction("Index", "Home")); } } } ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext); ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"]; model.UserRoleList = GetUserTypeList(); return(View(model)); } catch (Exception) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } }
protected void btn_registar_Click(object sender, EventArgs e) { try { string email = txt_email.Text; string nome = txt_nome.Text; string nif = txt_nif.Text; DateTime data_nasc = DateTime.Parse(txt_data_nasc.Text); string password = txt_password.Text; //Validar dados //email if (email == String.Empty || email.Contains("@") == false || email.Contains(".") == false) { throw new Exception("O email indicado não é válido."); } if (DateTime.Now.Year - data_nasc.Year < 16) { throw new Exception("Deves ter no mímimo 16 anos para poderes usar a Food4U"); } //nome if (nome == String.Empty || nome.Trim().Length < 3) { throw new Exception("O nome indicado não é válido. Deve ter pelo menos 3 letras."); } //nif int inif = int.Parse(nif); if (nif.Trim().Length != 9) { throw new Exception("O NIF indicado não é válido. Deve ter 9 digitos."); } //password if (password.Trim().Length < 5) { throw new Exception("A password é muito pequena"); } var respostaRecaptcha = Request.Form["g-Recaptcha-Response"]; var valido = ReCaptcha.Validate(respostaRecaptcha); if (valido == false) { throw new Exception("Tem de provar que não é um robô."); } int perfil = int.Parse(dp_perfis.SelectedValue); int[] allowedPerfis = new int[3] { 1, 2, 3 }; if (!allowedPerfis.Contains(perfil)) { throw new Exception("O perfil indicado é inválido."); } User utilizador = new User(); utilizador.email = email; utilizador.nome = nome; utilizador.nif = nif; utilizador.data_nasc = data_nasc; utilizador.password = password; utilizador.perfil = perfil; if (perfil == 1) { AdicionarRestaurante(utilizador); } else if (perfil == 2) { AdicionarEstafeta(utilizador); } else if (perfil == 3) { utilizador.Adicionar(); } lb_erro.Text = "Registado com sucesso!"; div_erro.Attributes["class"] = "alert alert-success"; div_erro.Visible = true; ScriptManager.RegisterStartupScript(this, typeof(Page), "Redirecionar", "returnMain('/login.aspx');", true); } catch (Exception erro) { lb_erro.Text = erro.Message; div_erro.Attributes["class"] = "alert alert-danger"; div_erro.Visible = true; } }
protected void Page_Load(object sender, EventArgs e) { this.Title = "LegacyPlayers | Sign Up"; if (!IsPostBack) { return; } try { string Username = Utility.SecureInput(pmName.Value); string Password = Utility.SecureInput(pmPass.Value); string PasswordCon = Utility.SecureInput(pmPassCon.Value); string Mail = Utility.SecureInput(pmMail.Value); string MailCon = Utility.SecureInput(pmMailCon.Value); if (Username != pmName.Value || Password != pmPass.Value || PasswordCon != pmPassCon.Value || Mail != pmMail.Value || MailCon != pmMailCon.Value ) { (this.Master as RPLL.MasterPage).setNotifaction("Invalid input!", 2); return; } if (Password != PasswordCon) { (this.Master as RPLL.MasterPage).setNotifaction("Passwords do not match!", 1); return; } if (Mail != MailCon) { (this.Master as RPLL.MasterPage).setNotifaction("Mails do not match!", 1); return; } if (!Mail.Contains("@") || !Mail.Contains(".")) { (this.Master as RPLL.MasterPage).setNotifaction("Invalid email format!", 1); return; } if (Username.Length > 51) { (this.Master as RPLL.MasterPage).setNotifaction("Username is too long!", 2); return; } if (Mail.Length > 120) { (this.Master as RPLL.MasterPage).setNotifaction("Mail is too long!", 2); return; } var encodedResponse = Request.Form["g-recaptcha-response"]; var isCaptchaValid = ReCaptcha.Validate(encodedResponse); if (!isCaptchaValid) { (this.Master as RPLL.MasterPage).setNotifaction("Invalid capture!", 2); return; } Password = BCryptHelper.HashPassword(Password, "obscurred"); SQLWrapper db = App.GetDB(); var exists = db.CreateCommand(); exists.CommandText = "SELECT id FROM gn_user WHERE LOWER(name)=? OR LOWER(mail)=?"; exists.Parameters.AddWithValue("@name", Username.ToLower()); exists.Parameters.AddWithValue("@mail", Mail.ToLower()); MySqlDataReader dr = exists.ExecuteReaderRpll(); if (dr.HasRows) { dr.CloseRpll(); (this.Master as RPLL.MasterPage).setNotifaction("Username or Mail is already in use!", 2); return; } dr.CloseRpll(); Utility.SendMail("*****@*****.**", Mail, "Legacyplayers account verification", "Hello there! <br /> In order to verify your account now, you are required to click this link. <br /> You will be automatically redirected to your accountpanel then! <br /> Link: https://legacyplayers.com/Account/?verify=" + Base32.Encode(System.Text.Encoding.UTF8.GetBytes(BCryptHelper.HashPassword(Username, "obscurred"))) + "<br /> cheers!"); var cmd = db.CreateCommand(); cmd.CommandText = "INSERT INTO gn_user (name, pass, mail, registerd, uhash) VALUES (?,?,?,UNIX_TIMESTAMP(),?)"; cmd.Parameters.AddWithValue("@name", Username); cmd.Parameters.AddWithValue("@pass", Password); cmd.Parameters.AddWithValue("@mail", Mail); cmd.Parameters.AddWithValue("@uhash", Base32.Encode(System.Text.Encoding.UTF8.GetBytes(BCryptHelper.HashPassword(Username + Password, "obscurred")))); cmd.ExecuteNonQuery(); //db.Kill(); // Inserting user into the table DBUser usr = new DBUser() { Name = Username, Amount = 0, LastContribution = 0, Level = 0, Patreon = 0, Registerd = 0, uHash = Base32.Encode(System.Text.Encoding.UTF8.GetBytes(BCryptHelper.HashPassword(Username + Password, "obscurred"))) }; App.m_User.TryAdd(App.m_User.Max(x => x.Key) + 1, usr); (this.Master as RPLL.MasterPage).setNotifaction("Success! A mail has been send to you!", 3); return; } catch (Exception ex) { (this.Master as RPLL.MasterPage).setNotifaction("Something went wrong, please try again later!\n Error: " + ex.Message, 1); return; } }
public ActionResult BoardSetting(string level_1_id /*board_id*/, string board_name, string group_id, string add_users, string remove_users, string delta_flags) { if (!Util.IsAjaxRequest(Request)) { Util.ThrowBadRequestException("Not ajax post."); } if (!ReCaptcha.Validate()) { Util.ThrowBadRequestException("驗證碼不正確。"); } if (board_name != null) { if (!GroupStore.IsChairOwner(level_1_id)) { Util.ThrowUnauthorizedException("只有板主可以變更板名。"); } checkBoardName(board_name); BoardInfoStore.SetBoardSetting(level_1_id, board_name + '板'); } else if (delta_flags != null) { if (GroupStore.HasChairOwner(level_1_id) && !GroupStore.IsChairOwner(level_1_id) && !GroupStore.IsSiteOwner()) { Util.ThrowUnauthorizedException("只有板主可以變更留言板設定。"); } checkFlags(delta_flags, null, SandFlags.MT_LOW_KEY + SandFlags.MTV_SEPARATOR + "0", SandFlags.MT_LOW_KEY + SandFlags.MTV_SEPARATOR + "1"); BoardInfoStore.SetBoardFlags(level_1_id, delta_flags); } else if (group_id != null && add_users != null && remove_users != null) { if (GroupStore.HasChairOwner(level_1_id) && !GroupStore.IsChairOwner(level_1_id)) { Util.ThrowUnauthorizedException("只有板主可以變更板主、副板主、或內部群組列表。"); } if (group_id != GroupStore.ChairOwnerGroupName && group_id != GroupStore.ViceOwnerGroupName && group_id != GroupStore.InsiderGroupName) { Util.ThrowBadRequestException("群組ID格式不正確。"); } int add_cnt = SandId.CountUserNameList(add_users); int remove_cnt = SandId.CountUserNameList(remove_users); if (!Warehouse.BsMapPond.Get().IsValidBoardId(level_1_id)) { Util.ThrowBadRequestException("Invalid board ID."); } GroupStore.UpdateGroup(level_1_id, group_id, add_users, remove_users); } return(Json(new { ok = true })); }
private async Task <bool> verifyCaptcha(string captcha) { var responce = await ReCaptcha.GetRespons(captcha); return(ReCaptcha.Validate(responce));; }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { ModelState.AddModelError("", this.Resource("Invalid reCaptcha")); return(View(model)); } if (model.BirthDate.AddYears(18) > DateTime.UtcNow) { ModelState.AddModelError("", "You must be 18 or older to register at Tradesatoshi.com"); return(View(model)); } var user = new User() { UserName = model.UserName, Email = model.EmailAddress, IsEnabled = true, IsTradeEnabled = true, IsWithdrawEnabled = true, IsTransferEnabled = true, RegisterDate = DateTime.UtcNow }; user.Profile = new UserProfile { Id = user.Id, BirthDate = model.BirthDate, FirstName = model.FirstName, LastName = model.LastName }; user.Settings = new UserSettings { Id = user.Id }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await UserManager.AddToRoleAsync(user.Id, SecurityRoles.Standard); string confirmationToken = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("RegisterConfirmEmail", "Account", new { username = user.UserName, confirmationToken = confirmationToken }, protocol: Request.Url.Scheme); if (await EmailService.Send(EmailType.Registration, user, Request.GetIPAddress(), new EmailParam("[CONFIRMLINK]", callbackUrl))) { return(ViewMessage(new ViewMessageModel(ViewMessageType.Info, "Confirmation Email Sent.", string.Format("An email has been sent to {0}, please click the activation link in the email to complete your registration process. <br /><br />", user.Email, callbackUrl)))); } ModelState.AddModelError("", "Failed to send registration confirmation email, if problem persists please contact Support."); return(ViewMessage(new ViewMessageModel(ViewMessageType.Danger, "Email Send Failed.", string.Format("Failed to send email to {0}, please contact <a href='/Support'>Support</a>. <br /><br />", user.Email, callbackUrl)))); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model, string returnUrl) { try { if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"])) { if (IsPhoneNumbersExits(model.PhoneNumber) && IsEmailExits(model.Email)) { if (model.Role == "0" && model.UserType == "professional") { ModelState.AddModelError("", "Select user type"); } if (ModelState.IsValid) { //SendOtp(model.PhoneNumber); // TempData["regmodel"] = model; // return RedirectToAction("ConfirmRegistration", "Account"); var user = new ApplicationUser { UserName = model.PhoneNumber, Email = model.Email, LastName = model.LastName, FirstName = model.FirstName, LastIpAddress = "192.168.225.1", IsEmailUnsubscribed = false, IsPhoneNumberUnsubscribed = true, LastLoginDateUtc = DateTime.UtcNow, CreatedOnUtc = DateTime.UtcNow, PhoneNumber = model.PhoneNumber, TwoFactorEnabled = true }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (model.UserType.ToLowerInvariant() == "professional") { await this.UserManager.AddToRoleAsync(user.Id, model.Role); var doctor = new Doctor { DoctorId = user.Id, RegistrationNumber = model.RegistrationNumber }; _doctorService.AddDoctor(doctor); } //gives content to sending thanks email await UserManager.SendEmailAsync(user.Id, "Thank you for registering at Doctor 365", "Thank you!!"); await SignInManager.SignInAsync(user, false, false); return(RedirectToAction("Index", "Home")); } string errorNotify = string.Empty; foreach (var item in result.Errors) { errorNotify += item + " ,"; } if (!string.IsNullOrWhiteSpace(errorNotify)) { ErrorNotification(errorNotify.TrimEnd(',')); } ViewBag.ReturnUrl = returnUrl; AddErrors(result); } } else { if (!IsPhoneNumbersExits(model.PhoneNumber)) { ErrorNotification("Phone number already exists."); } if (!IsEmailExits(model.Email)) { ErrorNotification("Email already exists."); } } } var capErr = ReCaptcha.GetLastErrors(this.HttpContext); if (capErr != null) { ErrorNotification("Oops!! Invalid Captcha."); } ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"]; model.UserRoleList = GetUserTypeList(); return(View(model)); } catch (Exception) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } }
public virtual async Task <ActionResult> SignUp(SignUpModel model) { var currentLanguage = WorkContext.CurrentLanguage; var countries = await _countriesService.GetAsSelectListAsync(); model.UserMustAcceptTerms = CurrentSettings.ShowAcceptTermsSignUp; model.CurrentLanguage = currentLanguage; model.CountriesList = countries; model.ExternalLoginProviders = _externalLoginProviderManager.GetAvailableLoginProvidersInfo(); if (CurrentSettings.UseGoogleRecaptchaForSignup && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts) { ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey; if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts) { if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey)) { IncreaseFailedAttempts(); ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext); return(View(model)); } } } if (!CurrentSettings.ShowAcceptTermsSignUp) { ModelState.Remove("AcceptTerms"); } if (!ModelState.IsValid) { IncreaseFailedAttempts(); return(View(model)); } var duplicatedEmail = await UserManager.FindByEmailAsync(model.Email); if (duplicatedEmail != null) { ModelState.AddModelError("Email", string.Format(_localizationService.GetResource("DuplicateEmail"), model.Email)); IncreaseFailedAttempts(); return(View(model)); } var user = new TblUsers() { UserName = model.Email, Email = model.Email, RegisterDate = DateTime.Now, FirstName = model.FName, LastName = model.LName, UserCountryId = model.Country, }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { EventPublisher.Publish(new UserSignupEvent(user)); var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); if (CurrentSettings.ConfirmUserEmailAddress) { var callbackUrl = Url.Action("ConfirmEmail", "User", new { userId = user.Id, code = code }, Request.Url.Scheme); await _emailService.SendEmailFromTemplateAsync("ConfirmEmail", _localizationService.GetResource("ConfirmAccount"), model.Email, new { Url = callbackUrl, UserFullName = user.FirstName + " " + user.LastName }); return(View("DisplayEmailConfirm")); } var confirmEmailResult = await UserManager.ConfirmEmailAsync(user.Id, code); return(View(confirmEmailResult.Succeeded ? "RegistrationCompleted" : "ErrorMessage")); } foreach (var error in result.Errors) { ModelState.AddModelError("", error); } IncreaseFailedAttempts(); return(View(model)); }
public static void RegisterCaptcha(string key, string secret) { ReCaptcha.Configure(key, secret); }
public virtual async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationModel model) { if (User.Identity.IsAuthenticated) { return(RedirectToLocal(model.ReturnUrl)); } var currentLanguage = WorkContext.CurrentLanguage; var countries = await _countriesService.GetAsSelectListAsync(); model.UserMustAcceptTerms = CurrentSettings.ShowAcceptTermsSignUp; model.CurrentLanguage = currentLanguage; model.CountriesList = countries; if (CurrentSettings.UseGoogleRecaptchaForSignup && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts) { ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey; if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts) { if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey)) { IncreaseFailedAttempts(); ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext); return(View(model)); } } } if (!CurrentSettings.ShowAcceptTermsSignUp) { ModelState.Remove("AcceptTerms"); } if (!ModelState.IsValid) { IncreaseFailedAttempts(); return(View(model)); } var duplicatedEmail = await UserManager.FindByEmailAsync(model.Email); if (duplicatedEmail != null) { ModelState.AddModelError("Email", string.Format(_localizationService.GetResource("DuplicateEmail"), model.Email)); IncreaseFailedAttempts(); return(View(model)); } // Get the information about the user from the external login provider var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return(View("Error")); } var user = new TblUsers() { UserName = loginInfo.Email, Email = loginInfo.Email, RegisterDate = DateTime.Now, FirstName = model.FName, LastName = model.LName, UserCountryId = model.Country, EmailConfirmed = true, Avatar = (await DownloadUserAvatar(model.Avatar)).SaveToAppData("socialAvatar.png") }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { EventPublisher.Publish(new UserSignupEvent(user)); result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : true, rememberBrowser : false); EventPublisher.Publish(new UserLoggedinEvent(user)); return(RedirectToLocal(model.ReturnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError("", error); } IncreaseFailedAttempts(); return(View(model)); }
public void WrongSiteKeyArgumentException() { Assert.Throws <ArgumentNullException>(() => ReCaptcha.Configure("", "something")); }
public virtual async Task <ActionResult> Login(LoginModel model) { var currentLanguage = WorkContext.CurrentLanguage; model.CurrentLanguage = currentLanguage; model.ExternalLoginProviders = _externalLoginProviderManager.GetAvailableLoginProvidersInfo(); if (CurrentSettings.UseGoogleRecaptchaForLogin && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts) { ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey; if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts) { if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey)) { IncreaseFailedAttempts(); ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext); return(View(model)); } } } if (!ModelState.IsValid) { IncreaseFailedAttempts(); return(View(model)); } var user = UserManager.FindByEmail(model.Email); if (CurrentSettings.ConfirmUserEmailAddress) { if (user != null && !UserManager.IsEmailConfirmed(user.Id)) { var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "User", new { userId = user.Id, code = code }, Request.Url.Scheme); await _emailService.SendEmailFromTemplateAsync("ConfirmEmail", _localizationService.GetResource("ConfirmAccount"), model.Email, new { Url = callbackUrl, UserFullName = user.FirstName + " " + user.LastName }); return(View("DisplayEmailConfirm")); } } var signIn = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, CurrentSettings.UserLockoutEnabled); switch (signIn) { case SignInStatus.Success: EventPublisher.Publish(new UserLoggedinEvent(user)); return(RedirectToLocal(model.ReturnUrl)); case SignInStatus.LockedOut: IncreaseFailedAttempts(); return(View("Lockout")); default: IncreaseFailedAttempts(); ModelState.AddModelError("", _localizationService.GetResource("InvalidLogin")); return(View(model)); } }
public void ResetTest() { ReCaptcha.ResetConfiguration(); }
public ActionResult Register(RegisterUserViewModel registerUser) { var recaptcha = new ReCaptcha(); var responseFromServer = recaptcha.OnActionExecuting(); if (responseFromServer.StartsWith("true", StringComparison.Ordinal)) { if (registerUser != null && ModelState.IsValid) { var userByUsername = DatabaseContext.RegisteredUsers.Find(new BsonDocument { { "Account.UserName", registerUser.Account.UserName } }).ToList(); var userByEmail = DatabaseContext.RegisteredUsers.Find(new BsonDocument { { "Account.Email", registerUser.Account.Email } }).ToList(); if (userByUsername.Count == 0) { if (userByEmail.Count == 0) { var passwordEncryption = new PasswordHashAndSalt(); registerUser.Id = Guid.NewGuid().ToString(); registerUser.Account.Password = passwordEncryption.getHashedPassword(registerUser.Account.Password); registerUser.Account.ConfirmPassword = passwordEncryption.getHashedPassword(registerUser.Account.ConfirmPassword); registerUser.Account.ImageId = "586a7d67cf43d7340cb54670"; var tradingDetails = new LetsTradingDetails { Id = registerUser.Id, Credit = 100 }; DatabaseContext.RegisteredUsers.InsertOne(registerUser); DatabaseContext.LetsTradingDetails.InsertOne(tradingDetails); using (var mail = new MailMessage()) { mail.To.Add(registerUser.Account.Email); mail.Subject = "Welcome to Royal Holloway LETS"; mail.Body = "<p>Hello " + registerUser.About.FirstName + ",</p><h3>Thanks for joining Royal Holloway LETS</h3><p>Please find your account details below</p><p>Title : <b>" + registerUser.About.Title + "</b></p><p>First Name : <b>" + registerUser.About.FirstName + "</b></p><p>Last Name : <b>" + registerUser.About.LastName + "</b></p><p>Gender : <b>" + registerUser.About.Gender + "</b></p><p>User Name : <b>" + registerUser.Account.UserName + "</b></p><p>Kind Regards,<br/>Royal Holloway LETS</p>"; SendEmail(mail); TempData.Add("Registered", "You have successfully signed up for Royal Holloway LETS, We have also sent you can email with your account details for your future reference."); } return(RedirectToAction("Login")); } else { registerUser.Account.Password = null; registerUser.Account.ConfirmPassword = null; ModelState.AddModelError("Account.Email", "Sorry, The following email already exists in our system."); return(View(registerUser)); } } else { registerUser.Account.Password = null; registerUser.Account.ConfirmPassword = null; ModelState.AddModelError("Account.UserName", "Sorry, This username is not available."); if (userByEmail.Count > 0) { ModelState.AddModelError("Account.Email", "Sorry, The following email already exists in our system."); } return(View(registerUser)); } } } else { registerUser.Account.Password = null; registerUser.Account.ConfirmPassword = null; ModelState.AddModelError("ReCaptcha", "Incorrect CAPTCHA entered."); return(View(registerUser)); } return(View()); }
public void AssertTestWillConectAndFailInvalidUserAnswerWithProxy() { ReCaptcha.Configure(SiteKey, SecretKey); Assert.Throws <ReCaptchaException>(() => ReCaptcha.ValidateCaptcha("resposta-fajuta", new WebProxy(TestProxyIp, PortProxy))); }
public async Task <ActionResult> Register(RegisterViewModel model, string message) { if (ModelState.IsValid) { var encodedResponse = Request.Form["g-Recaptcha-Response"]; var isCaptchaValid = ReCaptcha.Validate(encodedResponse); if (isCaptchaValid) { if ((!_context.Users.Any(x => x.EmployeeId == model.EmployeeId)) && (!_context.Users.Any(x => x.UserName == model.UserName)) && (!_context.Users.Any(x => x.Email == model.Email))) { var user = new ApplicationUser { UserName = model.UserName }; user.Email = model.Email; user.EmployeeId = model.EmployeeId; user.FirstName = model.FirstName; user.LastName = model.LastName; user.Department = model.Department; user.PhoneNumber = model.PhoneNumber; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await this.UserManager.AddToRoleAsync(user.Id, model.Name); string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Account confirmation"); await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); if (User.IsInRole("Administrators")) { return(RedirectToAction("Index", "User")); } else { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return(RedirectToAction("UserLogin", "Account")); } } AddErrors(result); } else { if (User.IsInRole("Administrators")) { return(RedirectToAction("Index", "User", new { message = "User already exists" })); } else { return(RedirectToAction("Register", "Account", new { message = "User already exists" })); } } } else { if (!User.IsInRole("Administrators")) { ViewBag.Name = new SelectList(_context.Roles.Where(x => x.Name == "Registered Users").ToList(), "Name", "Name"); } else { ViewBag.Name = new SelectList(_context.Roles.ToList(), "Name", "Name"); } ViewBag.Message = "Human verification is required."; return(View(model)); } } if (!User.IsInRole("Administrators")) { ViewBag.Name = new SelectList(_context.Roles.Where(x => x.Name == "Registered Users").ToList(), "Name", "Name"); } else { ViewBag.Name = new SelectList(_context.Roles.ToList(), "Name", "Name"); } // If we got this far, something failed, redisplay form return(View(model)); }