#!/usr/bin/env python
-import os, sys
+import os
+import sys
from os.path import dirname, abspath
+
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
parent = dirname(dirname(dirname(abspath(__file__))))
def test_twitter_backend(self):
# We grab the Twitter testing user details from settings file
TEST_TWITTER_USER = getattr(settings, 'TEST_TWITTER_USER', None)
- TEST_TWITTER_PASSWORD = getattr(settings, 'TEST_TWITTER_PASSWORD', None)
+ TEST_TWITTER_PASSWORD = getattr(settings, 'TEST_TWITTER_PASSWORD',
+ None)
self.assertTrue(TEST_TWITTER_USER)
self.assertTrue(TEST_TWITTER_PASSWORD)
def test_facebook_backend(self):
TEST_FACEBOOK_USER = getattr(settings, 'TEST_FACEBOOK_USER', None)
- TEST_FACEBOOK_PASSWORD = getattr(settings, 'TEST_FACEBOOK_PASSWORD', None)
+ TEST_FACEBOOK_PASSWORD = getattr(settings, 'TEST_FACEBOOK_PASSWORD',
+ None)
self.assertTrue(TEST_FACEBOOK_USER)
self.assertTrue(TEST_FACEBOOK_PASSWORD)
def test_linkedin_backend(self):
TEST_LINKEDIN_USER = getattr(settings, 'TEST_LINKEDIN_USER', None)
- TEST_LINKEDIN_PASSWORD = getattr(settings, 'TEST_LINKEDIN_PASSWORD', None)
+ TEST_LINKEDIN_PASSWORD = getattr(settings, 'TEST_LINKEDIN_PASSWORD',
+ None)
self.assertTrue(TEST_LINKEDIN_USER)
self.assertTrue(TEST_LINKEDIN_PASSWORD)
self.driver.get(self.url('/login/linkedin/'))
# We log in
- username_field = self.driver.find_element_by_id('session_key-oauthAuthorizeForm')
+ username_field = self.driver.find_element_by_id(
+ 'session_key-oauthAuthorizeForm')
username_field.send_keys(TEST_LINKEDIN_USER)
- password_field = self.driver.find_element_by_id('session_password-oauthAuthorizeForm')
+ password_field = self.driver.find_element_by_id(
+ 'session_password-oauthAuthorizeForm')
password_field.send_keys(TEST_LINKEDIN_PASSWORD)
password_field.submit()
# Django Social Auth documentation build configuration file, created by
# sphinx-quickstart on Sun Mar 20 23:07:14 2011.
#
-# This file is execfile()d with the current directory set to its containing dir.
+# This file is execfile()d with the current directory set to its containing
+# dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
# All configuration values have a default; values that are commented out
# serve to show the default.
-import sys, os
-
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
-# -- General configuration -----------------------------------------------------
+# -- General configuration ----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.viewcode']
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
+ 'sphinx.ext.todo', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
-# The reST default role (used for this markup: `text`) to use for all documents.
+# The reST default role (used for this markup: `text`) to use for all
+# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#modindex_common_prefix = []
-# -- Options for HTML output ---------------------------------------------------
+# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
htmlhelp_basename = 'DjangoSocialAuthdoc'
-# -- Options for LaTeX output --------------------------------------------------
+# -- Options for LaTeX output -------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author, documentclass [howto/manual]).
+# (source start file, target name, title, author, documentclass
+# [howto/manual]).
latex_documents = [
('index', 'DjangoSocialAuth.tex', u'Django Social Auth Documentation',
u'Matías Aguirre', 'manual'),
#latex_domain_indices = True
-# -- Options for manual page output --------------------------------------------
+# -- Options for manual page output -------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
from social_auth.signals import pre_update
from social_auth.backends.facebook import FacebookBackend
+
def facebook_extra_values(sender, user, response, details, **kwargs):
return False
username = kwargs['user'].username
else:
username = request.session.get('saved_username')
- return { 'username': username }
+ return {'username': username}
def redirect_to_form(*args, **kwargs):
- if not kwargs['request'].session.get('saved_username') and kwargs.get('user') is None:
+ if not kwargs['request'].session.get('saved_username') and \
+ kwargs.get('user') is None:
return HttpResponseRedirect('/form/')
return render_to_response('home.html', {'version': version},
RequestContext(request))
+
@login_required
def done(request):
"""Login complete view, displays user data"""
}
return render_to_response('done.html', ctx, RequestContext(request))
+
def error(request):
"""Error view"""
messages = get_messages(request)
'messages': messages},
RequestContext(request))
+
def logout(request):
"""Logs out user"""
auth_logout(request)
#!/usr/bin/env python
from django.core.management import execute_manager
try:
- import settings # Assumed to be in the same directory.
+ import settings # Assumed to be in the same directory.
except ImportError:
import sys
- sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+ sys.stderr.write(("Error: Can't find the file 'settings.py' in the " +
+ "directory containing %r. It appears you've "
+ "customized things.\nYou'll have to run "
+ "django-admin.py, passing it your settings module.\n" +
+ "(If the file settings.py does indeed exist, it's " +
+ "causing an ImportError somehow.)\n") % __file__)
sys.exit(1)
if __name__ == "__main__":
third parties.
"""
+
def long_description():
"""Return long description from README.rst if it's present
because it doesn't get installed."""
raise NotImplementedError('Implement in subclass')
def get_user(self, user_id):
- """Return user with given ID from the User model used by this backend"""
+ """
+ Return user with given ID from the User model used by this backend
+ """
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
setting is per backend and defined by:
<backend name in uppercase>_REQUEST_TOKEN_EXTRA_ARGUMENTS.
"""
- backend_name = self.AUTH_BACKEND.name.upper().replace('-','_')
+ backend_name = self.AUTH_BACKEND.name.upper().replace('-', '_')
return setting(backend_name + '_REQUEST_TOKEN_EXTRA_ARGUMENTS', {})
def auth_extra_arguments(self):
backend and defined by:
<backend name in uppercase>_AUTH_EXTRA_ARGUMENTS.
"""
- backend_name = self.AUTH_BACKEND.name.upper().replace('-','_')
+ backend_name = self.AUTH_BACKEND.name.upper().replace('-', '_')
return setting(backend_name + '_AUTH_EXTRA_ARGUMENTS', {})
@property
"""
try:
from urlparse import parse_qs
- parse_qs # placate pyflakes
+ parse_qs # placate pyflakes
except ImportError:
# fall back for Python 2.5
from cgi import parse_qs
def user_data(self, access_token):
"""Loads user data from service"""
- params = {'oauth_token': access_token,}
+ params = {'oauth_token': access_token}
url = FOURSQUARE_CHECK_AUTH + '?' + urllib.urlencode(params)
try:
return simplejson.load(urllib.urlopen(url))
# Setting these two are necessary for BaseAuth.authenticate to work
kwargs.update({
- 'response' : '',
+ 'response': '',
self.AUTH_BACKEND.name: True
})
return authenticate(*args, **kwargs)
'email': response.get('email') or '',
'first_name': response.get('name')}
+
class GithubAuth(BaseOAuth):
"""Github OAuth mechanism"""
AUTH_BACKEND = GithubBackend
def user_data(self, access_token):
"""Loads user data from service"""
- params = {'access_token': access_token,}
+ params = {'access_token': access_token}
url = INSTAGRAM_CHECK_AUTH + '?' + urllib.urlencode(params)
try:
return simplejson.load(urllib.urlopen(url))
if 'expires' in response:
data['expires'] = response['expires'][0]
- kwargs.update({ 'auth': self,
- 'response': data,
- self.AUTH_BACKEND.name: True })
+ kwargs.update({'auth': self,
+ 'response': data,
+ self.AUTH_BACKEND.name: True})
return authenticate(*args, **kwargs)
@classmethod
Parameters must be passed in queryset and Authorization header as described
on Google OAuth documentation at:
- http://groups.google.com/group/oauth/browse_thread/thread/d15add9beb418ebc
- and:
- http://code.google.com/apis/accounts/docs/OAuth2.html#CallingAnAPI
+ http://groups.google.com/group/oauth/browse_thread/thread/d15add9beb418ebc
+ and: http://code.google.com/apis/accounts/docs/OAuth2.html#CallingAnAPI
"""
request = Request(url + '?' + params, headers={'Authorization': params})
try:
data['backends'] = group_backend_by_type(data['backends'])
data['not_associated'] = group_backend_by_type(data['not_associated'])
data['associated'] = group_backend_by_type(data['associated'],
- key=lambda assoc: assoc.provider)
+ key=lambda assoc: assoc.provider)
return {'social_auth': data}
socialauth_registered = Signal(providing_args=['user', 'response', 'details'])
-socialauth_not_registered = Signal(providing_args=['uid', 'response', 'details'])
+socialauth_not_registered = Signal(providing_args=['uid', 'response',
+ 'details'])
if expired: # clear expired associations
Association.objects.filter(pk__in=expired).delete()
- if associations: # return most recet association
+ if associations: # return most recet association
associations.sort(key=lambda x: x.issued, reverse=True)
return associations[0]
REDIRECT_RE = re.compile('window.location.replace\("(.*)"\);')
+
class FacebookTestLogin(FacebookTestCase):
def test_login_succeful(self):
- response = self.client.get(self.reverse('socialauth_begin', 'facebook'))
+ response = self.client.get(self.reverse('socialauth_begin',
+ 'facebook'))
# social_auth must redirect to service page
self.assertEqual(response.status_code, 302)
REDIRECT_RE = re.compile('window.location.replace\("(.*)"\);')
+
class GoogleOpenIdTestLogin(GoogleTestCase):
SERVER_NAME = 'myapp.com'
SERVER_PORT = '8000'
# Check that action and values were loaded properly
self.assertTrue(parser.action)
self.assertTrue(parser.values)
- content = self.get_content(parser.action, parser.values, use_cookies=True)
+ content = self.get_content(parser.action, parser.values,
+ use_cookies=True)
parser = FormParserByID('gaia_loginform')
parser.feed(content)
"""
Given the hostname and an untrusted URL to redirect to,
this method tests it to make sure it isn't garbage/harmful
- and returns it, else returns None.
-
- See http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L36
+ and returns it, else returns None, similar as how's it done
+ on django.contrib.auth.views.
>>> print sanitize_redirect('myapp.com', None)
None
def log(level, *args, **kwargs):
"""Small wrapper around logger functions."""
- { 'debug': logger.debug,
- 'error': logger.error,
- 'exception': logger.exception,
- 'warn': logger.warn }[level](*args, **kwargs)
+ {'debug': logger.debug,
+ 'error': logger.error,
+ 'exception': logger.exception,
+ 'warn': logger.warn}[level](*args, **kwargs)
def model_to_ctype(val):
*args, **kwargs)
return backend.continue_pipeline(pipeline_index=idx, *args, **kwargs)
else:
- return backend.auth_complete(user=user, request=request, *args, **kwargs)
+ return backend.auth_complete(user=user, request=request, *args,
+ **kwargs)