public JsonResult AddComment(Comment comment) { bool isAdd = false; string message = "Упс, щось пішло не так. Спробуйте пізніше..."; bool captcha = ReCaptcha.ValidateCaptcha(Request["g-recaptcha-response"]); if (comment.ProductId == null || String.IsNullOrWhiteSpace(comment.Author) || String.IsNullOrWhiteSpace(comment.Text) || !captcha) { message = "Заповніть усі поля!"; } else { var ukraineTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time")); comment.Time = ukraineTime.ToString("HH:mm MM/dd/yyyy"); db.Comments.Add(comment); db.SaveChanges(); isAdd = true; } return(Json(new { IsAdd = isAdd, Message = message, JsonRequestBehavior.AllowGet })); }
public JsonResult SendFeedback(string userName, string userEmail, string userMessage) { bool isSend = false; string message = "Упс, щось пішло не так. Спробуйте пізніше..."; bool captcha = ReCaptcha.ValidateCaptcha(Request["g-recaptcha-response"]); if (String.IsNullOrWhiteSpace(userName) || String.IsNullOrWhiteSpace(userEmail) || String.IsNullOrWhiteSpace(userMessage) || !captcha) { message = "Заповніть усі поля!"; } else { try { EmailService.SendEmail("*****@*****.**", "Нове повідомлення", $"Надійшло нове повідомлення через форму зворотнього зв'язку.\n\nІм'я: {userName}\nE-mail: {userEmail}\nПовідомлення: {userMessage}"); isSend = true; message = "Ваше повідомлення успішно відправлено!"; } catch (Exception ex) { message = $"Помилка: {ex.Message}"; } } return(Json(new { IsSend = isSend, Message = message, JsonRequestBehavior.AllowGet })); }
public async Task <ActionResult> Register(RegisterViewModel model) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { // A bot, not validated ! return(RedirectToAction("Unauthorized", "Account")); } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, 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 http://go.microsoft.com/fwlink/?LinkID=320771 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 async Task <ActionResult> CreateRating( [Bind( Include = "RatingId,RatingName,LateFees,LandLordNotice,LandLordResponse,ContactPhoneNumer,RecommendLandLord,RentIncrease,WrittenLease,LandLordRating,RateAnonymously,User_Id,LandLordId,RatingDescription,IsApproved,IsDeclined" )] Rating rating) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { // A bot, not validated ! return(RedirectToAction("Unauthorized", "Account")); } rating.User = GetCurrentUser(); if (ModelState.IsValid) { db.Ratings.Add(rating); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(rating)); }
public async Task <ActionResult> SubmitPublicRecord([Bind(Include = "RecordType,CriminalType,CivilType,DomesticType,CaseName,CaseNumber,DateFiled,CaseURL,LandLord_LandLordId,PlaintiffOrDefendant")] PublicRecord record) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { // A bot, not validated ! return(RedirectToAction("Unauthorized", "Account")); } if (IsAdminUser()) { record.IsApproved = true; } var landlordid = TempData["landlordid"]; var landlord = db.LandLords.Find(landlordid); record.LandLord = landlord; if (ModelState.IsValid) { db.PublicRecords.Add(record); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } IEnumerable <ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors); return(View(record)); }
public void InvalidSecretKeyException() { Assert.Throws <ReCaptchaException>(() => { ReCaptcha.Configure("something", "Invalid-Secret-Key"); bool answer = ReCaptcha.ValidateCaptcha("resposta-fajuta"); }); }
public ActionResult Signup(UserViewModel model, bool?isCaptchaValid) { SiteSettings siteSettings = SettingsService.GetSiteSettings(); if (Context.IsLoggedIn || !siteSettings.AllowUserSignup || ApplicationSettings.UseWindowsAuthentication) { return(RedirectToAction("Index", "Home")); } if (ModelState.IsValid) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { // Invalid recaptcha ModelState.AddModelError("General", SiteStrings.Signup_Error_Recaptcha); } else { // Everything is valid. try { try { string key = UserService.Signup(model, null); if (string.IsNullOrEmpty(key)) { ModelState.AddModelError("General", SiteStrings.Signup_Error_General); } else { // Send the confirm email _signupEmail.Send(model); if (UserService.Authenticate(model.NewEmail, model.Password)) { Context.CurrentUser = UserService.GetLoggedInUserName(HttpContext); } return(View("SignupComplete", model)); } } catch (SecurityException e) { ModelState.AddModelError("General", e.Message); } } catch (SecurityException e) { ModelState.AddModelError("General", e.Message); } } } return(View()); }
public ActionResult Public(ContactViewModel model) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (validCaptcha) { try { Contact contact = new Contact() { Address = model.Address, Content = model.Content, Email = model.Email, Name = model.Name, Title = model.Title }; var response = _contactLogic.Create(contact); if (response.IsError == true) { foreach (var item in response.ErrorCodes) { ModelState.AddModelError(string.Empty, item); } return(View(model)); } else { var msg = new MailMessage(); msg.To.Add(new MailAddress(ConfigurationManager.AppSettings["AdminEmail"])); msg.Subject = "E-SINERGI Contact - " + model.Title; msg.Body = "Dari: " + model.Email + ", Isi: " + model.Content; msg.From = new MailAddress("*****@*****.**"); using (var client = new SmtpClient() { Host = "relay-hosting.secureserver.net", Port = 25, EnableSsl = false, UseDefaultCredentials = false }) { client.Send(msg); } } return(RedirectToAction("ThankYouPage")); } catch (Exception ex) { return(View()); } } else { ModelState.AddModelError(string.Empty, "Invalid Captcha"); return(View()); } }
public static bool Validate() { try { #if !DEBUG return(ReCaptcha.ValidateCaptcha(HttpContext.Current.Request.Params["g-recaptcha-response"])); #else return(true); #endif } catch { } return(false); }
public ActionResult HandleBookingSubmit(BookingViewModel model) { if (!ModelState.IsValid) { return(CurrentUmbracoPage()); } ReCaptcha.CaptchaResponse response = new ReCaptcha.CaptchaResponse(); if (ConfigurationManager.AppSettings["Development"] != "True") { response = ReCaptcha.ValidateCaptcha(Request["g-recaptcha-response"].ToString()); } //Validate reCaptcha if (response.Success == "True" || ConfigurationManager.AppSettings["Development"] == "True") { try { //Insert Request into Db Booking bookingDetails = PopulateBooking(model); var db = UmbracoContext.Application.DatabaseContext.Database; var res = db.Insert(bookingDetails); //Send Email and Redirect to Thank You page. string link = "http://" + Request.Url.Host + "/umbraco#/BookingSection/BookingSectionTree/edit/" + res; EmailHelper email = new EmailHelper(); email.SendBookingInternalEmail(model, link); //IPublishedContent formNode = Umbraco.TypedContent(UmbracoContext.PageId.Value); //email.SendCustomerFacingEmail( // bookingDetails.Email, // formNode.GetProperty("emailSubject").Value.ToString(), // formNode.GetProperty("emailBody").Value.ToString().Replace("src=\"/","src=\"http://" + Request.Url.Authority + "/") // ); return(this.Redirect("thank-you")); } catch (Exception ex) { LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "failed Submitting booking form", new Exception(ex.Message)); TempData["Status"] = "Failed submitting event booking"; return(CurrentUmbracoPage()); } } else { TempData["reCapthcaMessage"] = response.Message; return(CurrentUmbracoPage()); } }
public ActionResult Forma(string myinput1) { var r = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(r); if (validCaptcha) { return(Content($"Hi there HUMAN")); } else { return(Content($"ROBOT ALERT")); } }
public static bool ValidateCaptcha() { try { #if !DEBUG return(ReCaptcha.ValidateCaptcha(HttpContext.Current.Request.Params["g-recaptcha-response"])); #endif } catch (Exception ex) { // We don't return false here because we don't want to lock out users if there are issues with google and not the site Log.Exception("[ValidateCaptcha] Captcha Verification Failed", ex); } return(true); }
public async Task <ActionResult> FlagLandLord(Flag flag) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { // A bot, not validated ! return(RedirectToAction("Unauthorized", "Account")); } flag.ApplicationUser = GetCurrentUser(); db.Flags.Add(flag); await db.SaveChangesAsync(); return(RedirectToAction("FlagSubmitted", "LandLords", new { id = flag.FlaggedObjectId })); }
public async Task <ActionResult> Create( [Bind(Include = "LandLordId,FullName,PhoneNumber,City,State,IsDeclined,IsApproved,Description,ProfileImageUrl,LandLordOrTenant,IndividualOrCompany,OverallRating,IsApproved,IsClaimed,IsDeclined,IsClaimedDuringCreation,DeclinedReason,ZipCode,Latitude,Longitude")] LandLord landLord) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { // A bot, not validated ! return(RedirectToAction("Unauthorized", "Account")); } if (IsAdminUser()) { landLord.IsApproved = true; landLord.IsDeclined = false; } else { landLord.IsApproved = false; landLord.IsDeclined = false; } if (ModelState.IsValid) { var gls = new GoogleLocationService(); var latlong = gls.GetLatLongFromAddress(landLord.City + " " + landLord.ZipCode); landLord.Latitude = latlong.Latitude; landLord.Longitude = latlong.Longitude; db.LandLords.Add(landLord); await db.SaveChangesAsync(); if (landLord.IsClaimedDuringCreation) { landLord.IsClaimed = true; var user = GetCurrentUser(); if (user.ClaimedLandLordId != 0) { return(RedirectToAction("CannotClaim")); } user.ClaimedLandLordId = landLord.LandLordId; db.Entry(user).State = EntityState.Modified; await db.SaveChangesAsync(); } return(RedirectToAction("Index")); } return(View(landLord)); }
public ActionResult Contact(ContactViewModel vm) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { // A bot, not validated ! return(RedirectToAction("Unauthorized", "Account")); } if (ModelState.IsValid) { try { MailMessage msz = new MailMessage(); msz.From = new MailAddress(vm.Email); //Email which you are getting //from contact us page msz.To.Add("*****@*****.**"); //Where mail will be sent msz.Subject = vm.Subject; msz.Body = vm.Message; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.Credentials = new System.Net.NetworkCredential ("eriehackalerts", "Winter89!"); smtp.EnableSsl = true; smtp.Send(msz); ModelState.Clear(); ViewBag.Message = "Thank you for Contacting us "; } catch (Exception ex) { ModelState.Clear(); ViewBag.Message = $" An error occurred. Please try again! {ex.Message}"; } } IEnumerable <ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors); return(View()); }
private bool ValidateCaptchaCode(string userResponse, OAuthGrantResourceOwnerCredentialsContext context) { try { bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha || userResponse.IsNullOrWhiteSpace()) { // Bot Attack, non validated ! throw new ReCaptchaException(); } return(true); } catch { context.SetError("مجوز نامعتبر", "فیلد 'من ربات نیستم' صحیح نیست. لطفا مجددا تلاش کنید"); return(false); } }
public ActionResult TipMail(MailViewModel modelEmail) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (validCaptcha) { // Real User, validated ! SendTipMail.SendEmails(string.Empty, modelEmail.Reciever, string.Empty, modelEmail.Name, modelEmail.Message); return(View()); } else { // Not validated ! return(View()); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var data = await context.Request.ReadFormAsync(); string userResponse = data["recaptcha"]; try { bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha || userResponse.IsNullOrWhiteSpace()) { // Bot Attack, non validated ! throw new ReCaptchaException(); } } catch { context.SetError("مجوز نامعتبر", "فیلد 'من ربات نیستم' صحیح نیست. لطفا مجددا تلاش کنید"); return; } var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("مجوز نامعتبر", "نام کاربری یا رمز عبور اشتباه است"); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public async Task <IHttpActionResult> Register(RegisterBindingModel model) { try { bool validCaptcha = ReCaptcha.ValidateCaptcha(model.Recaptcha); if (!validCaptcha || model.Recaptcha.IsNullOrWhiteSpace()) { // Bot Attack, non validated ! throw new ReCaptchaException(); } } catch { ModelState.AddModelError("model.Recaptcha", "فیلد 'من ربات نیستم' صحیح نیست. لطفا مجددا تلاش کنید"); return(BadRequest(ModelState)); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, CreateDateTime = DateTime.Now }; var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext())); userManager.UserValidator = new UserValidationProvider <ApplicationUser>(userManager); IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return(GetErrorResult(result)); } return(Ok(result)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { string userResponse = Request["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (validCaptcha) { var user = new User { UserName = model.Username, Email = model.Email, Id = Guid.NewGuid().ToString() }; try { var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); await UserManager.AddToRoleAsync(user.Id, "User"); return(RedirectToAction("Default", "Home")); } AddErrors(result); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } } // If we got this far, something failed, redisplay form return(View(model)); }
public static void Validate() { if (SystemSettings.UseLoginCaptcha) { var userResponse = HttpContext.Current.Request.Params["g-recaptcha-response"]; var validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha) { HasError = true; ErrorMessage = WebResources.CaptchaFailed; } else { HasError = false; } } else { HasError = false; } }
public ActionResult SendContactMessage(ContactModel contactModel) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!ModelState.IsValid) { return(View("Contact")); } if (!validCaptcha) { ViewBag.CatchaError = "Captcha not provided"; return(View("Contact")); } string subject = $"{contactModel.Name} {contactModel.Email}"; string body = $@"Name : {contactModel.Name} <br/> Surname : {contactModel.Surname} <br/> Email : { contactModel.Email } <br/> Phone : {contactModel.PhoneNumber} <br/> Message : <br/> { contactModel.Message}"; //send email to admins var response = Utilities.EmailSender.SendEmail(System.Configuration.ConfigurationManager.AppSettings["appEmail"], subject, body); //send a copy to user var response2 = Utilities.EmailSender.SendEmail(contactModel.Email, subject, body); contactModel.Success = response && response2; // using the POST/REDIRECT/GET Pattern to prevent form resubmission // https://en.wikipedia.org/wiki/Post/Redirect/Get return(RedirectToAction("ThankYou")); }
private async Task <bool> ValidateRecaptch(OAuthGrantResourceOwnerCredentialsContext context) { var data = await context.Request.ReadFormAsync(); string userResponse = data["recaptcha"]; try { bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (!validCaptcha || userResponse.IsNullOrWhiteSpace()) { // Bot Attack, non validated ! throw new ReCaptchaException(); } return(true); } catch { context.SetError("مجوز نامعتبر", "فیلد 'من ربات نیستم' صحیح نیست. لطفا مجددا تلاش کنید"); return(false); } }
public JsonResult Login(Admin model) { bool isLogin = false; Admin admin = null; string message = "Упс, щось пішло не так. Спробуйте пізніше..."; bool captcha = ReCaptcha.ValidateCaptcha(Request["g-recaptcha-response"]); if (String.IsNullOrWhiteSpace(model.Login) || String.IsNullOrWhiteSpace(model.Password) || !captcha) { message = "Заповніть усі поля!"; } else { admin = db.Admins.FirstOrDefault(u => u.Login == model.Login); if (admin != null) { var verifyUserPass = SecurePasswordHasher.Verify(model.Password, admin.Password); if (verifyUserPass) { FormsAuthentication.SetAuthCookie(model.Login, true); isLogin = true; } else { message = "Невірно вказаний пароль"; } } else { message = "Користувача з таким логіном не існує"; } } return(Json(new { IsLogin = isLogin, Message = message, JsonRequestBehavior.AllowGet })); }
public void AssertTestWillConectAndFailInvalidUserAnswerWithProxy() { ReCaptcha.Configure(SiteKey, SecretKey); Assert.Throws <ReCaptchaException>(() => ReCaptcha.ValidateCaptcha("resposta-fajuta", new WebProxy(TestProxyIp, PortProxy))); }
public void AssertTestWillConectAndFailInvalidUserAnswer() { ReCaptcha.Configure(SiteKey, SecretKey); Assert.Throws <ReCaptchaException>(() => ReCaptcha.ValidateCaptcha("resposta-fajuta")); }
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()); }
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 ActionResult Index(HttpPostedFileBase file, HomeViewModel model) { string userResponse = HttpContext.Request.Params["g-recaptcha-response"]; bool validCaptcha = ReCaptcha.ValidateCaptcha(userResponse); if (validCaptcha) { try { Report report = new Report() { Name = model.Name, Address = model.Address, PhoneNumber = model.PhoneNumber, Description = model.Description, Origin = Constant.ReportOrigin.WEBSITE }; var response = _reportLogic.Create(report); if (response.IsError == true) { foreach (var item in response.ErrorCodes) { ModelState.AddModelError(string.Empty, item); } return(View(model)); } else { // if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var filePath = response.CreatedId.ToString() + "_" + fileName; var path = Path.Combine(Server.MapPath("~/Content/UploadReporter"), filePath); file.SaveAs(path); ReporterFile reporterFile = new ReporterFile(); reporterFile.FileName = fileName; reporterFile.ReportId = response.CreatedId; _reporterFileLogic.Create(reporterFile); } try { var msg = new MailMessage(); msg.To.Add(new MailAddress(ConfigurationManager.AppSettings["AdminEmail"])); msg.Subject = "LAPOR-BRANTAS New Report"; msg.Body = "Dari: " + model.PhoneNumber + ", Isi: " + model.Description; msg.From = new MailAddress("*****@*****.**"); using (var client = new SmtpClient() { Host = "relay-hosting.secureserver.net", Port = 25, EnableSsl = false, UseDefaultCredentials = false }) { client.Send(msg); } } catch (Exception ex) { } } return(RedirectToAction("SubmitLandingPage", new { id = response.CreatedId, name = model.Name })); } catch { return(RedirectToAction("Index")); } } else { ModelState.AddModelError(string.Empty, "Invalid Captcha"); HomeViewModel homeView = new HomeViewModel(); homeView.ReportList = new List <ReportViewModel>(); var reports = _reportLogic.GetAll(); foreach (var item in reports) { ReportViewModel report = new ReportViewModel() { Address = item.Address, Description = item.Description, Name = item.Name, Origin = item.Origin, CreatedDate = item.CreatedDate.ToString("dd-MMM-yyyy hh:mm"), Status = item.Status, Id = item.Id }; homeView.ReportList.Add(report); } return(View(homeView)); } }
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 })); }