Example #1
0
        /// <inheritdoc cref="ICaptcha.Create" />
        public void Create(HttpContext context)
        {
            var feature = GetCaptchaFeature(context);

            if (feature.HasCaptchaToken)
            {
                store.InvalidateCaptcha(context, feature.CaptchaToken);
            }

            var text    = textGenerator.Generate();
            var blob    = new BinaryBlob(256);
            var token   = new CaptchaToken(blob);
            var cookie  = options.Cookie.Build(context);
            var captcha = new GeneratedCaptcha(token, text, DateTime.UtcNow);

            store.SetCaptcha(context, captcha);

            context.Response.Cookies.Append(
                options.Cookie.Name,
                WebEncoders.Base64UrlEncode(token.Value.GetData()),
                cookie
                );

            logger.LogDebug($"New CAPTCHA was generated: {options.Cookie.Name}={blob.DebugString}");
        }
Example #2
0
        private async Task ImageContentAsync(HttpContext context, GeneratedCaptcha info)
        {
            var routeData     = context.GetRouteData() ?? new RouteData();
            var actionContext = new ActionContext(context, routeData, emptyActionDescriptor);
            var headers       = new RequestHeaders(context.Request.Headers);

            using (var stream = new MemoryStream())
            {
                var codec = GetImageCodec(options.Image.Format);

                if (false == CanClientAccept(headers.Accept, codec.MimeType))
                {
                    return;
                }

                using (var image = await generator.GenerateImageAsync(info.Captcha))
                {
                    var encoderContext = new GeneratedCaptchaImageContext(codec);
                    var args           = options.Image.EncoderParameters.Invoke(encoderContext);

                    image.Save(stream, codec, args);
                }

                var contentType = new MediaTypeHeaderValue(codec.MimeType, 1.0d);
                var result      = new FileContentResult(stream.ToArray(), contentType);

                await result.ExecuteResultAsync(actionContext);
            }
        }
Example #3
0
        public void SetCaptcha(HttpContext context, GeneratedCaptcha captcha)
        {
            if (null == context)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (null == captcha)
            {
                throw new ArgumentNullException(nameof(captcha));
            }

            var token = captcha.Token;

            cache[token.Value] = captcha;
        }
Example #4
0
        internal static bool NotExpired(GeneratedCaptcha captcha, TimeSpan timeout)
        {
            var duration = DateTime.UtcNow - captcha.CreatedAt;

            return(duration <= timeout);
        }