import urlparse
+
def sanitize_redirect(host, redirect_to):
"""
Given the hostname and an untrusted URL to redirect to,
and returns it, else returns None.
See http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L36
+
+ >>> print sanitize_redirect('myapp.com', None)
+ None
+ >>> print sanitize_redirect('myapp.com', '')
+ None
+ >>> print sanitize_redirect('myapp.com', {})
+ None
+ >>> print sanitize_redirect('myapp.com', 'http://notmyapp.com/path/')
+ None
+ >>> print sanitize_redirect('myapp.com', 'http://myapp.com/path/')
+ http://myapp.com/path/
+ >>> print sanitize_redirect('myapp.com', '/path/')
+ /path/
"""
# Quick sanity check.
if not redirect_to:
return None
- netloc = urlparse.urlparse(redirect_to)[1]
- # Heavier security check -- don't allow redirection to a different host.
+
+ # Heavier security check, don't allow redirection to a different host.
+ try:
+ netloc = urlparse.urlparse(redirect_to)[1]
+ except TypeError: # not valid redirect_to value
+ return None
+
if netloc and netloc != host:
return None
+
return redirect_to
+
+
+if __name__ == '__main__':
+ import doctest
+ doctest.testmod()
"""Views"""
from django.conf import settings
-from django.http import HttpResponseRedirect, HttpResponse, HttpResponseServerError
+from django.http import HttpResponseRedirect, HttpResponse, \
+ HttpResponseServerError
from django.core.urlresolvers import reverse
from django.db import transaction
from django.contrib.auth import login, REDIRECT_FIELD_NAME
try:
user = backend.auth_complete()
- except ValueError, e: # some Authentication error ocurred
+ except ValueError, e: # some Authentication error ocurred
user = None
error_key = getattr(settings, 'SOCIAL_AUTH_ERROR_KEY', None)
- if error_key: # store error in session
+ if error_key: # store error in session
request.session[error_key] = str(e)
if user and getattr(user, 'is_active', True):
login(request, user)
if getattr(settings, 'SOCIAL_AUTH_SESSION_EXPIRATION', True):
- # Set session expiration date if present and not disabled by setting
+ # Set session expiration date if present and not disabled by
+ # setting
backend_name = backend.AUTH_BACKEND.name
social_user = user.social_auth.get(provider=backend_name)
if social_user.expiration_delta():
return HttpResponseRedirect(url)
-def auth_process(request, backend, complete_url_name,
+def auth_process(request, backend, complete_url_name,
default_redirect=DEFAULT_REDIRECT):
"""Authenticate using social backend"""
redirect = reverse(complete_url_name, args=(backend,))