Ejemplo n.º 1
0
        private static TimeSpan CalculateExpirationTime(ThrottlingPeriod period)
        {
            switch (period)
            {
            case ThrottlingPeriod.Second:
                return(TimeSpan.FromSeconds(1));

            case ThrottlingPeriod.Minute:
                return(TimeSpan.FromMinutes(1));

            case ThrottlingPeriod.Hour:
                return(TimeSpan.FromHours(1));

            case ThrottlingPeriod.Day:
                return(TimeSpan.FromDays(1));

            default:
                throw new ArgumentException(period.ToString());
            }
        }
Ejemplo n.º 2
0
        private Response CheckThrottlingLimitHook(
            NancyContext context,
            ThrottlingProperties propertiesSet,
            ThrottlingPeriod period,
            int requestCountLimit,
            Func <NancyContext, bool> checkIf = null,
            Func <NancyContext, bool> skipIf  = null,
            params string[] requestKeys)
        {
            if (checkIf != null && !checkIf(context))
            {
                return(null);
            }

            if (skipIf != null && skipIf(context))
            {
                return(null);
            }

            var key            = BuildRequestKey(propertiesSet, period, context, requestKeys);
            var expirationTime = CalculateExpirationTime(period);

            var counterValue = IncrementCounter(key, expirationTime);

            if (IsLimitExceeded(requestCountLimit, counterValue))
            {
                if (IsNeedToLog(requestCountLimit, counterValue))
                {
                    logger.Error($"Flood detected ({counterValue} in {period.ToString()} allowed {requestCountLimit})" +
                                 $" on path: {context?.Request?.Path}" +
                                 $" ip: {context?.GetClientHost()}");
                }
                return(new Response
                {
                    StatusCode = HttpStatusCode.TooManyRequests
                });
            }

            return(null);
        }