Beispiel #1
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            if (!await _recaptchaService.VerifyAsync(Request.Form["g-recaptcha-response"]))
            {
                ModelState.AddModelError(string.Empty, "Invalid Recaptcha"); return(Page());
            }

            var user = await _userManager.FindByEmailAsync(Input.Email);

            if (user == null)
            {
                return(RedirectToPage("./ResetPasswordConfirmation"));
            }

            var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password);

            if (result.Succeeded)
            {
                return(RedirectToPage("./ResetPasswordConfirmation"));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return(Page());
        }
        public async Task <IActionResult> Login([FromBody] Credentials credentials, CancellationToken cancellationToken)
        {
            var response = await _recaptchaService.VerifyAsync(credentials.RecaptchaToken, cancellationToken : cancellationToken);

            if (!response.Success)
            {
                _logger.LogError($"Recaptcha error: {JsonConvert.SerializeObject(response.ErrorCodes)}");
                return(BadRequest());
            }

            // Process login

            return(Ok());
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            if (!await _recaptchaService.VerifyAsync(Request.Form["g-recaptcha-response"]))
            {
                ModelState.AddModelError(string.Empty, "Invalid Recaptcha"); return(Page());
            }

            var user = await _userManager.FindByEmailAsync(Input.Email);

            if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
            {
                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
            var callbackUrl = Url.Page(
                "/ResetPassword",
                pageHandler: null,
                values: new { code },
                protocol: Request.Scheme);

            await _emailService.SendAsync(Input.Email, "Reset Password",
                                          $@"
Hello {HtmlEncoder.Default.Encode(user.UserName)}!
<br/>
<br/>
Please reset your password by
<a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.
<br/>
<br/>
Best Regards,
<br/>
ImaginaryCTF's Team
");

            return(RedirectToPage("./ForgotPasswordConfirmation"));
        }
        public async Task <ActionResult> Store([FromBody] MessageEditForm form)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var  ip             = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
            bool recaptchaValid = await _recaptchaService.VerifyAsync(form.Token, ip);

            if (!recaptchaValid)
            {
                ModelState.AddModelError("recaptcha", "驗證失敗");
                return(BadRequest(ModelState));
            }

            var message = form.Message.MapEntity(_mapper, CurrentUserId);

            message = await _messagesService.CreateAsync(message);

            return(Ok(message.MapViewModel(_mapper)));
        }
        public async Task Invoke(HttpContext httpContext)
        {
            var mode = _options.CurrentValue.InvalidRecaptchaResponseMode;

            if (httpContext.Request.Headers.All(x => !x.Key.Equals(Constants.ReCaptchaHeader, StringComparison.InvariantCultureIgnoreCase)))
            {
                await RejectRequestAsync(httpContext, mode);
            }

            var reCaptchaResponse = httpContext.Request.Headers.FirstOrDefault(x =>
                                                                               x.Key.Equals(Constants.ReCaptchaHeader, StringComparison.InvariantCultureIgnoreCase)).Value;

            if (string.IsNullOrEmpty(reCaptchaResponse))
            {
                await RejectRequestAsync(httpContext, mode);
            }

            var recaptchaVerificationResult = await _recaptchaService.VerifyAsync(reCaptchaResponse, CancellationToken.None);

            if (!recaptchaVerificationResult.Success)
            {
                const string msg = "Recaptcha verification failed";
                switch (mode)
                {
                case InvalidRecaptchaResponseMode.ThrowRecaptchaException:
                    throw new RecaptchaVerificationFailureException(msg);

                case InvalidRecaptchaResponseMode.ReturnBadRequest:
                    httpContext.Response.StatusCode = 400;
                    await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { error = msg }));

                    return;
                }
            }

            await _next.Invoke(httpContext);
        }
Beispiel #6
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var mode = _options.CurrentValue.InvalidRecaptchaResponseMode;

            if (context.HttpContext.Request.Headers.All(x => !x.Key.Equals(Constants.ReCaptchaHeader, StringComparison.InvariantCultureIgnoreCase)))
            {
                RejectRequest(context, mode);
                return;
            }

            var reCaptchaResponse = context.HttpContext.Request.Headers.FirstOrDefault(x =>
                                                                                       x.Key.Equals(Constants.ReCaptchaHeader, StringComparison.InvariantCultureIgnoreCase)).Value;

            if (string.IsNullOrEmpty(reCaptchaResponse))
            {
                RejectRequest(context, mode);
                return;
            }

            var recaptchaVerificationResult = await _recaptchaService.VerifyAsync(reCaptchaResponse, CancellationToken.None);

            if (!recaptchaVerificationResult.Success)
            {
                const string msg = "Recaptcha verification failed";
                switch (mode)
                {
                case InvalidRecaptchaResponseMode.ThrowRecaptchaException:
                    throw new RecaptchaVerificationFailureException(msg);

                case InvalidRecaptchaResponseMode.ReturnBadRequest:
                    context.Result = new BadRequestObjectResult(new { error = msg });
                    break;
                }
            }

            await base.OnActionExecutionAsync(context, next);
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            string reCaptchaResponse = Request.Form["g-recaptcha-response"];

            returnUrl ??= Url.Content("~/");

            if (!await _recaptchaService.VerifyAsync(reCaptchaResponse))
            {
                ModelState.AddModelError(string.Empty, "Invalid Recaptcha");
                return(Page());
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var existentUser = await _userManager.FindByEmailAsync(Input.Email);

            if (existentUser != null && !existentUser.EmailConfirmed)
            {
                await _userManager.DeleteAsync(existentUser);
            }

            var user = new ApplicationUser {
                UserName = Input.Username, Email = Input.Email, User = new User(), ApiKey = RandomHelper.GenerateRandomString()
            };
            var result = await _userManager.CreateAsync(user, Input.Password);

            if (result.Succeeded)
            {
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/ConfirmEmail",
                    pageHandler: null,
                    values: new { area = "Account", userId = user.Id, code = code, returnUrl = returnUrl },
                    protocol: Request.Scheme);

                await _emailService.SendAsync(Input.Email, "ImaginaryCTF - Confirm your email",
                                              $@"
Hello {HtmlEncoder.Default.Encode(user.UserName)}!
<br/>
<br/>
Please confirm your account by
<a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.
<br/>
<br/>
Best Regards,
<br/>
ImaginaryCTF's Team
");

                return(RedirectToPage("/RegisterConfirmation", new { area = "Account" }));
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return(Page());
        }