Beispiel #1
0
def is_ratelimited(request,
                   name,
                   rate,
                   method=["POST"],
                   skip_if=lambda r: False):
    """
    Reimplement ``ratelimit.helpers.is_ratelimited``, with sumo-specific details:

    * Always check for the bypass rate limit permission.
    * Log times when users are rate limited.
    * Always uses ``user_or_ip`` for the rate limit key.
    """
    if skip_if(request) or request.user.has_perm("sumo.bypass_ratelimit"):
        request.limited = False
    else:
        # TODO: make sure 'group' value below is sufficient
        # TODO: make sure 'user_or_ip' is a valid replacement for
        # old/deleted custom user_or_ip method
        rl_is_ratelimited(request,
                          increment=True,
                          group="sumo.utils.is_ratelimited",
                          rate=rate,
                          key="user_or_ip")
        if request.limited:
            if hasattr(request, "user") and request.user.is_authenticated:
                key = 'user "{}"'.format(request.user.username)
            else:
                ip = request.META.get("HTTP_X_CLUSTER_CLIENT_IP",
                                      request.META["REMOTE_ADDR"])
                key = "anonymous user ({})".format(ip)
            Record.objects.info("sumo.ratelimit",
                                "{key} hit the rate limit for {name}",
                                key=key,
                                name=name)
    return request.limited
Beispiel #2
0
def is_ratelimited(request, name, rate, method=['POST'], skip_if=lambda r: False):
    """
    Reimplement ``ratelimit.helpers.is_ratelimited``, with sumo-specific details:

    * Always check for the bypass rate limit permission.
    * Log times when users are rate limited.
    * Always uses ``user_or_ip`` for the rate limit key.
    """
    if skip_if(request) or request.user.has_perm('sumo.bypass_ratelimit'):
        request.limited = False
    else:
        # TODO: make sure 'group' value below is sufficient
        # TODO: make sure 'user_or_ip' is a valid replacement for
        # old/deleted custom user_or_ip method
        rl_is_ratelimited(request, increment=True, group='sumo.utils.is_ratelimited',
                          rate=rate, key='user_or_ip')
        if request.limited:
            if hasattr(request, 'user') and request.user.is_authenticated():
                key = 'user "{}"'.format(request.user.username)
            else:
                ip = request.META.get('HTTP_X_CLUSTER_CLIENT_IP', request.META['REMOTE_ADDR'])
                key = 'anonymous user ({})'.format(ip)
            Record.objects.info('sumo.ratelimit', '{key} hit the rate limit for {name}',
                                key=key, name=name)
    return request.limited