Skip to content

Commit 190b6de

Browse files
committed
2 parents 480b447 + c6f7c20 commit 190b6de

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

oauth2_provider/validators.py

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,49 @@
1-
from django.core.validators import URLValidator
1+
from __future__ import unicode_literals
2+
3+
import re
4+
5+
from django.core.exceptions import ValidationError
6+
from django.utils.translation import ugettext_lazy as _
7+
from django.utils.encoding import force_text
8+
from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
9+
from django.core.validators import RegexValidator
10+
11+
12+
class URIValidator(RegexValidator):
13+
regex = re.compile(
14+
r'^(?:[a-z0-9\.\-]*)s?://' # http:// or https://
15+
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
16+
r'(?!-)[A-Z\d-]{1,63}(?<!-)|' # also cover non-dotted domain
17+
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
18+
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
19+
r'(?::\d+)?' # optional port
20+
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
21+
message = _('Enter a valid URL.')
22+
23+
def __call__(self, value):
24+
try:
25+
super(URIValidator, self).__call__(value)
26+
except ValidationError as e:
27+
# Trivial case failed. Try for possible IDN domain
28+
if value:
29+
value = force_text(value)
30+
scheme, netloc, path, query, fragment = urlsplit(value)
31+
try:
32+
netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
33+
except UnicodeError: # invalid domain part
34+
raise e
35+
url = urlunsplit((scheme, netloc, path, query, fragment))
36+
super(URIValidator, self).__call__(url)
37+
else:
38+
raise
39+
else:
40+
url = value
241

342

443
def validate_uris(value):
544
"""
645
This validator ensures that `value` contains valid blank-separated urls"
746
"""
8-
v = URLValidator()
47+
v = URIValidator()
948
for uri in value.split():
1049
v(uri)

0 commit comments

Comments
 (0)