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
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'
# 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):
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"""
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
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'
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"""
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
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
+}
"""
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
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'
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"""
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)
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
+}
+# -*- 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
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'
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):
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)
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
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):
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')}
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
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:
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}
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')
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):
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
"""
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()
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,
# 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):
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):
"""
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 = {
"""
from django.utils import simplejson
-from urllib import urlencode, unquote
+from urllib import urlencode
from urllib2 import urlopen
from urlparse import urlparse, urlsplit
]
def get_user_details(self, response):
+ """Return user details from Yandex account"""
name = response['name']
last_name = ''
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):
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
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:
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,
from django.utils.translation import ugettext
+
class SocialAuthBaseException(ValueError):
"""Base class for pipeline exceptions."""
pass
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):
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:
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']
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
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 = {