"""Slowing down password guessing at the login endpoint.

There was nothing here before: /api/auth/login/ answered as fast as the server
could, forever, so a weak password was a matter of waiting rather than luck.

Two limits, because one is not enough:

  * per username — the one that matters. It cannot be side-stepped by changing
    address, so an account under attack stays protected however many machines
    are pointed at it.

  * per address — a coarse backstop. It is generous on purpose: a whole office
    behind one connection shares an address, and locking out a real team to
    inconvenience an attacker is a bad trade. It also reads X-Forwarded-For,
    which a caller can lie about, so it is a speed bump and not the defence.

A throttled request is answered with 429 and a Retry-After, the same as any
other rate limit, so an honest user with a forgotten password sees a wait
rather than a mystery.
"""

from rest_framework.throttling import SimpleRateThrottle


def _client_ip(request):
    """The caller's address as the proxy reports it.

    LiteSpeed and Cloudflare both put the real address first in
    X-Forwarded-For and their own last. Without this every request looks like
    it came from the proxy, and one limit would be shared by everybody.
    """
    forwarded = request.META.get('HTTP_X_FORWARDED_FOR', '')
    if forwarded:
        return forwarded.split(',')[0].strip()[:45]
    return request.META.get('REMOTE_ADDR', '')


class LoginUsernameThrottle(SimpleRateThrottle):
    """Per account, per minute. The limit an attacker cannot avoid."""

    scope = 'login_user'

    def get_cache_key(self, request, view):
        username = (request.data.get('username') or '').strip().lower()
        if not username:
            return None  # nothing to count against; the view rejects it anyway
        return self.cache_format % {'scope': self.scope, 'ident': username}


class LoginUsernameDayThrottle(LoginUsernameThrottle):
    """Per account, per hour. Stops a slow, patient grind at one account."""

    scope = 'login_user_hour'


class LoginIPThrottle(SimpleRateThrottle):
    """Per address, deliberately generous — see the note above."""

    scope = 'login_ip'

    def get_cache_key(self, request, view):
        ident = _client_ip(request)
        return self.cache_format % {'scope': self.scope, 'ident': ident} if ident else None
