From: Matías Aguirre Date: Wed, 9 May 2012 19:39:06 +0000 (-0300) Subject: PEP8 X-Git-Url: https://git.parisson.com/?a=commitdiff_plain;h=7e661894b1e1f471678c98dac7eef72d10f6628a;p=django-social-auth.git PEP8 --- diff --git a/social_auth/backends/__init__.py b/social_auth/backends/__init__.py index 54a933c..cc2dc20 100644 --- a/social_auth/backends/__init__.py +++ b/social_auth/backends/__init__.py @@ -17,8 +17,7 @@ from openid.consumer.consumer import Consumer, SUCCESS, CANCEL, FAILURE from openid.consumer.discover import DiscoveryFailure from openid.extensions import sreg, ax -from oauth2 import Consumer as OAuthConsumer, Token, Request as OAuthRequest, \ - SignatureMethod_HMAC_SHA1 +from oauth2 import Consumer as OAuthConsumer, Token, Request as OAuthRequest from django.db import models from django.contrib.auth import authenticate diff --git a/social_auth/backends/contrib/evernote.py b/social_auth/backends/contrib/evernote.py index cdd4fd7..2fbd943 100644 --- a/social_auth/backends/contrib/evernote.py +++ b/social_auth/backends/contrib/evernote.py @@ -31,11 +31,16 @@ class EvernoteBackend(OAuthBackend): Possible Values: {'edam_expires': ['1367525289541'], - 'edam_noteStoreUrl': ['https://sandbox.evernote.com/shard/s1/notestore'], + 'edam_noteStoreUrl': [ + 'https://sandbox.evernote.com/shard/s1/notestore' + ], 'edam_shard': ['s1'], 'edam_userId': ['123841'], 'edam_webApiUrlPrefix': ['https://sandbox.evernote.com/shard/s1/'], - 'oauth_token': ['S=s1:U=1e3c1:E=13e66dbee45:C=1370f2ac245:P=185:A=my_user:H=411443c5e8b20f8718ed382a19d4ae38']} + 'oauth_token': [ + 'S=s1:U=1e3c1:E=13e66dbee45:C=1370f2ac245:P=185:A=my_user:' \ + 'H=411443c5e8b20f8718ed382a19d4ae38' + ]} """ name = 'evernote' diff --git a/social_auth/backends/contrib/live.py b/social_auth/backends/contrib/live.py index 6d68208..a8c3d0c 100644 --- a/social_auth/backends/contrib/live.py +++ b/social_auth/backends/contrib/live.py @@ -24,11 +24,11 @@ from social_auth.backends.exceptions import AuthUnknownError # Live Connect configuration -LIVE_AUTHORIZATION_URL = 'https://login.live.com/oauth20_authorize.srf' -LIVE_ACCESS_TOKEN_URL = 'https://login.live.com/oauth20_token.srf' -LIVE_USER_DATA_URL = 'https://apis.live.net/v5.0/me' -LIVE_SERVER = 'live.com' -LIVE_DEFAULT_PERMISSIONS = ['wl.basic', 'wl.emails'] +LIVE_AUTHORIZATION_URL = 'https://login.live.com/oauth20_authorize.srf' +LIVE_ACCESS_TOKEN_URL = 'https://login.live.com/oauth20_token.srf' +LIVE_USER_DATA_URL = 'https://apis.live.net/v5.0/me' +LIVE_SERVER = 'live.com' +LIVE_DEFAULT_PERMISSIONS = ['wl.basic', 'wl.emails'] class LiveBackend(OAuthBackend): @@ -61,15 +61,15 @@ class LiveBackend(OAuthBackend): class LiveAuth(BaseOAuth2): - AUTHORIZATION_URL = LIVE_AUTHORIZATION_URL - ACCESS_TOKEN_URL = LIVE_ACCESS_TOKEN_URL - SERVER_URL = LIVE_SERVER - AUTH_BACKEND = LiveBackend - SETTINGS_KEY_NAME = 'LIVE_CLIENT_ID' + AUTHORIZATION_URL = LIVE_AUTHORIZATION_URL + ACCESS_TOKEN_URL = LIVE_ACCESS_TOKEN_URL + SERVER_URL = LIVE_SERVER + AUTH_BACKEND = LiveBackend + SETTINGS_KEY_NAME = 'LIVE_CLIENT_ID' SETTINGS_SECRET_NAME = 'LIVE_CLIENT_SECRET' - SCOPE_SEPARATOR = ',' - SCOPE_VAR_NAME = 'LIVE_EXTENDED_PERMISSIONS' - DEFAULT_SCOPE = LIVE_DEFAULT_PERMISSIONS + SCOPE_SEPARATOR = ',' + SCOPE_VAR_NAME = 'LIVE_EXTENDED_PERMISSIONS' + DEFAULT_SCOPE = LIVE_DEFAULT_PERMISSIONS def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" @@ -79,7 +79,8 @@ class LiveAuth(BaseOAuth2): try: return simplejson.load(urlopen(url)) except (ValueError, IOError): - raise AuthUnknownError("Error during profile retrieval, please, try again later") + raise AuthUnknownError('Error during profile retrieval, ' \ + 'please, try again later') # Backend definition diff --git a/social_auth/backends/contrib/mailru.py b/social_auth/backends/contrib/mailru.py index 5794303..2ac95d1 100644 --- a/social_auth/backends/contrib/mailru.py +++ b/social_auth/backends/contrib/mailru.py @@ -20,11 +20,12 @@ from hashlib import md5 from social_auth.backends import OAuthBackend, BaseOAuth2, USERNAME from social_auth.utils import setting, log -MAILRU_API_URL = 'http://www.appsmail.ru/platform/api' -MAILRU_OAUTH2_SCOPE = [''] +MAILRU_API_URL = 'http://www.appsmail.ru/platform/api' +MAILRU_OAUTH2_SCOPE = [''] EXPIRES_NAME = getattr(settings, 'SOCIAL_AUTH_EXPIRATION', 'expires') + class MailruBackend(OAuthBackend): """Mail.ru authentication backend""" name = 'mailru-oauth2' @@ -34,16 +35,21 @@ class MailruBackend(OAuthBackend): def get_user_id(self, details, response): """Return user unique id provided by Mail.ru""" return response['uid'] - + def get_user_details(self, response): """Return user details from Mail.ru request""" - values = { USERNAME: unquote(response['nick']), 'email': unquote(response['email']), - 'first_name': unquote(response['first_name']), 'last_name': unquote(response['last_name'])} - + values = { + USERNAME: unquote(response['nick']), + 'email': unquote(response['email']), + 'first_name': unquote(response['first_name']), + 'last_name': unquote(response['last_name']) + } + if values['first_name'] and values['last_name']: - values['fullname'] = "%s %s" % (values['first_name'], values['last_name']) + values['fullname'] = '%s %s' % (values['first_name'], + values['last_name']) return values - + class MailruOAuth2(BaseOAuth2): """Mail.ru OAuth2 support""" @@ -58,8 +64,9 @@ class MailruOAuth2(BaseOAuth2): def auth_complete(self, *args, **kwargs): try: - auth_result = super(MailruOAuth2, self).auth_complete(*args, **kwargs) - except HTTPError: # Mail.ru returns HTTPError 400 if cancelled + auth_result = super(MailruOAuth2, self).auth_complete(*args, + **kwargs) + except HTTPError: # Mail.ru returns HTTPError 400 if cancelled raise ValueError('Authentication cancelled') return auth_result @@ -69,30 +76,32 @@ class MailruOAuth2(BaseOAuth2): data = {'method': 'users.getInfo', 'session_key': access_token} return mailru_api(data)[0] + def mailru_sig(data): """ Calculates signature of request data """ - param_list = sorted(list(item + '=' + data[item] for item in data)) - - return md5(''.join(param_list) + settings.MAILRU_OAUTH2_CLIENT_SECRET).hexdigest() - + return md5(''.join(param_list) + + settings.MAILRU_OAUTH2_CLIENT_SECRET).hexdigest() + + def mailru_api(data): """ Calls Mail.ru REST API method http://api.mail.ru/docs/guides/restapi/ """ data.update({'app_id': settings.MAILRU_OAUTH2_CLIENT_KEY, 'secure': '1'}) data['sig'] = mailru_sig(data) - + params = urlencode(data) request = Request(MAILRU_API_URL, params) try: return simplejson.loads(urlopen(request).read()) except (TypeError, KeyError, IOError, ValueError, IndexError): - log('error', 'Could not load data from Mail.ru.', exc_info=True, extra=dict(data=params)) + log('error', 'Could not load data from Mail.ru.', + exc_info=True, extra=dict(data=params)) return None - + # Backend definition BACKENDS = { 'mailru-oauth2': MailruOAuth2 -} \ No newline at end of file +} diff --git a/social_auth/backends/contrib/odnoklassniki.py b/social_auth/backends/contrib/odnoklassniki.py index 25d271b..b88c2ec 100644 --- a/social_auth/backends/contrib/odnoklassniki.py +++ b/social_auth/backends/contrib/odnoklassniki.py @@ -1,16 +1,15 @@ """ Odnoklassniki.ru OAuth2 support -Take a look to http://dev.odnoklassniki.ru/wiki/display/ok/The+OAuth+2.0+Protocol +Take a look to: +http://dev.odnoklassniki.ru/wiki/display/ok/The+OAuth+2.0+Protocol You need to register OAuth application here: http://dev.odnoklassniki.ru/wiki/pages/viewpage.action?pageId=13992188 -Then setup your application according manual and use information from registration -mail to set settings values - +Then setup your application according manual and use information from +registration mail to set settings values. """ - from django.conf import settings from django.utils import simplejson @@ -21,11 +20,12 @@ from hashlib import md5 from social_auth.backends import OAuthBackend, BaseOAuth2, USERNAME from social_auth.utils import setting, log -ODNOKLASSNIKI_API_URL = 'http://api.odnoklassniki.ru/fb.do' -ODNOKLASSNIKI_OAUTH2_SCOPE = [''] # Enough for authentication +ODNOKLASSNIKI_API_URL = 'http://api.odnoklassniki.ru/fb.do' +ODNOKLASSNIKI_OAUTH2_SCOPE = [''] # Enough for authentication EXPIRES_NAME = getattr(settings, 'SOCIAL_AUTH_EXPIRATION', 'expires') + class OdnoklassnikiBackend(OAuthBackend): """Odnoklassniki authentication backend""" name = 'odnoklassniki' @@ -35,13 +35,17 @@ class OdnoklassnikiBackend(OAuthBackend): def get_user_id(self, details, response): """Return user unique id provided by Odnoklassniki""" return response['uid'] - + def get_user_details(self, response): """Return user details from Odnoklassniki request""" - values = { USERNAME: response['uid'], 'email': '', 'fullname': unquote(response['name']), - 'first_name': unquote(response['first_name']), 'last_name': unquote(response['last_name'])} - return values - + return { + USERNAME: response['uid'], + 'email': '', + 'fullname': unquote(response['name']), + 'first_name': unquote(response['first_name']), + 'last_name': unquote(response['last_name']) + } + class OdnoklassnikiOAuth2(BaseOAuth2): """Odnoklassniki OAuth2 support""" @@ -59,21 +63,26 @@ class OdnoklassnikiOAuth2(BaseOAuth2): data = {'access_token': access_token, 'method': 'users.getCurrentUser'} return odnoklassniki_api(data) + def odnoklassniki_sig(data): - """ Calculates signature of request data - access_token value must be included """ - - suffix = md5(data['access_token'] + settings.ODNOKLASSNIKI_OAUTH2_CLIENT_SECRET).hexdigest() - - check_list = sorted(list(item + '=' + data[item] for item in data if item != 'access_token')) - - return md5(''.join(check_list) + suffix).hexdigest() - + """Calculates signature of request data access_token value must be + included""" + suffix = md5(data['access_token'] + + settings.ODNOKLASSNIKI_OAUTH2_CLIENT_SECRET).hexdigest() + check_list = sorted(list(item + '=' + data[item] + for item in data + if item != 'access_token')) + return md5(''.join(check_list) + suffix).hexdigest() + + def odnoklassniki_api(data): """ Calls Odnoklassniki REST API method http://dev.odnoklassniki.ru/wiki/display/ok/Odnoklassniki+Rest+API """ - data.update({'application_key': settings.ODNOKLASSNIKI_OAUTH2_APP_KEY, 'format': 'JSON'}) + data.update({ + 'application_key': settings.ODNOKLASSNIKI_OAUTH2_APP_KEY, + 'format': 'JSON' + }) data['sig'] = odnoklassniki_sig(data) params = urlencode(data) @@ -81,10 +90,12 @@ def odnoklassniki_api(data): try: return simplejson.loads(urlopen(request).read()) except (TypeError, KeyError, IOError, ValueError, IndexError): - log('error', 'Could not load data from Odnoklassniki.', exc_info=True, extra=dict(data=params)) + log('error', 'Could not load data from Odnoklassniki.', + exc_info=True, extra=dict(data=params)) return None + # Backend definition BACKENDS = { 'odnoklassniki': OdnoklassnikiOAuth2 -} \ No newline at end of file +} diff --git a/social_auth/backends/contrib/vkontakte.py b/social_auth/backends/contrib/vkontakte.py index 0e4ad2a..1b45f7c 100644 --- a/social_auth/backends/contrib/vkontakte.py +++ b/social_auth/backends/contrib/vkontakte.py @@ -1,8 +1,10 @@ +# -*- coding: utf-8 -*- """ VKontakte OpenAPI and OAuth 2.0 support. -This contribution adds support for VKontakte OpenAPI and OAuth 2.0 service in the form -www.vkontakte.ru. Username is retrieved from the identity returned by server. +This contribution adds support for VKontakte OpenAPI and OAuth 2.0 service in +the form www.vkontakte.ru. Username is retrieved from the identity returned by +server. """ from django.contrib.auth import authenticate @@ -13,22 +15,26 @@ from urllib2 import urlopen from hashlib import md5 from time import time -from social_auth.backends import SocialAuthBackend, OAuthBackend, BaseAuth, BaseOAuth2, USERNAME +from social_auth.backends import SocialAuthBackend, OAuthBackend, BaseAuth, \ + BaseOAuth2, USERNAME from social_auth.utils import setting, log + # Vkontakte configuration VK_AUTHORIZATION_URL = 'http://oauth.vk.com/authorize' VK_ACCESS_TOKEN_URL = 'https://oauth.vk.com/access_token' VK_SERVER = 'vk.com' -VK_DEFAULT_DATA = ['first_name','last_name','screen_name','nickname', 'photo'] +VK_DEFAULT_DATA = ['first_name', 'last_name', 'screen_name', + 'nickname', 'photo'] -VKONTAKTE_API_URL = 'https://api.vkontakte.ru/method/' +VKONTAKTE_API_URL = 'https://api.vkontakte.ru/method/' VKONTAKTE_SERVER_API_URL = 'http://api.vkontakte.ru/api.php' -VKONTAKTE_API_VERSION = '3.0' +VKONTAKTE_API_VERSION = '3.0' USE_APP_AUTH = setting('VKONTAKTE_APP_AUTH', False) LOCAL_HTML = setting('VKONTAKTE_LOCAL_HTML', 'vkontakte.html') + class VKontakteBackend(SocialAuthBackend): """VKontakte OpenAPI authentication backend""" name = 'vkontakte' @@ -40,9 +46,13 @@ class VKontakteBackend(SocialAuthBackend): def get_user_details(self, response): """Return user details from VKontakte request""" nickname = response.GET['nickname'] - values = { USERNAME: response.GET['id'] if len(nickname) == 0 else nickname, 'email': '', 'fullname': '', - 'first_name': response.GET['first_name'], 'last_name': response.GET['last_name']} - return values + return { + USERNAME: response.GET['id'] if len(nickname) == 0 else nickname, + 'email': '', + 'fullname': '', + 'first_name': response.GET['first_name'], + 'last_name': response.GET['last_name'] + } class VKontakteAuth(BaseAuth): @@ -51,11 +61,13 @@ class VKontakteAuth(BaseAuth): APP_ID = setting('VKONTAKTE_APP_ID') def auth_html(self): - """Returns local VK authentication page, not necessary for VK to authenticate """ + """Returns local VK authentication page, not necessary for + VK to authenticate. + """ from django.template import RequestContext, loader - dict = { 'VK_APP_ID' : self.APP_ID, - 'VK_COMPLETE_URL': self.redirect } + dict = {'VK_APP_ID': self.APP_ID, + 'VK_COMPLETE_URL': self.redirect} vk_template = loader.get_template(LOCAL_HTML) context = RequestContext(self.request, dict) @@ -63,21 +75,28 @@ class VKontakteAuth(BaseAuth): return vk_template.render(context) def auth_complete(self, *args, **kwargs): - """Performs check of authentication in VKontakte, returns User if succeeded""" + """Performs check of authentication in VKontakte, returns User if + succeeded""" app_cookie = 'vk_app_' + self.APP_ID - if not 'id' in self.request.GET or not app_cookie in self.request.COOKIES: + if not 'id' in self.request.GET or \ + not app_cookie in self.request.COOKIES: raise ValueError('VKontakte authentication is not completed') - cookie_dict = dict(item.split('=') for item in self.request.COOKIES[app_cookie].split('&')) - check_str = ''.join([item + '=' + cookie_dict[item] for item in ['expire', 'mid', 'secret', 'sid']]) + cookie_dict = dict(item.split('=') for item in + self.request.COOKIES[app_cookie].split('&')) + check_str = ''.join(item + '=' + cookie_dict[item] + for item in ['expire', 'mid', 'secret', 'sid']) hash = md5(check_str + setting('VKONTAKTE_APP_SECRET')).hexdigest() - if hash != cookie_dict['sig'] or int(cookie_dict['expire']) < time() : + if hash != cookie_dict['sig'] or int(cookie_dict['expire']) < time(): raise ValueError('VKontakte authentication failed: invalid hash') else: - kwargs.update({'response': self.request, self.AUTH_BACKEND.name: True}) + kwargs.update({ + 'response': self.request, + self.AUTH_BACKEND.name: True + }) return authenticate(*args, **kwargs) @property @@ -103,10 +122,12 @@ class VKontakteOAuth2Backend(OAuthBackend): def get_user_details(self, response): """Return user details from Vkontakte account""" - return {USERNAME: response.get('screen_name'), - 'email': '', - 'first_name': response.get('first_name'), - 'last_name': response.get('last_name')} + return { + USERNAME: response.get('screen_name'), + 'email': '', + 'first_name': response.get('first_name'), + 'last_name': response.get('last_name') + } class VKontakteOAuth2(BaseOAuth2): @@ -117,15 +138,17 @@ class VKontakteOAuth2(BaseOAuth2): AUTH_BACKEND = VKontakteOAuth2Backend SETTINGS_KEY_NAME = 'VK_APP_ID' SETTINGS_SECRET_NAME = 'VK_API_SECRET' - # Look at http://vk.com/developers.php?oid=-1&p=%D0%9F%D1%80%D0%B0%D0%B2%D0%B0_%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF%D0%B0_%D0%BF%D1%80%D0%B8%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9 + # Look at: + # http://vk.com/developers.php?oid=-17680044&p=Application_Access_Rights SCOPE_VAR_NAME = 'VK_EXTRA_SCOPE' def get_scope(self): - return setting(VKontakteOAuth2.SCOPE_VAR_NAME) or setting('VKONTAKTE_OAUTH2_EXTRA_SCOPE') + return setting(VKontakteOAuth2.SCOPE_VAR_NAME) or \ + setting('VKONTAKTE_OAUTH2_EXTRA_SCOPE') def user_data(self, access_token, response, *args, **kwargs): """Loads user data from service""" - fields = ','.join(VK_DEFAULT_DATA + setting('VK_EXTRA_DATA',[])) + fields = ','.join(VK_DEFAULT_DATA + setting('VK_EXTRA_DATA', [])) params = {'access_token': access_token, 'fields': fields, 'uids': response.get('user_id')} @@ -134,7 +157,7 @@ class VKontakteOAuth2(BaseOAuth2): if data: data = data.get('response')[0] - data['user_photo'] = data.get('photo') # Backward compatibility + data['user_photo'] = data.get('photo') # Backward compatibility return data @@ -154,7 +177,7 @@ class VKontakteAppAuth(VKontakteOAuth2): return super(VKontakteAppAuth, self).auth_complete(*args, **kwargs) - def user_profile(self, user_id, access_token = None): + def user_profile(self, user_id, access_token=None): data = {'uids': user_id, 'fields': 'photo'} if access_token: @@ -164,7 +187,7 @@ class VKontakteAppAuth(VKontakteOAuth2): return profiles[0] if profiles else None - def is_app_user(self, user_id, access_token = None): + def is_app_user(self, user_id, access_token=None): """Returns app usage flag from VKontakte API""" data = {'uid': user_id} @@ -175,11 +198,12 @@ class VKontakteAppAuth(VKontakteOAuth2): return vkontakte_api('isAppUser', data).get('response', 0) def application_auth(self): - required_params = ('is_app_user', 'viewer_id', 'access_token', 'api_id', ) + required_params = ('is_app_user', 'viewer_id', 'access_token', + 'api_id') for param in required_params: if not param in self.request.REQUEST: - return (False, None,) + return (False, None) auth_key = self.request.REQUEST.get('auth_key') @@ -190,20 +214,24 @@ class VKontakteAppAuth(VKontakteOAuth2): USE_APP_AUTH['key']])).hexdigest() if check_key != auth_key: - raise ValueError('VKontakte authentication failed: invalid auth key') + raise ValueError('VKontakte authentication failed: invalid ' \ + 'auth key') user_check = USE_APP_AUTH.get('user_mode', 0) user_id = self.request.REQUEST.get('viewer_id') if user_check: - is_user = self.request.REQUEST.get('is_app_user') if user_check == 1 else self.is_app_user(user_id) + is_user = self.request.REQUEST.get('is_app_user') \ + if user_check == 1 else self.is_app_user(user_id) if not int(is_user): - return (True, None,) + return (True, None) data = {'response': self.user_profile(user_id), 'user_id': user_id} - return (True, authenticate(**{'response': data, self.AUTH_BACKEND.name: True})) + return (True, authenticate(**{ + 'response': data, self.AUTH_BACKEND.name: True + })) def _api_get_val_fun(name, conf): @@ -214,7 +242,7 @@ def _api_get_val_fun(name, conf): def vkontakte_api(method, data): - """ Calls VKontakte OpenAPI method + """Calls VKontakte OpenAPI method http://vkontakte.ru/apiclub, http://vkontakte.ru/pages.php?o=-1&p=%C2%FB%EF%EE%EB%ED%E5%ED%E8%E5%20%E7%E0%EF%F0%EE%F1%EE%E2%20%EA%20API """ @@ -225,13 +253,13 @@ def vkontakte_api(method, data): data['v'] = VKONTAKTE_API_VERSION if not 'api_id' in data: - data['api_id'] = _api_get_val_fun('id','VKONTAKTE_APP_ID') + data['api_id'] = _api_get_val_fun('id', 'VKONTAKTE_APP_ID') data['method'] = method data['format'] = 'json' url = VKONTAKTE_SERVER_API_URL - secret = _api_get_val_fun('key','VKONTAKTE_APP_SECRET') + secret = _api_get_val_fun('key', 'VKONTAKTE_APP_SECRET') param_list = sorted(list(item + '=' + data[item] for item in data)) data['sig'] = md5(''.join(param_list) + secret).hexdigest() @@ -243,9 +271,11 @@ def vkontakte_api(method, data): try: return simplejson.load(urlopen(url)) except (TypeError, KeyError, IOError, ValueError, IndexError): - log('error', 'Could not load data from VKontakte.', exc_info=True, extra=dict(data=data)) + log('error', 'Could not load data from VKontakte.', + exc_info=True, extra=dict(data=data)) return None + # Backend definition BACKENDS = { 'vkontakte': VKontakteAuth, diff --git a/social_auth/backends/contrib/yahoo.py b/social_auth/backends/contrib/yahoo.py index 2e1b3f2..df94e1a 100644 --- a/social_auth/backends/contrib/yahoo.py +++ b/social_auth/backends/contrib/yahoo.py @@ -27,9 +27,9 @@ from social_auth.backends.exceptions import AuthUnknownError # Google OAuth base configuration YAHOO_OAUTH_SERVER = 'api.login.yahoo.com' -REQUEST_TOKEN_URL = 'https://api.login.yahoo.com/oauth/v2/get_request_token' -AUTHORIZATION_URL = 'https://api.login.yahoo.com/oauth/v2/request_auth' -ACCESS_TOKEN_URL = 'https://api.login.yahoo.com/oauth/v2/get_token' +REQUEST_TOKEN_URL = 'https://api.login.yahoo.com/oauth/v2/get_request_token' +AUTHORIZATION_URL = 'https://api.login.yahoo.com/oauth/v2/request_auth' +ACCESS_TOKEN_URL = 'https://api.login.yahoo.com/oauth/v2/get_token' class YahooOAuthBackend(OAuthBackend): @@ -61,24 +61,26 @@ class YahooOAuthBackend(OAuthBackend): class YahooOAuth(ConsumerBasedOAuth): - AUTHORIZATION_URL = AUTHORIZATION_URL - REQUEST_TOKEN_URL = REQUEST_TOKEN_URL - ACCESS_TOKEN_URL = ACCESS_TOKEN_URL - SERVER_URL = YAHOO_OAUTH_SERVER - AUTH_BACKEND = YahooOAuthBackend - SETTINGS_KEY_NAME = 'YAHOO_CONSUMER_KEY' + AUTHORIZATION_URL = AUTHORIZATION_URL + REQUEST_TOKEN_URL = REQUEST_TOKEN_URL + ACCESS_TOKEN_URL = ACCESS_TOKEN_URL + SERVER_URL = YAHOO_OAUTH_SERVER + AUTH_BACKEND = YahooOAuthBackend + SETTINGS_KEY_NAME = 'YAHOO_CONSUMER_KEY' SETTINGS_SECRET_NAME = 'YAHOO_CONSUMER_SECRET' def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" guid = self._get_guid(access_token) - url = 'http://social.yahooapis.com/v1/user/%s/profile?format=json' % guid + url = 'http://social.yahooapis.com/v1/user/%s/profile?format=json' \ + % guid request = self.oauth_request(access_token, url) response = self.fetch_response(request) try: return simplejson.loads(response)['profile'] except ValueError: - raise AuthUnknownError("Error during profile retrieval, please, try again later") + raise AuthUnknownError('Error during profile retrieval, ' \ + 'please, try again later') def _get_guid(self, access_token): """ @@ -92,7 +94,9 @@ class YahooOAuth(ConsumerBasedOAuth): json = simplejson.loads(response) return json['guid']['value'] except ValueError: - raise AuthUnknownError("Error during user id retrieval, please, try again later") + raise AuthUnknownError('Error during user id retrieval, ' \ + 'please, try again later') + # Backend definition BACKENDS = { diff --git a/social_auth/backends/contrib/yandex.py b/social_auth/backends/contrib/yandex.py index 7f519f1..95a3eab 100644 --- a/social_auth/backends/contrib/yandex.py +++ b/social_auth/backends/contrib/yandex.py @@ -8,7 +8,7 @@ If username is not specified, OpenID 2.0 url used for authentication. """ from django.utils import simplejson -from urllib import urlencode, unquote +from urllib import urlencode from urllib2 import urlopen from urlparse import urlparse, urlsplit @@ -70,6 +70,7 @@ class YaruBackend(OAuthBackend): ] def get_user_details(self, response): + """Return user details from Yandex account""" name = response['name'] last_name = '' @@ -80,11 +81,12 @@ class YaruBackend(OAuthBackend): else: first_name = name - """Return user details from Yandex account""" - return { USERNAME: get_username_from_url(response.get('links')), - 'email': response.get('email', ''), - 'first_name': first_name, 'last_name': last_name, - } + return { + USERNAME: get_username_from_url(response.get('links')), + 'email': response.get('email', ''), + 'first_name': first_name, + 'last_name': last_name, + } class YaruAuth(BaseOAuth2): @@ -110,7 +112,8 @@ class YaruAuth(BaseOAuth2): try: return simplejson.load(urlopen(url)) except (ValueError, IndexError): - log('error', 'Could not load data from Yandex.', exc_info=True, extra=dict(data=params)) + log('error', 'Could not load data from Yandex.', + exc_info=True, extra=dict(data=params)) return None @@ -127,7 +130,8 @@ class YandexOAuth2(YaruAuth): return setting('YANDEX_OAUTH2_API_URL') def user_data(self, access_token, response, *args, **kwargs): - reply = super(YandexOAuth2, self).user_data(access_token, response, args, kwargs) + reply = super(YandexOAuth2, self).user_data(access_token, + response, args, kwargs) if reply: if isinstance(reply, list) and len(reply) >= 1: @@ -138,10 +142,15 @@ class YandexOAuth2(YaruAuth): elif 'avatar' in reply: userpic = reply['avatar'].get('Portrait') - reply.update({"id":reply["id"].split("/")[-1], "access_token": access_token, "userpic": userpic or ''}) + reply.update({ + 'id': reply['id'].split("/")[-1], + 'access_token': access_token, + 'userpic': userpic or '' + }) return reply + # Backend definition BACKENDS = { 'yandex': YandexAuth, diff --git a/social_auth/backends/exceptions.py b/social_auth/backends/exceptions.py index d49a589..654ff22 100644 --- a/social_auth/backends/exceptions.py +++ b/social_auth/backends/exceptions.py @@ -1,5 +1,6 @@ from django.utils.translation import ugettext + class SocialAuthBaseException(ValueError): """Base class for pipeline exceptions.""" pass @@ -27,7 +28,8 @@ class AuthFailed(AuthException): if self.message == 'access_denied': return ugettext(u'Authentication process was cancelled') else: - return ugettext(u'Authentication failed: %s') % super(AuthFailed, self).__unicode__() + return ugettext(u'Authentication failed: %s') % \ + super(AuthFailed, self).__unicode__() class AuthCanceled(AuthException): diff --git a/social_auth/backends/facebook.py b/social_auth/backends/facebook.py index c0ebc90..a6511f0 100644 --- a/social_auth/backends/facebook.py +++ b/social_auth/backends/facebook.py @@ -100,7 +100,8 @@ class FacebookAuth(BaseOAuth2): try: response = cgi.parse_qs(urlopen(url).read()) except HTTPError: - raise AuthFailed(self, 'There was an error authenticating the app') + raise AuthFailed(self, 'There was an error authenticating ' \ + 'the app') access_token = response['access_token'][0] if 'expires' in response: @@ -110,8 +111,9 @@ class FacebookAuth(BaseOAuth2): response = load_signed_request(self.data.get('signed_request')) if response is not None: - access_token = response.get('access_token') or response.get('oauth_token') \ - or self.data.get('access_token') + access_token = response.get('access_token') or \ + response.get('oauth_token') or \ + self.data.get('access_token') if 'expires' in response: expires = response['expires'] @@ -120,13 +122,14 @@ class FacebookAuth(BaseOAuth2): data = self.user_data(access_token) if not isinstance(data, dict): - # From time to time Facebook responds back a JSON with just False - # as value, the reason is still unknown, but since the data is - # needed (it contains the user ID used to identify the account on - # further logins), this app cannot allow it to continue with the - # auth process. - raise AuthUnknownError(self, 'An error ocurred while retrieving '\ - 'users Facebook data') + # From time to time Facebook responds back a JSON with just + # False as value, the reason is still unknown, but since the + # data is needed (it contains the user ID used to identify the + # account on further logins), this app cannot allow it to + # continue with the auth process. + raise AuthUnknownError(self, 'An error ocurred while ' \ + 'retrieving users Facebook ' \ + 'data') data['access_token'] = access_token # expires will not be part of response if offline access @@ -156,24 +159,28 @@ def base64_url_decode(data): data += '=' * (4 - (len(data) % 4)) return base64.urlsafe_b64decode(data) + def base64_url_encode(data): return base64.urlsafe_b64encode(data).rstrip('=') - + + def load_signed_request(signed_request): try: sig, payload = signed_request.split(u'.', 1) sig = base64_url_decode(sig) data = simplejson.loads(base64_url_decode(payload)) - expected_sig = hmac.new( - setting('FACEBOOK_API_SECRET'), msg=payload, digestmod=hashlib.sha256).digest() + expected_sig = hmac.new(setting('FACEBOOK_API_SECRET'), + msg=payload, + digestmod=hashlib.sha256).digest() # allow the signed_request to function for upto 1 day if sig == expected_sig and \ data[u'issued_at'] > (time.time() - 86400): - return data - except ValueError, ex: - pass # ignore if can't split on dot + return data + except ValueError: + pass # ignore if can't split on dot + # Backend definition BACKENDS = {