Commit 8ce13d08 authored by Sofia Papagiannaki's avatar Sofia Papagiannaki
Browse files

Fix various unicode issues

Substitute ``synnefo.util.text.uenc`` occurrences
with the respective django encoding utilities
parent 9b77cbfe
......@@ -44,6 +44,7 @@ from django.contrib.auth import authenticate
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.utils.encoding import iri_to_uri
from django.utils.translation import ugettext as _
from astakos.im.models import AstakosUser, Invitation
......@@ -217,7 +218,7 @@ def prepare_response(request, user, next='', renew=False):
if not next:
next = settings.LOGIN_SUCCESS_URL
response['Location'] = next
response['Location'] = iri_to_uri(next)
response.status_code = 302
return response
......
......@@ -31,7 +31,6 @@
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
import urllib
import urlparse
import uuid
import datetime
......@@ -40,25 +39,11 @@ import json
from base64 import b64encode, b64decode
from hashlib import sha512
from synnefo.util.text import uenc
from synnefo.util import urltools
import logging
logger = logging.getLogger(__name__)
def urlencode(params):
if hasattr(params, 'urlencode') and callable(getattr(params, 'urlencode')):
return params.urlencode()
for k in params:
params[uenc(k)] = uenc(params.pop(k))
return urllib.urlencode(params)
def normalize(url):
return urltools.normalize(uenc(url))
def handles_oa2_requests(func):
def wrapper(self, *args, **kwargs):
if not self._errors_to_http:
......@@ -356,7 +341,7 @@ class SimpleBackend(object):
return bool(self.get_client_by_id(client_id))
def build_site_url(self, prefix='', **params):
params = urlencode(params)
params = self.urlencode(params)
return "%s%s%s%s" % (self.base_url, self.endpoints_prefix, prefix,
params)
......@@ -367,7 +352,7 @@ class SimpleBackend(object):
def build_client_redirect_uri(self, client, uri, **params):
if not client.redirect_uri_is_valid(uri):
raise OA2Error("Invalid redirect uri")
params = urlencode(params)
params = self.urlencode(params)
uri = self._get_uri_base(uri)
return "%s?%s" % (uri, params)
......@@ -411,12 +396,12 @@ class SimpleBackend(object):
def redirect_to_login_response(self, request, params):
parts = list(urlparse.urlsplit(request.path))
parts[3] = urlencode(params)
parts[3] = self.urlencode(params)
query = {'next': urlparse.urlunsplit(parts)}
return Response(302,
headers={'Location': '%s?%s' %
(self.get_login_uri(),
urlencode(query))})
parts[2] = self.get_login_uri()
parts[3] = self.urlencode(query)
return Response(302, headers={'Location': urlparse.urlunsplit(parts)})
def redirect_to_uri(self, redirect_uri, code, state=None):
parts = list(urlparse.urlsplit(redirect_uri))
......@@ -424,10 +409,8 @@ class SimpleBackend(object):
params['code'] = code
if state is not None:
params['state'] = state
parts[3] = urlencode(params)
return Response(302,
headers={'Location': '%s' %
urlparse.urlunsplit(parts)})
parts[3] = self.urlencode(params)
return Response(302, headers={'Location': urlparse.urlunsplit(parts)})
def build_response_from_error(self, exception):
response = Response(400)
......@@ -459,7 +442,8 @@ class SimpleBackend(object):
scope=None, token_type="Bearer"):
if scope and code_instance.scope != scope:
raise OA2Error("Invalid scope")
if normalize(redirect_uri) != normalize(code_instance.redirect_uri):
if self.normalize(redirect_uri) != \
self.normalize(code_instance.redirect_uri):
raise OA2Error("The redirect uri does not match "
"the one used during authorization")
token = self.add_token_for_client(token_type, code_instance)
......@@ -572,7 +556,8 @@ class SimpleBackend(object):
if not client.redirect_uri_is_valid(redirect_uri):
raise OA2Error("Mismatching redirect uri")
if expected_value is not None and \
normalize(redirect_uri) != normalize(expected_value):
self.normalize(redirect_uri) != \
self.normalize(expected_value):
raise OA2Error("Invalid redirect uri")
else:
try:
......@@ -707,3 +692,11 @@ class SimpleBackend(object):
else:
#TODO: handle custom type
raise OA2Error("Invalid grant type")
@staticmethod
def urlencode(params):
raise NotImplementedError
@staticmethod
def normalize(url):
raise NotImplementedError
......@@ -43,10 +43,13 @@ from django.core.validators import URLValidator
from django.core.urlresolvers import reverse
from django.conf.urls.defaults import patterns, url
from django.http import HttpResponseNotAllowed
from django.utils.encoding import smart_str, iri_to_uri
from django.views.decorators.csrf import csrf_exempt
from synnefo.lib import join_urls
from synnefo.util.text import uenc
from synnefo.util import urltools
import urllib
import logging
logger = logging.getLogger(__name__)
......@@ -121,7 +124,7 @@ class DjangoBackend(DjangoBackendORMMixin, oa2base.SimpleBackend,
response.status_code = oa2response.status
response.content = oa2response.body
for key, value in oa2response.headers.iteritems():
response[uenc(key)] = uenc(value)
response[smart_str(key)] = smart_str(value)
return response
def build_request(self, django_request):
......@@ -165,6 +168,19 @@ class DjangoBackend(DjangoBackendORMMixin, oa2base.SimpleBackend,
def get_login_uri(self):
return reverse('login')
@staticmethod
def urlencode(params):
if hasattr(params, 'urlencode') and \
callable(getattr(params, 'urlencode')):
return params.urlencode()
for k in params:
params[smart_str(k)] = smart_str(params.pop(k))
return urllib.urlencode(params)
@staticmethod
def normalize(url):
return urltools.normalize(iri_to_uri(url))
class AstakosBackend(DjangoBackend):
pass
......@@ -44,15 +44,14 @@ from django.test import Client as TestClient
from django.core.urlresolvers import reverse
from django.utils import simplejson as json
from django.utils.encoding import smart_str, iri_to_uri
from astakos.oa2 import settings
from astakos.oa2.models import Client, AuthorizationCode, Token
from astakos.im.tests import common
from synnefo.util.text import uenc
from synnefo.util.urltools import normalize
ParsedURL = namedtuple('ParsedURL', ['host', 'scheme', 'path', 'params',
'url'])
......@@ -105,7 +104,7 @@ class URLAssertionsMixin(object):
@parsed_url_wrapper
def assertPath(self, url, path):
self.assertEqual(normalize(url.path), normalize(path))
self.assertEqual(iri_to_uri(url.path), iri_to_uri(path))
@parsed_url_wrapper
def assertSecure(self, url, key):
......@@ -219,10 +218,10 @@ class TestOA2(TestCase, URLAssertionsMixin):
self.assertEqual(token.token_type, token_type)
self.assertEqual(token.grant_type, 'authorization_code')
#self.assertEqual(token.user, expected.get('user'))
self.assertEqual(normalize(uenc(token.redirect_uri)),
normalize(uenc(expected.get('redirect_uri'))))
self.assertEqual(normalize(uenc(token.scope)),
normalize(uenc(expected.get('scope'))))
self.assertEqual(smart_str(token.redirect_uri),
smart_str(expected.get('redirect_uri')))
self.assertEqual(smart_str(token.scope),
smart_str(expected.get('scope')))
self.assertEqual(token.state, expected.get('state'))
except Token.DoesNotExist:
self.fail("Invalid access_token")
......@@ -231,7 +230,7 @@ class TestOA2(TestCase, URLAssertionsMixin):
baseurl = reverse('oauth2_authenticate').replace('/auth', '/')
self.client = OA2Client(baseurl)
client1 = Client.objects.create(identifier="client1", secret="secret")
self.client1_redirect_uri = "https://server.com/handle_code"
self.client1_redirect_uri = "https://server.com/handle_code?α=β&a=b"
client1.redirecturl_set.create(url=self.client1_redirect_uri)
client2 = Client.objects.create(identifier="client2", type='public')
......@@ -331,7 +330,8 @@ class TestOA2(TestCase, URLAssertionsMixin):
code = AuthorizationCode.objects.get(code=redirect.params['code'][0])
#self.assertEqual(code.state, '')
self.assertEqual(code.state, None)
self.assertEqual(code.redirect_uri, self.client1_redirect_uri)
self.assertEqual(normalize(iri_to_uri(code.redirect_uri)),
normalize(iri_to_uri(self.client1_redirect_uri)))
params['state'] = 'csrfstate'
params['scope'] = 'resource1'
......@@ -342,7 +342,8 @@ class TestOA2(TestCase, URLAssertionsMixin):
code = AuthorizationCode.objects.get(code=redirect.params['code'][0])
self.assertEqual(code.state, 'csrfstate')
self.assertEqual(code.redirect_uri, self.client1_redirect_uri)
self.assertEqual(normalize(iri_to_uri(code.redirect_uri)),
normalize(iri_to_uri(self.client1_redirect_uri)))
# valid request: trusted client
params = {'redirect_uri': self.client3_redirect_uri,
......@@ -419,7 +420,8 @@ class TestOA2(TestCase, URLAssertionsMixin):
self.assertEqual(r.status_code, 400)
# redirect uri descendant
redirect_uri = '%s/φωτογραφία.JPG?α=γιουνικοντ' % self.client3_redirect_uri
redirect_uri = '%s/φωτογραφία.JPG?α=γιουνικοντ' % \
self.client3_redirect_uri
params['redirect_uri'] = redirect_uri
self.client.set_credentials('client3', 'secret')
r = self.client.authorize_code('client3', urlparams=params)
......@@ -436,8 +438,8 @@ class TestOA2(TestCase, URLAssertionsMixin):
code = AuthorizationCode.objects.get(code=redirect.params['code'][0])
self.assertEqual(code.state, 'csrfstate')
self.assertEqual(normalize(uenc(code.redirect_uri)),
normalize(uenc(redirect_uri)))
self.assertEqual(smart_str(code.redirect_uri),
smart_str(redirect_uri))
def test_get_token(self):
# invalid method
......@@ -553,7 +555,8 @@ class TestOA2(TestCase, URLAssertionsMixin):
'state': None}
self.assert_access_token_response(r, expected)
redirect_uri = '%s/φωτογραφία.JPG?α=γιουνικοντ' % self.client3_redirect_uri
redirect_uri = '%s/φωτογραφία.JPG?α=γιουνικοντ' % \
self.client3_redirect_uri
params = {'redirect_uri': redirect_uri}
r = self.client.authorize_code('client3', urlparams=params)
self.assertCount(AuthorizationCode, 1)
......
......@@ -76,7 +76,6 @@ from pithos.backends.base import (NotAllowedError, QuotaError, ItemNotExists,
VersionNotExists)
from synnefo.lib import join_urls
from synnefo.util import text
from astakosclient import AstakosClient
from astakosclient.errors import NoUserName, NoUUID, AstakosClientException
......@@ -1185,8 +1184,9 @@ def view_method():
try:
access_token = request.GET.get('access_token')
requested_resource = text.uenc(request.path.split(VIEW_PREFIX,
2)[-1])
requested_resource = request.path.split(VIEW_PREFIX, 2)[-1]
requested_resource = smart_str(requested_resource,
encoding="utf-8")
astakos = AstakosClient(SERVICE_TOKEN, ASTAKOS_AUTH_URL,
retry=2, use_pool=True,
logger=logger)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment