use django-allauth for authentication using oauth2 with authentic2

This commit is contained in:
Benjamin Dauvergne 2014-03-07 17:45:48 +01:00
commit 402dff8f9c
6 changed files with 82 additions and 0 deletions

0
__init__.py Normal file
View File

1
models.py Normal file
View File

@ -0,0 +1 @@
# Create your models here.

33
provider.py Normal file
View File

@ -0,0 +1,33 @@
from allauth.socialaccount import providers
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
from allauth.account.models import EmailAddress
class Authentic2Account(ProviderAccount):
def to_str(self):
return self.account.uid
class Authentic2Provider(OAuth2Provider):
id = 'authentic2'
name = 'Authentic2'
package = 'portail_citoyen2.allauth_authentic2'
account_class = Authentic2Account
def extract_uid(self, data):
return str(data['username'])
def extract_common_fields(self, data):
return dict(email=data.get('email'),
username=data.get('username'),
name=data.get('displayname'))
def extract_email_addresses(self, data):
ret = [EmailAddress(email=data['email'],
verified=True,
primary=True)]
return ret
providers.registry.register(Authentic2Provider)

0
tests.py Normal file
View File

5
urls.py Normal file
View File

@ -0,0 +1,5 @@
from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns
from .provider import Authentic2Provider
urlpatterns = default_urlpatterns(Authentic2Provider)

43
views.py Normal file
View File

@ -0,0 +1,43 @@
import urlparse
import requests
from django.core.exceptions import ImproperlyConfigured
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import Authentic2Provider
class Authentic2OAuth2Adapter(OAuth2Adapter):
provider_id = Authentic2Provider.id
def get_url(self):
provider = self.get_provider()
try:
return provider.get_settings()['URL']
except IndexError:
raise ImproperlyConfigured('The authentic2 provider needs an URL defined in settings')
@property
def access_token_url(self):
return urlparse.urljoin(self.get_url(), 'access_token')
@property
def authorize_url(self):
return urlparse.urljoin(self.get_url(), 'authorize')
@property
def profile_url(self):
return urlparse.urljoin(self.get_url(), 'user-info')
def complete_login(self, request, app, token, **kwargs):
resp = requests.get(self.profile_url,
params={'access_token': token.token})
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(Authentic2OAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(Authentic2OAuth2Adapter)