django-allauth-ens/allauth_ens/providers/clipper/provider.py
2018-04-18 22:31:24 +02:00

87 lines
2.7 KiB
Python

# -*- coding: utf-8 -*-
import ldap
from allauth.account.models import EmailAddress
from allauth.socialaccount.providers.base import ProviderAccount
from allauth_cas.providers import CASProvider
from django.conf import settings
class ClipperAccount(ProviderAccount):
pass
class ClipperProvider(CASProvider):
id = 'clipper'
name = 'Clipper'
account_class = ClipperAccount
def extract_email(self, data):
uid, extra = data
return '{}@clipper.ens.fr'.format(uid.strip().lower())
def extract_uid(self, data):
# Normalize UID
uid, _ = data
uid = uid.lower().strip()
return uid
def extract_common_fields(self, data):
def get_names(clipper):
assert clipper.isalnum()
try:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_NEVER)
l = ldap.initialize("ldaps://ldap.spi.ens.fr:636")
l.set_option(ldap.OPT_REFERRALS, 0)
l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
l.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
l.set_option(ldap.OPT_X_TLS_DEMAND, True)
l.set_option(ldap.OPT_DEBUG_LEVEL, 255)
l.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
l.set_option(ldap.OPT_TIMEOUT, 10)
info = l.search_s('dc=spi,dc=ens,dc=fr',
ldap.SCOPE_SUBTREE,
('(uid=%s)' % (clipper,)),
[str("cn"), ])
if len(info) > 0:
fullname = info[0][1].get('cn', [''])[0].decode("utf-8")
first_name, last_name = fullname.split(' ', 1)
return first_name, last_name
except ldap.LDAPError:
pass
return '', ''
common = super(ClipperProvider, self).extract_common_fields(data)
fn, ln = get_names(common['username'])
common['email'] = self.extract_email(data)
common['name'] = fn
common['last_name'] = ln
return common
def extract_email_addresses(self, data):
return [
EmailAddress(
email=self.extract_email(data),
verified=True, primary=True,
),
]
def extract_extra_data(self, data):
extra_data = super(ClipperProvider, self).extract_extra_data(data)
extra_data['email'] = self.extract_email(data)
return extra_data
def message_suggest_caslogout_on_logout(self, request):
return (
self.get_settings()
.get('MESSAGE_SUGGEST_CASLOGOUT_ON_LOGOUT', True)
)
provider_classes = [ClipperProvider]