// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { InitializeDatabase(app); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseAuthentication(); app.UseHttpsRedirection(); app.UseRouting(); app.UseStaticFiles(); app.UseEndpoints(endpoints => { endpoints.MapHub <InterrogateHub>("/interrogate"); endpoints.MapRazorPages(); }); app.UseCookiePolicy(); WebHelper.Configure(app.ApplicationServices.GetRequiredService <IHttpContextAccessor>()); ReCaptchaHelper.Configure(app.ApplicationServices.GetRequiredService <IConfiguration>()); }
public ActionResult SubmitLogin(LoginPageViewModel currentPage) { Response.Cache.SetCacheability(HttpCacheability.NoCache); if (ModelState.IsValid) { if (!string.IsNullOrWhiteSpace(currentPage.Username) && !string.IsNullOrWhiteSpace(currentPage.Password)) { //prevent brute force first if (ReCaptchaHelper.Validate(Request.Form["g-Recaptcha-Response"])) { //yes this is depreciated, but there are no decent alternatives for this simple use-case. //please make one. if (FormsAuthentication.Authenticate(currentPage.Username, currentPage.Password)) { FormsAuthentication.RedirectFromLoginPage(currentPage.Username, currentPage.RememberMe); } } else { ModelState.AddModelError("Login", "Beep Boop - Robot test failed."); } } } //forget the entered password on retry currentPage.Password = string.Empty; //model not valid return(View("Login", currentPage)); }
/** * Set user phone number. */ private async Task <APIGatewayProxyResponse> ResetUserPassword(IDataStores dataStores, IDictionary <string, string> requestHeaders, JObject requestBody) { Debug.Untested(); Debug.AssertValid(dataStores); Debug.AssertValid(requestHeaders); Debug.AssertValidOrNull(requestBody); try { // Log call LoggingHelper.LogMessage($"UserIdentityService::ResetUserPassword()"); // Get the NoSQL DB client AmazonDynamoDBClient dbClient = (AmazonDynamoDBClient)dataStores.GetNoSQLDataStore().GetDBClient(); Debug.AssertValid(dbClient); // Check inputs ResetUserPasswordRequest resetUserPasswordRequest = UserIdentityService_ResetUserPassword_LogicLayer.CheckValidResetUserPasswordRequest(requestBody); Debug.AssertValid(resetUserPasswordRequest); // Check reCaptcha ReCaptchaHelper.CheckReCaptchaToken(resetUserPasswordRequest.reCaptcha); // Perform logic await UserIdentityService_ResetUserPassword_LogicLayer.ResetUserPassword(dbClient, resetUserPasswordRequest); // Respond return(new APIGatewayProxyResponse { StatusCode = APIHelper.STATUS_CODE_NO_CONTENT }); } catch (Exception exception) { Debug.Tested(); if ((exception.Message == SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS) || (exception.Message == IdentityServiceLogicLayer.ERROR_EMAIL_NOT_VERIFIED) || (exception.Message == ReCaptchaHelper.ERROR_INVALID_RECAPTCHA_TOKEN)) { Debug.Tested(); // Note tht no error code is returned for security reasons. //??--return StatusCode(APIHelper.STATUS_CODE_FORBIDDEN); return(new APIGatewayProxyResponse { StatusCode = APIHelper.STATUS_CODE_FORBIDDEN }); } else { Debug.Untested(); return(APIHelper.ResponseFromException(exception)); } } }
public async Task <ActionResult> Register(RegisterViewModel model, FormCollection form) { if (string.IsNullOrWhiteSpace(form["g-recaptcha-response"])) { } ReCaptchaResponse reCaptchaResponse = ReCaptchaHelper.VerifyCaptcha("6LdWMlMUAAAAAEFkcpAZd2XCd5vFvyjaR0PgK_Xu", form["g-recaptcha-response"]); if (!reCaptchaResponse.success) { //Throw error as required //You can also log errors returned from google in reCaptchaResponse.error_codes ModelState.AddModelError("RecaptchaERR", "Mã xác thực captcha không đúng."); return(View(model)); } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email , Email = model.Email , CreatedDate = DateTime.Now , FullName = model.FullName , Address = model.Address , Gender = model.Gender , BirthDate = model.BirthDate }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // 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)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { InitializeDatabase(app); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseAuthentication(); app.UseHttpsRedirection(); app.UseSignalR(route => { route.MapHub <InterrogateHub>("/interrogate"); }); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { var path = ctx.File.PhysicalPath; if (path.EndsWith(".css") || path.EndsWith(".js") || path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png") || path.EndsWith(".svg")) { var maxAge = new TimeSpan(7, 0, 0, 0); ctx.Context.Response.Headers.Append("Cache-Control", "max-age=" + maxAge.TotalSeconds.ToString("0")); } } }); app.UseCookiePolicy(); app.UseMvc(); WebHelper.Configure(app.ApplicationServices.GetRequiredService <IHttpContextAccessor>()); ReCaptchaHelper.Configure(app.ApplicationServices.GetRequiredService <IConfiguration>()); }
protected void Application_Start() { ReCaptchaHelper.Set(); AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); }
public IActionResult OnPost() { var resultLink = _repository.Single(LinkSpecification.ByUrl(ShortcutLink)); if (resultLink == null) { return(NotFound()); } var resultTopic = _repository.SingleInclude(BaseSpecification <Topic> .ById(resultLink.TopicId), new List <ISpecification <Topic> > { TopicSpecification.IncludeQuestions() }); if (resultTopic == null) { return(NotFound()); } if (resultTopic.PreventNSFW) { if (IsNsfw(Question.Content)) { ModelState.AddModelError("Question.Content", "Question contains word/s that are considered as NSFW"); } } if (resultTopic.PreventSpam) { if (!ReCaptchaHelper.ValidateRecaptcha(Request.Form["g-recaptcha-response"])) { ModelState.AddModelError("Question.Content", "Invalid ReCaptcha"); } } switch (resultTopic.DuplicationCheck) { case DuplicationCheck.IpAddress: { if (IpAddressExists(WebHelper.GetRemoteIP, resultTopic.Id)) { ModelState.AddModelError("Question.Content", "You have already asked a question on this poll"); break; } else if (ModelState.IsValid) { AddIpAddress(resultTopic.Id); } break; } case DuplicationCheck.BrowserCookie: { const string cookieKey = "PID"; if (CookieExists(cookieKey, ShortcutLink)) { ModelState.AddModelError("Question.Content", "You have already asked a question on this poll"); break; } else if (ModelState.IsValid) { WebHelper.SetCookie(cookieKey, ShortcutLink, null); } break; } case DuplicationCheck.None: break; default: _logger.LogError($"Unkown duplication check case {resultTopic.DuplicationCheck}."); throw new InvalidEnumArgumentException("Unrecognized case value."); } if (!ModelState.IsValid) { return(Page()); } resultTopic.Questions.Add(Question); _repository.Update(resultTopic); InterrogateClient.UpdateList(ShortcutLink, Question); InterrogateClient.UpdateQuestionCount(ShortcutLink, resultTopic.Questions.Count); return(RedirectToPage("Result")); }