From: Matías Aguirre Date: Sat, 4 Feb 2012 19:44:39 +0000 (-0200) Subject: Improve settings values gathering X-Git-Url: https://git.parisson.com/?a=commitdiff_plain;h=8a6ca06663adb707e4d49d09494163ac350e4769;p=django-social-auth.git Improve settings values gathering --- diff --git a/social_auth/backends/__init__.py b/social_auth/backends/__init__.py index 6884320..eda7864 100644 --- a/social_auth/backends/__init__.py +++ b/social_auth/backends/__init__.py @@ -24,7 +24,6 @@ from oauth2 import Consumer as OAuthConsumer, Token, Request as OAuthRequest, \ SignatureMethod_HMAC_SHA1 from django.db import models -from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.backends import ModelBackend from django.utils import simplejson @@ -35,8 +34,8 @@ from social_auth.store import DjangoOpenIDStore from social_auth.backends.exceptions import StopPipeline -if getattr(settings, 'SOCIAL_AUTH_USER_MODEL', None): - User = models.get_model(*settings.SOCIAL_AUTH_USER_MODEL.rsplit('.', 1)) +if setting('SOCIAL_AUTH_USER_MODEL'): + User = models.get_model(*setting('SOCIAL_AUTH_USER_MODEL').rsplit('.', 1)) else: from django.contrib.auth.models import User @@ -308,8 +307,8 @@ class BaseAuth(object): """Return extra argumens needed on auth process, setting is per bancked and defined by _AUTH_EXTRA_ARGUMENTS. """ - name = self.AUTH_BACKEND.name.upper().replace('-','_') + '_AUTH_EXTRA_ARGUMENTS' - return getattr(settings, name, {}) + backend_name = self.AUTH_BACKEND.name.upper().replace('-','_') + return setting(backend_name + '_AUTH_EXTRA_ARGUMENTS', {}) @property def uses_redirect(self): @@ -531,8 +530,8 @@ class ConsumerBasedOAuth(BaseOAuth): @classmethod def enabled(cls): """Return backend enabled status by checking basic settings""" - return all(hasattr(settings, name) for name in - (cls.SETTINGS_KEY_NAME, cls.SETTINGS_SECRET_NAME)) + return setting(cls.SETTINGS_KEY_NAME) and \ + setting(cls.SETTINGS_SECRET_NAME) class BaseOAuth2(BaseOAuth): @@ -635,7 +634,7 @@ def get_backends(force_load=False): below can retry a requested backend that may not yet be discovered. """ if not BACKENDS or force_load: - for auth_backend in settings.AUTHENTICATION_BACKENDS: + for auth_backend in setting('AUTHENTICATION_BACKENDS'): module = import_module(auth_backend.rsplit(".", 1)[0]) backends = getattr(module, "BACKENDS", {}) for name, backend in backends.items(): diff --git a/social_auth/backends/contrib/dropbox.py b/social_auth/backends/contrib/dropbox.py index 0a140fb..33a484b 100644 --- a/social_auth/backends/contrib/dropbox.py +++ b/social_auth/backends/contrib/dropbox.py @@ -8,9 +8,9 @@ given by Dropbox application registration process. By default account id and token expiration time are stored in extra_data field, check OAuthBackend class for details on how to extend it. """ -from django.conf import settings from django.utils import simplejson +from social_auth.utils import setting from social_auth.backends import ConsumerBasedOAuth, OAuthBackend, USERNAME @@ -20,14 +20,16 @@ DROPBOX_API = 'api.%s' % DROPBOX_SERVER DROPBOX_REQUEST_TOKEN_URL = 'https://%s/1/oauth/request_token' % DROPBOX_API DROPBOX_AUTHORIZATION_URL = 'https://www.%s/1/oauth/authorize' % DROPBOX_SERVER DROPBOX_ACCESS_TOKEN_URL = 'https://%s/1/oauth/access_token' % DROPBOX_API -EXPIRES_NAME = getattr(settings, 'SOCIAL_AUTH_EXPIRATION', 'expires') class DropboxBackend(OAuthBackend): """Dropbox OAuth authentication backend""" name = 'dropbox' # Default extra data to store - EXTRA_DATA = [('id', 'id'), ('expires', EXPIRES_NAME)] + EXTRA_DATA = [ + ('id', 'id'), + ('expires', setting('SOCIAL_AUTH_EXPIRATION', 'expires')) + ] def get_user_details(self, response): """Return user details from Dropbox account""" @@ -64,9 +66,7 @@ class DropboxAuth(ConsumerBasedOAuth): @classmethod def enabled(cls): """Return backend enabled status by checking basic settings""" - return all(hasattr(settings, name) for name in - ('DROPBOX_APP_ID', - 'DROPBOX_API_SECRET')) + return setting('DROPBOX_APP_ID') and setting('DROPBOX_API_SECRET') # Backend definition diff --git a/social_auth/backends/contrib/flickr.py b/social_auth/backends/contrib/flickr.py index b61db38..b6ba55b 100644 --- a/social_auth/backends/contrib/flickr.py +++ b/social_auth/backends/contrib/flickr.py @@ -10,14 +10,14 @@ extra_data field, check OAuthBackend class for details on how to extend it. """ 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 -from django.conf import settings - from oauth2 import Token + +from social_auth.utils import setting from social_auth.backends import ConsumerBasedOAuth, OAuthBackend, USERNAME @@ -26,16 +26,17 @@ FLICKR_SERVER = 'http://www.flickr.com/services' FLICKR_REQUEST_TOKEN_URL = '%s/oauth/request_token' % FLICKR_SERVER FLICKR_AUTHORIZATION_URL = '%s/oauth/authorize' % FLICKR_SERVER FLICKR_ACCESS_TOKEN_URL = '%s/oauth/access_token' % FLICKR_SERVER -EXPIRES_NAME = getattr(settings, 'SOCIAL_AUTH_EXPIRATION', 'expires') class FlickrBackend(OAuthBackend): """Flickr OAuth authentication backend""" name = 'flickr' # Default extra data to store - EXTRA_DATA = [('id', 'id'), - ('username', 'username'), - ('expires', EXPIRES_NAME)] + EXTRA_DATA = [ + ('id', 'id'), + ('username', 'username'), + ('expires', setting('SOCIAL_AUTH_EXPIRATION', 'expires')) + ] def get_user_details(self, response): """Return user details from Flickr account""" diff --git a/social_auth/backends/contrib/github.py b/social_auth/backends/contrib/github.py index 3b13835..11df0e0 100644 --- a/social_auth/backends/contrib/github.py +++ b/social_auth/backends/contrib/github.py @@ -17,10 +17,10 @@ import logging logger = logging.getLogger(__name__) -from django.conf import settings from django.utils import simplejson from django.contrib.auth import authenticate +from social_auth.utils import setting from social_auth.backends import BaseOAuth, OAuthBackend, USERNAME @@ -29,14 +29,16 @@ GITHUB_SERVER = 'github.com' GITHUB_AUTHORIZATION_URL = 'https://%s/login/oauth/authorize' % GITHUB_SERVER GITHUB_ACCESS_TOKEN_URL = 'https://%s/login/oauth/access_token' % GITHUB_SERVER GITHUB_API_URL = 'https://api.%s' % GITHUB_SERVER -EXPIRES_NAME = getattr(settings, 'SOCIAL_AUTH_EXPIRATION', 'expires') class GithubBackend(OAuthBackend): """Github OAuth authentication backend""" name = 'github' # Default extra data to store - EXTRA_DATA = [('id', 'id'), ('expires', EXPIRES_NAME)] + EXTRA_DATA = [ + ('id', 'id'), + ('expires', setting('SOCIAL_AUTH_EXPIRATION', 'expires')) + ] def get_user_details(self, response): """Return user details from Github account""" @@ -50,21 +52,22 @@ class GithubAuth(BaseOAuth): def auth_url(self): """Returns redirect url""" - args = {'client_id': settings.GITHUB_APP_ID, + args = {'client_id': setting('GITHUB_APP_ID'), 'redirect_uri': self.redirect_uri} - if hasattr(settings, 'GITHUB_EXTENDED_PERMISSIONS'): - args['scope'] = ','.join(settings.GITHUB_EXTENDED_PERMISSIONS) + if setting('GITHUB_EXTENDED_PERMISSIONS'): + args['scope'] = ','.join(setting('GITHUB_EXTENDED_PERMISSIONS')) args.update(self.auth_extra_arguments()) return GITHUB_AUTHORIZATION_URL + '?' + urllib.urlencode(args) def auth_complete(self, *args, **kwargs): """Returns user, might be logged in""" if 'code' in self.data: - url = GITHUB_ACCESS_TOKEN_URL + '?' + \ - urllib.urlencode({'client_id': settings.GITHUB_APP_ID, - 'redirect_uri': self.redirect_uri, - 'client_secret': settings.GITHUB_API_SECRET, - 'code': self.data['code']}) + url = GITHUB_ACCESS_TOKEN_URL + '?' + urllib.urlencode({ + 'client_id': setting('GITHUB_APP_ID'), + 'redirect_uri': self.redirect_uri, + 'client_secret': setting('GITHUB_API_SECRET'), + 'code': self.data['code'] + }) response = cgi.parse_qs(urllib.urlopen(url).read()) if response.get('error'): error = self.data.get('error') or 'unknown error' @@ -94,9 +97,7 @@ class GithubAuth(BaseOAuth): @classmethod def enabled(cls): """Return backend enabled status by checking basic settings""" - return all(hasattr(settings, name) for name in - ('GITHUB_APP_ID', - 'GITHUB_API_SECRET')) + return setting('GITHUB_APP_ID') and setting('GITHUB_API_SECRET') # Backend definition diff --git a/social_auth/backends/contrib/linkedin.py b/social_auth/backends/contrib/linkedin.py index 00ac92b..94fae9f 100644 --- a/social_auth/backends/contrib/linkedin.py +++ b/social_auth/backends/contrib/linkedin.py @@ -9,8 +9,7 @@ logger = logging.getLogger(__name__) from xml.etree import ElementTree from xml.parsers.expat import ExpatError -from django.conf import settings - +from social_auth.utils import setting from social_auth.backends import ConsumerBasedOAuth, OAuthBackend, USERNAME @@ -57,8 +56,7 @@ class LinkedinAuth(ConsumerBasedOAuth): def user_data(self, access_token): """Return user data provided""" fields_selectors = LINKEDIN_FIELD_SELECTORS + \ - getattr(settings, 'LINKEDIN_EXTRA_FIELD_SELECTORS', - []) + setting('LINKEDIN_EXTRA_FIELD_SELECTORS', []) url = LINKEDIN_CHECK_AUTH + ':(%s)' % ','.join(fields_selectors) request = self.oauth_request(access_token, url) raw_xml = self.fetch_response(request) diff --git a/social_auth/backends/contrib/orkut.py b/social_auth/backends/contrib/orkut.py index c426dab..7ad4054 100644 --- a/social_auth/backends/contrib/orkut.py +++ b/social_auth/backends/contrib/orkut.py @@ -14,9 +14,9 @@ import urllib import logging logger = logging.getLogger(__name__) -from django.conf import settings from django.utils import simplejson +from social_auth.utils import setting from social_auth.backends import OAuthBackend, USERNAME from social_auth.backends.google import BaseGoogleOAuth @@ -56,9 +56,9 @@ class OrkutAuth(BaseGoogleOAuth): def user_data(self, access_token): """Loads user data from Orkut service""" fields = ORKUT_DEFAULT_DATA - if hasattr(settings, 'ORKUT_EXTRA_DATA'): - fields += ',' + settings.ORKUT_EXTRA_DATA - scope = ORKUT_SCOPE + getattr(settings, 'ORKUT_EXTRA_SCOPE', []) + if setting('ORKUT_EXTRA_DATA'): + fields += ',' + setting('ORKUT_EXTRA_DATA') + scope = ORKUT_SCOPE + setting('ORKUT_EXTRA_SCOPE', []) params = {'method': 'people.get', 'id': 'myself', 'userId': '@me', @@ -74,7 +74,7 @@ class OrkutAuth(BaseGoogleOAuth): def oauth_request(self, token, url, extra_params=None): extra_params = extra_params or {} - scope = ORKUT_SCOPE + getattr(settings, 'ORKUT_EXTRA_SCOPE', []) + scope = ORKUT_SCOPE + setting('ORKUT_EXTRA_SCOPE', []) extra_params['scope'] = ' '.join(scope) return super(OrkutAuth, self).oauth_request(token, url, extra_params) diff --git a/social_auth/backends/facebook.py b/social_auth/backends/facebook.py index d51b0e5..57e30cf 100644 --- a/social_auth/backends/facebook.py +++ b/social_auth/backends/facebook.py @@ -19,16 +19,14 @@ import cgi from urllib import urlencode from urllib2 import urlopen -from django.conf import settings from django.utils import simplejson from django.contrib.auth import authenticate from social_auth.backends import BaseOAuth2, OAuthBackend, USERNAME -from social_auth.utils import sanitize_log_data +from social_auth.utils import sanitize_log_data, setting # Facebook configuration -EXPIRES_NAME = getattr(settings, 'SOCIAL_AUTH_EXPIRATION', 'expires') FACEBOOK_ME = 'https://graph.facebook.com/me?' @@ -36,7 +34,10 @@ class FacebookBackend(OAuthBackend): """Facebook OAuth2 authentication backend""" name = 'facebook' # Default extra data to store - EXTRA_DATA = [('id', 'id'), ('expires', EXPIRES_NAME)] + EXTRA_DATA = [ + ('id', 'id'), + ('expires', setting('SOCIAL_AUTH_EXPIRATION', 'expires')) + ] def get_user_details(self, response): """Return user details from Facebook account""" @@ -57,7 +58,7 @@ class FacebookAuth(BaseOAuth2): SETTINGS_SECRET_NAME = 'FACEBOOK_API_SECRET' def get_scope(self): - return getattr(settings, 'FACEBOOK_EXTENDED_PERMISSIONS', []) + return setting('FACEBOOK_EXTENDED_PERMISSIONS', []) def user_data(self, access_token): """Loads user data from service""" @@ -79,9 +80,9 @@ class FacebookAuth(BaseOAuth2): """Completes loging process, must return user instance""" if 'code' in self.data: url = 'https://graph.facebook.com/oauth/access_token?' + \ - urlencode({'client_id': settings.FACEBOOK_APP_ID, + urlencode({'client_id': setting('FACEBOOK_APP_ID'), 'redirect_uri': self.redirect_uri, - 'client_secret': settings.FACEBOOK_API_SECRET, + 'client_secret': setting('FACEBOOK_API_SECRET'), 'code': self.data['code']}) response = cgi.parse_qs(urlopen(url).read()) access_token = response['access_token'][0] @@ -104,8 +105,7 @@ class FacebookAuth(BaseOAuth2): @classmethod def enabled(cls): """Return backend enabled status by checking basic settings""" - return all(hasattr(settings, name) for name in ('FACEBOOK_APP_ID', - 'FACEBOOK_API_SECRET')) + return setting('FACEBOOK_APP_ID') and setting('FACEBOOK_API_SECRET') # Backend definition diff --git a/social_auth/backends/google.py b/social_auth/backends/google.py index 21b5453..92e4385 100644 --- a/social_auth/backends/google.py +++ b/social_auth/backends/google.py @@ -21,9 +21,9 @@ from urllib2 import Request, urlopen from oauth2 import Request as OAuthRequest -from django.conf import settings from django.utils import simplejson +from social_auth.utils import setting from social_auth.backends import OpenIdAuth, ConsumerBasedOAuth, BaseOAuth2, \ OAuthBackend, OpenIDBackend, USERNAME @@ -44,7 +44,6 @@ GOOGLE_OAUTH_SCOPE = ['https://www.googleapis.com/auth/userinfo#email'] GOOGLEAPIS_EMAIL = 'https://www.googleapis.com/userinfo/email' GOOGLE_OPENID_URL = 'https://www.google.com/accounts/o8/id' -EXPIRES_NAME = getattr(settings, 'SOCIAL_AUTH_EXPIRATION', 'expires') # Backends @@ -69,8 +68,10 @@ class GoogleOAuthBackend(OAuthBackend): class GoogleOAuth2Backend(GoogleOAuthBackend): """Google OAuth2 authentication backend""" name = 'google-oauth2' - EXTRA_DATA = [('refresh_token', 'refresh_token'), - ('expires_in', EXPIRES_NAME)] + EXTRA_DATA = [ + ('refresh_token', 'refresh_token'), + ('expires_in', setting('SOCIAL_AUTH_EXPIRATION', 'expires')) + ] class GoogleBackend(OpenIDBackend): @@ -126,14 +127,12 @@ class GoogleOAuth(BaseGoogleOAuth): def oauth_request(self, token, url, extra_params=None): extra_params = extra_params or {} - scope = GOOGLE_OAUTH_SCOPE + \ - getattr(settings, 'GOOGLE_OAUTH_EXTRA_SCOPE', []) + scope = GOOGLE_OAUTH_SCOPE + setting('GOOGLE_OAUTH_EXTRA_SCOPE', []) extra_params.update({ 'scope': ' '.join(scope), }) if not self.registered(): - xoauth_displayname = getattr(settings, 'GOOGLE_DISPLAY_NAME', - 'Social Auth') + xoauth_displayname = setting('GOOGLE_DISPLAY_NAME', 'Social Auth') extra_params['xoauth_displayname'] = xoauth_displayname return super(GoogleOAuth, self).oauth_request(token, url, extra_params) @@ -159,7 +158,7 @@ class GoogleOAuth(BaseGoogleOAuth): # TODO: Remove this setting name check, keep for backward compatibility -_OAUTH2_KEY_NAME = hasattr(settings, 'GOOGLE_OAUTH2_CLIENT_ID') and \ +_OAUTH2_KEY_NAME = setting('GOOGLE_OAUTH2_CLIENT_ID') and \ 'GOOGLE_OAUTH2_CLIENT_ID' or \ 'GOOGLE_OAUTH2_CLIENT_KEY' @@ -173,8 +172,7 @@ class GoogleOAuth2(BaseOAuth2): SETTINGS_SECRET_NAME = 'GOOGLE_OAUTH2_CLIENT_SECRET' def get_scope(self): - return GOOGLE_OAUTH_SCOPE + \ - getattr(settings, 'GOOGLE_OAUTH_EXTRA_SCOPE', []) + return GOOGLE_OAUTH_SCOPE + setting('GOOGLE_OAUTH_EXTRA_SCOPE', []) def user_data(self, access_token): """Return user data from Google API""" diff --git a/social_auth/backends/pipeline/associate.py b/social_auth/backends/pipeline/associate.py index 1e260fd..18c9c46 100644 --- a/social_auth/backends/pipeline/associate.py +++ b/social_auth/backends/pipeline/associate.py @@ -1,6 +1,6 @@ -from django.conf import settings from django.core.exceptions import MultipleObjectsReturned +from social_auth.utils import setting from social_auth.models import User from social_auth.backends.pipeline import warn_setting @@ -11,7 +11,7 @@ def associate_by_email(details, *args, **kwargs): warn_setting('SOCIAL_AUTH_ASSOCIATE_BY_MAIL', 'associate_by_email') - if email and getattr(settings, 'SOCIAL_AUTH_ASSOCIATE_BY_MAIL', False): + if email and setting('SOCIAL_AUTH_ASSOCIATE_BY_MAIL'): # try to associate accounts registered with the same email address, # only if it's a single object. ValueError is raised if multiple # objects are returned diff --git a/social_auth/backends/pipeline/social.py b/social_auth/backends/pipeline/social.py index 604fb8c..d843616 100644 --- a/social_auth/backends/pipeline/social.py +++ b/social_auth/backends/pipeline/social.py @@ -1,6 +1,6 @@ -from django.conf import settings from django.db.utils import IntegrityError +from social_auth.utils import setting from social_auth.models import UserSocialAuth from social_auth.backends.pipeline import warn_setting @@ -51,7 +51,7 @@ def load_extra_data(backend, details, response, social_user, uid, user, """ warn_setting('SOCIAL_AUTH_EXTRA_DATA', 'load_extra_data') - if getattr(settings, 'SOCIAL_AUTH_EXTRA_DATA', True): + if setting('SOCIAL_AUTH_EXTRA_DATA', True): extra_data = backend.extra_data(user, uid, response, details) if extra_data and social_user.extra_data != extra_data: social_user.extra_data = extra_data diff --git a/social_auth/backends/pipeline/user.py b/social_auth/backends/pipeline/user.py index eaca1ae..d8d006f 100644 --- a/social_auth/backends/pipeline/user.py +++ b/social_auth/backends/pipeline/user.py @@ -1,7 +1,6 @@ from uuid import uuid4 -from django.conf import settings - +from social_auth.utils import setting from social_auth.models import User from social_auth.backends.pipeline import USERNAME, USERNAME_MAX_LENGTH, \ warn_setting @@ -22,20 +21,19 @@ def get_username(details, user=None, *args, **kwargs): warn_setting('SOCIAL_AUTH_UUID_LENGTH', 'get_username') warn_setting('SOCIAL_AUTH_USERNAME_FIXER', 'get_username') - if getattr(settings, 'SOCIAL_AUTH_FORCE_RANDOM_USERNAME', False): + if setting('SOCIAL_AUTH_FORCE_RANDOM_USERNAME'): username = uuid4().get_hex() elif details.get(USERNAME): username = details[USERNAME] - elif hasattr(settings, 'SOCIAL_AUTH_DEFAULT_USERNAME'): - username = settings.SOCIAL_AUTH_DEFAULT_USERNAME + elif setting('SOCIAL_AUTH_DEFAULT_USERNAME'): + username = setting('SOCIAL_AUTH_DEFAULT_USERNAME') if callable(username): username = username() else: username = uuid4().get_hex() - uuid_lenght = getattr(settings, 'SOCIAL_AUTH_UUID_LENGTH', 16) - username_fixer = getattr(settings, 'SOCIAL_AUTH_USERNAME_FIXER', - lambda u: u) + uuid_lenght = setting('SOCIAL_AUTH_UUID_LENGTH', 16) + username_fixer = setting('SOCIAL_AUTH_USERNAME_FIXER', lambda u: u) short_username = username[:USERNAME_MAX_LENGTH - uuid_lenght] final_username = None @@ -66,7 +64,7 @@ def create_user(backend, details, response, uid, username, user=None, *args, warn_setting('SOCIAL_AUTH_CREATE_USERS', 'create_user') - if not getattr(settings, 'SOCIAL_AUTH_CREATE_USERS', True): + if not setting('SOCIAL_AUTH_CREATE_USERS', True): # Send signal for cases where tracking failed registering is useful. socialauth_not_registered.send(sender=backend.__class__, uid=uid, @@ -89,7 +87,7 @@ def update_user_details(backend, details, response, user, is_new=False, *args, warn_setting('SOCIAL_AUTH_CHANGE_SIGNAL_ONLY', 'update_user_details') # check if values update should be left to signals handlers only - if not getattr(settings, 'SOCIAL_AUTH_CHANGE_SIGNAL_ONLY', False): + if not setting('SOCIAL_AUTH_CHANGE_SIGNAL_ONLY'): for name, value in details.iteritems(): # do not update username, it was already generated if name in (USERNAME, 'id', 'pk'): diff --git a/social_auth/models.py b/social_auth/models.py index 6d05201..b700329 100644 --- a/social_auth/models.py +++ b/social_auth/models.py @@ -2,9 +2,9 @@ from datetime import timedelta from django.db import models -from django.conf import settings from social_auth.fields import JSONField +from social_auth.utils import setting # If User class is overridden, it *must* provide the following fields @@ -16,8 +16,8 @@ from social_auth.fields import JSONField # def is_authenticated(): # ... -if getattr(settings, 'SOCIAL_AUTH_USER_MODEL', None): - User = models.get_model(*settings.SOCIAL_AUTH_USER_MODEL.rsplit('.', 1)) +if setting('SOCIAL_AUTH_USER_MODEL'): + User = models.get_model(*setting('SOCIAL_AUTH_USER_MODEL').rsplit('.', 1)) else: from django.contrib.auth.models import User @@ -43,7 +43,7 @@ class UserSocialAuth(models.Model): value stored or it's malformed. """ if self.extra_data: - name = getattr(settings, 'SOCIAL_AUTH_EXPIRATION', 'expires') + name = setting('SOCIAL_AUTH_EXPIRATION', 'expires') try: return timedelta(seconds=int(self.extra_data.get(name))) except (ValueError, TypeError): diff --git a/social_auth/tests/__init__.py b/social_auth/tests/__init__.py index bc143cc..74ed06f 100644 --- a/social_auth/tests/__init__.py +++ b/social_auth/tests/__init__.py @@ -1,8 +1,11 @@ -from django.conf import settings +from social_auth.utils import setting -if getattr(settings,'SOCIAL_AUTH_TEST_TWITTER', True): + +if setting('SOCIAL_AUTH_TEST_TWITTER', True): from social_auth.tests.twitter import * -if getattr(settings,'SOCIAL_AUTH_TEST_FACEBOOK', True): + +if setting('SOCIAL_AUTH_TEST_FACEBOOK', True): from social_auth.tests.facebook import * -if getattr(settings,'SOCIAL_AUTH_TEST_GOOGLE', True): + +if setting('SOCIAL_AUTH_TEST_GOOGLE', True): from social_auth.tests.google import * diff --git a/social_auth/tests/facebook.py b/social_auth/tests/facebook.py index 1eb2735..74d5b47 100644 --- a/social_auth/tests/facebook.py +++ b/social_auth/tests/facebook.py @@ -1,7 +1,6 @@ import re -from django.conf import settings - +from social_auth.utils import setting from social_auth.tests.base import SocialAuthTestsCase, FormParserByID @@ -12,8 +11,8 @@ class FacebookTestCase(SocialAuthTestsCase): def setUp(self, *args, **kwargs): super(FacebookTestCase, self).setUp(*args, **kwargs) - self.user = getattr(settings, 'TEST_FACEBOOK_USER', None) - self.passwd = getattr(settings, 'TEST_FACEBOOK_PASSWORD', None) + self.user = setting('TEST_FACEBOOK_USER') + self.passwd = setting('TEST_FACEBOOK_PASSWORD') # check that user and password are setup properly self.assertTrue(self.user) self.assertTrue(self.passwd) diff --git a/social_auth/tests/google.py b/social_auth/tests/google.py index 9f3cd1d..3beb5a9 100644 --- a/social_auth/tests/google.py +++ b/social_auth/tests/google.py @@ -1,7 +1,6 @@ import re -from django.conf import settings - +from social_auth.utils import setting from social_auth.tests.base import SocialAuthTestsCase, FormParserByID, \ FormParser, RefreshParser @@ -12,8 +11,8 @@ class GoogleTestCase(SocialAuthTestsCase): def setUp(self, *args, **kwargs): super(GoogleTestCase, self).setUp(*args, **kwargs) - self.user = getattr(settings, 'TEST_GOOGLE_USER', None) - self.passwd = getattr(settings, 'TEST_GOOGLE_PASSWORD', None) + self.user = setting('TEST_GOOGLE_USER') + self.passwd = setting('TEST_GOOGLE_PASSWORD') # check that user and password are setup properly self.assertTrue(self.user) self.assertTrue(self.passwd) @@ -65,4 +64,4 @@ class GoogleOpenIdTestLogin(GoogleTestCase): result = self.get_redirect(parser.action, parser.values, use_cookies=True) response = self.client.get(self.make_relative(result.headers['Location'])) - self.assertTrue(settings.LOGIN_REDIRECT_URL in self.make_relative(response['Location'])) + self.assertTrue(setting('LOGIN_REDIRECT_URL') in self.make_relative(response['Location'])) diff --git a/social_auth/tests/twitter.py b/social_auth/tests/twitter.py index 6cfc5c5..ee5cc23 100644 --- a/social_auth/tests/twitter.py +++ b/social_auth/tests/twitter.py @@ -1,5 +1,4 @@ -from django.conf import settings - +from social_auth.utils import setting from social_auth.tests.base import SocialAuthTestsCase, FormParserByID, \ RefreshParser @@ -10,8 +9,8 @@ class TwitterTestCase(SocialAuthTestsCase): def setUp(self, *args, **kwargs): super(TwitterTestCase, self).setUp(*args, **kwargs) - self.user = getattr(settings, 'TEST_TWITTER_USER', None) - self.passwd = getattr(settings, 'TEST_TWITTER_PASSWORD', None) + self.user = setting('TEST_TWITTER_USER') + self.passwd = setting('TEST_TWITTER_PASSWORD') # check that user and password are setup properly self.assertTrue(self.user) self.assertTrue(self.passwd) @@ -60,5 +59,5 @@ class TwitterTestLogin(TwitterTestCase): response = self.client.get(self.make_relative(parser.value)) self.assertEqual(response.status_code, 302) location = self.make_relative(response['Location']) - login_redirect = getattr(settings, 'LOGIN_REDIRECT_URL', '') + login_redirect = setting('LOGIN_REDIRECT_URL') self.assertTrue(location == login_redirect) diff --git a/social_auth/views.py b/social_auth/views.py index d1903a4..48a2446 100644 --- a/social_auth/views.py +++ b/social_auth/views.py @@ -10,7 +10,6 @@ logger = logging.getLogger(__name__) from functools import wraps -from django.conf import settings from django.http import HttpResponseRedirect, HttpResponse, \ HttpResponseServerError from django.core.urlresolvers import reverse @@ -25,22 +24,7 @@ from social_auth.utils import sanitize_redirect, setting DEFAULT_REDIRECT = setting('SOCIAL_AUTH_LOGIN_REDIRECT_URL') or \ setting('LOGIN_REDIRECT_URL') -NEW_USER_REDIRECT = setting('SOCIAL_AUTH_NEW_USER_REDIRECT_URL') -NEW_ASSOCIATION_REDIRECT = setting('SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL') -DISCONNECT_REDIRECT_URL = setting('SOCIAL_AUTH_DISCONNECT_REDIRECT_URL') -LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', settings.LOGIN_URL) -INACTIVE_USER_URL = setting('SOCIAL_AUTH_INACTIVE_USER_URL', LOGIN_ERROR_URL) -COMPLETE_URL_NAME = setting('SOCIAL_AUTH_COMPLETE_URL_NAME', - 'socialauth_complete') -ASSOCIATE_URL_NAME = setting('SOCIAL_AUTH_ASSOCIATE_URL_NAME', - 'socialauth_associate_complete') -SOCIAL_AUTH_LAST_LOGIN = setting('SOCIAL_AUTH_LAST_LOGIN', - 'social_auth_last_login_backend') -SESSION_EXPIRATION = setting('SOCIAL_AUTH_SESSION_EXPIRATION', True) -BACKEND_ERROR_REDIRECT = setting('SOCIAL_AUTH_BACKEND_ERROR_URL', - LOGIN_ERROR_URL) -SANITIZE_REDIRECTS = setting('SOCIAL_AUTH_SANITIZE_REDIRECTS', True) -ERROR_MESSAGE = setting('LOGIN_ERROR_MESSAGE', None) +LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL')) def dsa_view(redirect_name=None): @@ -70,18 +54,20 @@ def dsa_view(redirect_name=None): logger.error(unicode(e), exc_info=True, extra=dict(request=request)) - if 'django.contrib.messages' in settings.INSTALLED_APPS: + if 'django.contrib.messages' in setting('INSTALLED_APPS'): from django.contrib.messages.api import error error(request, unicode(e), extra_tags=backend_name) else: logger.warn('Messages framework not in place, some '+ 'errors have not been shown to the user.') - return HttpResponseRedirect(BACKEND_ERROR_REDIRECT) + + url = setting('SOCIAL_AUTH_BACKEND_ERROR_URL', LOGIN_ERROR_URL) + return HttpResponseRedirect(url) return wrapper return dec -@dsa_view(COMPLETE_URL_NAME) +@dsa_view(setting('SOCIAL_AUTH_COMPLETE_URL_NAME', 'socialauth_complete')) def auth(request, backend): """Start authentication process""" return auth_process(request, backend) @@ -96,7 +82,8 @@ def complete(request, backend, *args, **kwargs): @login_required -@dsa_view(ASSOCIATE_URL_NAME) +@dsa_view(setting('SOCIAL_AUTH_ASSOCIATE_URL_NAME', + 'socialauth_associate_complete')) def associate(request, backend): """Authentication starting process""" return auth_process(request, backend) @@ -116,7 +103,9 @@ def associate_complete(request, backend, *args, **kwargs): elif isinstance(user, HttpResponse): return user else: - url = NEW_ASSOCIATION_REDIRECT or redirect_value or DEFAULT_REDIRECT + url = setting('SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL') or \ + redirect_value or \ + DEFAULT_REDIRECT return HttpResponseRedirect(url) @@ -126,7 +115,7 @@ def disconnect(request, backend, association_id=None): """Disconnects given backend from current logged in user.""" backend.disconnect(request.user, association_id) url = request.REQUEST.get(REDIRECT_FIELD_NAME, '') or \ - DISCONNECT_REDIRECT_URL or \ + setting('SOCIAL_AUTH_DISCONNECT_REDIRECT_URL') or \ DEFAULT_REDIRECT return HttpResponseRedirect(url) @@ -137,10 +126,11 @@ def auth_process(request, backend): if REDIRECT_FIELD_NAME in request.REQUEST: data = request.POST if request.method == 'POST' else request.GET if REDIRECT_FIELD_NAME in data: - # Check and sanitize a user-defined GET/POST redirect_to field value. + # Check and sanitize a user-defined GET/POST redirect_to field + # value. redirect = data[REDIRECT_FIELD_NAME] - if SANITIZE_REDIRECTS: + if setting('SOCIAL_AUTH_SANITIZE_REDIRECTS', True): redirect = sanitize_redirect(request.get_host(), redirect) request.session[REDIRECT_FIELD_NAME] = redirect or DEFAULT_REDIRECT @@ -167,7 +157,7 @@ def complete_process(request, backend, *args, **kwargs): # in authenticate process social_user = user.social_user - if SESSION_EXPIRATION: + if setting('SOCIAL_AUTH_SESSION_EXPIRATION', True): # Set session expiration date if present and not disabled by # setting. Use last social-auth instance for current provider, # users can associate several accounts with a same provider. @@ -175,19 +165,23 @@ def complete_process(request, backend, *args, **kwargs): request.session.set_expiry(social_user.expiration_delta()) # store last login backend name in session - request.session[SOCIAL_AUTH_LAST_LOGIN] = social_user.provider + key = setting('SOCIAL_AUTH_LAST_LOGIN', + 'social_auth_last_login_backend') + request.session[key] = social_user.provider # Remove possible redirect URL from session, if this is a new # account, send him to the new-users-page if defined. - if NEW_USER_REDIRECT and getattr(user, 'is_new', False): - url = NEW_USER_REDIRECT + new_user_redirect = setting('SOCIAL_AUTH_NEW_USER_REDIRECT_URL') + if new_user_redirect and getattr(user, 'is_new', False): + url = new_user_redirect else: url = redirect_value or DEFAULT_REDIRECT else: - url = INACTIVE_USER_URL or LOGIN_ERROR_URL + url = setting('SOCIAL_AUTH_INACTIVE_USER_URL', LOGIN_ERROR_URL) else: - if ERROR_MESSAGE: - messages.error(request, ERROR_MESSAGE) + msg = setting('LOGIN_ERROR_MESSAGE', None) + if msg: + messages.error(request, msg) url = LOGIN_ERROR_URL return HttpResponseRedirect(url)