File: ip.py

package info (click to toggle)
django-ipware 4.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 196 kB
  • sloc: python: 731; makefile: 6; sh: 3
file content (61 lines) | stat: -rw-r--r-- 2,065 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from . import utils as util
from . import defaults as defs


def get_client_ip(
    request,
    proxy_order='left-most',
    proxy_count=None,
    proxy_trusted_ips=None,
    request_header_order=None,
):
    client_ip = None
    routable = False

    if proxy_count is None:
        proxy_count = -1

    if proxy_trusted_ips is None:
        proxy_trusted_ips = []

    if request_header_order is None:
        request_header_order = defs.IPWARE_META_PRECEDENCE_ORDER

    for key in request_header_order:
        value = util.get_request_meta(request, key)
        if value:
            ips, ip_count = util.get_ips_from_string(value)

            if ip_count < 1:
                # we are expecting at least one IP address to process
                continue

            if proxy_count == 0 and ip_count > 1:
                # we are not expecting requests via any proxies
                continue

            if proxy_count > 0 and proxy_count != ip_count - 1:
                # we are expecting requests via `proxy_count` number of proxies
                continue

            if proxy_trusted_ips and ip_count < 2:
                # we are expecting requests via at least one trusted proxy
                continue

            if proxy_order == 'right-most' and ip_count > 1:
                # we are expecting requests via proxies to be custom as per `<proxy2>, <proxy1>, <client>`
                ips.reverse()

            if proxy_trusted_ips:
                for proxy in proxy_trusted_ips:
                    # right most proxy is the most reliable proxy that talks to the django server
                    if ips[-1].startswith(proxy):
                        client_ip, routable = util.get_ip_info(ips[0])
                        if client_ip and routable:
                            return client_ip, routable
            else:
                client_ip, routable = util.get_ip_info(util.get_best_ip(client_ip, ips[0]))
                if client_ip and routable:
                    return client_ip, routable

    return client_ip, routable