Projet

Général

Profil

0001-utils-add-a-same_origin-url1-url2-helper-32239.patch

Benjamin Dauvergne, 12 avril 2019 20:40

Télécharger (2,28 ko)

Voir les différences:

Subject: [PATCH 1/3] utils: add a same_origin(url1, url2) helper (#32239)

 combo/utils/urls.py | 47 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)
combo/utils/urls.py
20 20
from django.utils.encoding import force_text
21 21
from django.template import Context, Template, TemplateSyntaxError, VariableDoesNotExist
22 22
from django.utils.http import quote
23
from django.utils.six.moves.urllib import parse as urlparse
23 24

  
24 25

  
25 26
class TemplateError(Exception):
......
62 63
            raise TemplateError('unknown variable %s', varname)
63 64
        return force_text(template_vars[varname])
64 65
    return re.sub(r'(\[.+?\])', repl, url)
66

  
67
PROTOCOLS_TO_PORT = {
68
    'http': '80',
69
    'https': '443',
70
}
71

  
72

  
73
def same_domain(domain1, domain2):
74
    if domain1 == domain2:
75
        return True
76

  
77
    if not domain1 or not domain2:
78
        return False
79

  
80
    if domain2.startswith('.'):
81
        # p1 is a sub-domain or the base domain
82
        if domain1.endswith(domain2) or domain1 == domain2[1:]:
83
            return True
84
    return False
85

  
86

  
87
def same_origin(url1, url2):
88
    '''Checks if both URL use the same domain. It understands domain patterns on url2, i.e. .example.com
89
    matches www.example.com.
90

  
91
    If not scheme is given in url2, scheme compare is skipped.
92
    If not scheme and not port are given, port compare is skipped.
93
    The last two rules allow authorizing complete domains easily.
94
    '''
95
    p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2)
96

  
97
    if p2.scheme and p1.scheme != p2.scheme:
98
        return False
99

  
100
    if not same_domain(p1.hostname, p2.hostname):
101
        return False
102

  
103
    try:
104
        if (p2.port or (p1.port and p2.scheme)) and (
105
                (p1.port or PROTOCOLS_TO_PORT[p1.scheme])
106
                != (p2.port or PROTOCOLS_TO_PORT[p2.scheme])):
107
            return False
108
    except (ValueError, KeyError):
109
        return False
110

  
111
    return True
65
-