Commit 95d8b630 authored by root's avatar root

Adaptation du cas pour django 1.8 : utilisation de django-cas-ng

parent d08f60e4
# -*- coding: utf-8 -*-
#
# LOGIN.PY -- Gère l'interface d'authentification à l'aide des modèles Django.
#
# Copyright (C) 2009-2010 Nicolas Dandrimont
# Authors: Nicolas Dandrimont <olasd@crans.org>
# Censor: Antoine Durand-Gasselin <adg@crans.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import settings, ldap
from django.contrib.auth.models import Group, User
from django.contrib.auth.backends import ModelBackend
from django.utils.importlib import import_module
from django_cas.backends import CASBackend, _verify
from django_cas.models import User
import login
conn_pool = import_module('conn_pool', 'intranet')
class CransCASBackend(CASBackend):
"""Authentifie un utilisateur à l'aide de la base LDAP"""
supports_anonymous_user = False
supports_inactive_user = False
def authenticate(self, ticket, service, request):
"""Authentifie l'utilisateur sur la base LDAP. Crée un
utilisateur django s'il n'existe pas encore."""
username, attributes = _verify(ticket, service)
# Si _verify plante, username contient None.
if username is None or not username:
return None
# Sanitize username
username = username.lower()
if attributes:
request.session['attributes'] = attributes
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# user will have an "unusable" password
user = User.objects.create_user(unicode(username), '')
user.save()
request.session.set_expiry(settings.SESSION_EXPIRY)
django_username = user.username
try:
ldap_user = conn_pool.get_user(user)
except IndexError:
return None
except ldap.INVALID_CREDENTIALS:
return None
login.refresh_droits(user, ldap_user)
login.refresh_fields(user, ldap_user)
return user
def refresh_droits(self, user, cl_user):
"""Rafraîchit les droits de l'utilisateur django `user' depuis
l'utilisateur LDAP `cl_user'"""
cl_droits = [x.value for x in cl_user.get('droits', [])]
if u"Nounou" in cl_droits:
user.is_staff = True
user.is_superuser = True
else:
user.is_staff = False
user.is_superuser = False
if u"Apprenti" in cl_droits:
user.is_staff = True
if u"Imprimeur" in cl_droits:
user.is_staff = True
groups = []
for cl_droit in cl_droits:
group, created = Group.objects.get_or_create(name="crans_%s" % cl_droit.lower())
group.save()
groups.append(group)
if cl_user.paiement_ok():
group, created = Group.objects.get_or_create(name="crans_paiement_ok")
group.save()
groups.append(group)
if cl_user.imprimeur_clubs():
group, created = Group.objects.get_or_create(name="crans_imprimeur_club")
group.save()
groups.append(group)
if cl_user.clubs():
group, created = Group.objects.get_or_create(name="crans_respo_club")
group.save()
groups.append(group)
user.groups = [ group for group in user.groups.all() if not group.name.startswith('crans_') ]
user.groups.add(*groups)
user.save()
def refresh_fields(self, user, cl_user):
"""Rafraîchit les champs correspondants à l'utilisateur (nom,
prénom, email)"""
user.first_name = unicode(cl_user['prenom'][0])
user.last_name = unicode(cl_user['nom'][0])
mail = unicode(cl_user['mail'][0])
if '@' not in mail: # Ne devrait pas arriver (pour migration)
mail += u'@crans.org'
user.email = mail
user.save()
......@@ -24,6 +24,8 @@ import settings, ldap
from django.contrib.auth.models import Group, User
from django.contrib.auth.backends import ModelBackend
from django.utils.importlib import import_module
from django_cas_ng.signals import cas_user_authenticated
# Pour se connecter à la base ldap
import lc_ldap.shortcuts
......@@ -82,6 +84,11 @@ def refresh_fields(user, cl_user):
user.save()
def post_cas_login(sender, user, created, attributes, ticket, service, **kwargs):
ldap_user = conn_pool.get_user(user)
refresh_droits(user, ldap_user)
refresh_fields(user, ldap_user)
class LDAPUserBackend(ModelBackend):
"""Authentifie un utilisateur à l'aide de la base LDAP"""
......@@ -121,3 +128,6 @@ class LDAPUserBackend(ModelBackend):
return User.objects.get(pk=uid)
except User.DoesNotExist:
return None
cas_user_authenticated.connect(login.post_cas_login)
......@@ -191,7 +191,9 @@ MIDDLEWARE_CLASSES = (
if CAS_ENABLED:
MIDDLEWARE_CLASSES += (
'django_cas.middleware.CASMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
MIDDLEWARE_CLASSES += (
......@@ -229,7 +231,7 @@ CAS_VERSION = '3'
# En dehors d'un usage personnel, on se permet d'activer le backend LDAP
# (reste à voir si on se connecte à la vraie ou à la base de test)
if CAS_ENABLED:
AUTHENTICATION_BACKENDS.append('cas_login.CransCASBackend')
AUTHENTICATION_BACKENDS.append('django_cas_ng.backends.CASBackend')
elif LOCATION != 'perso':
AUTHENTICATION_BACKENDS.append('login.LDAPUserBackend')
......
......@@ -9,8 +9,8 @@ from django.contrib import admin
admin.autodiscover()
if settings.CAS_ENABLED:
login_url = url('^login', 'django_cas.views.login', name="login")
logout_url = url('^logout', 'django_cas.views.logout', name="logout")
login_url = url(r'^login$', 'django_cas_ng.views.login', name="login")
logout_url = url(r'^logout$', 'django_cas_ng.views.logout', name="logout")
else:
login_url = url('^login', protect(django.contrib.auth.views.login), {'template_name': 'login.html'}, name="login")
logout_url = url('^logout', 'django.contrib.auth.views.logout_then_login', name ="logout")
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment