login.py 3.56 KB
Newer Older
1 2 3
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
4
# LOGIN.PY -- Gère l'interface d'authentification à l'aide des modèles Django.
5
#
6
# Copyright (C) 2009-2010 Nicolas Dandrimont
7
# Authors: Nicolas Dandrimont <olasd@crans.org>
8
# Censor: Antoine Durand-Gasselin <adg@crans.org>
9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# 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/>.

23
import settings, ldap
24 25
from django.contrib.auth.models import Group, User
from django.contrib.auth.backends import ModelBackend
26 27 28 29 30 31 32 33
from django.utils.importlib import import_module

# Pour se connecter à la base ldap
import sys
sys.path.append("/usr/scripts/lc_ldap")
from lc_ldap import lc_ldap

conn_pool = import_module('conn_pool', 'intranet')
34

35 36
class LDAPUserBackend(ModelBackend):
    """Authentifie un utilisateur à l'aide de la base LDAP"""
Nicolas Dandrimont's avatar
Nicolas Dandrimont committed
37

38
    supports_anonymous_user = False
39

40 41 42
    def authenticate(self, username=None, password=None):
        """Authentifie l'utilisateur sur la base LDAP. Crée un
        utilisateur django s'il n'existe pas encore."""
43

44 45
        if not username or not password:
            return None
46

47
        try:
Daniel Stan's avatar
Daniel Stan committed
48
            conn = lc_ldap(user = username, cred = password, test=settings.LDAP_TEST)
49
            ldap_user = conn.search(dn = conn.dn, scope = ldap.SCOPE_BASE)[0]
50 51
        except IndexError:
            return None
52 53
        except ldap.INVALID_CREDENTIALS:
            return None
54

55 56 57 58 59 60 61 62 63 64 65
        # On stocke les utilisateurs dans la base django comme "uid@crans.org"
        django_username = '%s@crans.org' % username
        try:
            user = User.objects.get(username=django_username)
        except User.DoesNotExist:
            user = User(username=django_username, password="LDAP Backend User!")
        user.save()
        conn_pool.CONNS[django_username] = conn
        self.refresh_droits(user, ldap_user)
        self.refresh_fields(user, ldap_user)
        return user
66 67 68 69 70

    def refresh_droits(self, user, cl_user):
        """Rafraîchit les droits de l'utilisateur django `user' depuis
        l'utilisateur LDAP `cl_user'"""

71
        cl_droits = [x.value for x in cl_user['droits']]
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
        if u"Nounou" in cl_droits:
            user.is_staff = True
            user.is_superuser = True
        else:
            user.is_staff = False
            user.is_superuser = False

        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)

        user.groups.add(*groups)
        user.save()

    def refresh_fields(self, user, cl_user):
        """Rafraîchit les champs correspondants à l'utilisateur (nom,
        prénom, email)"""

92 93 94
        user.first_name = unicode(cl_user['prenom'][0])
        user.last_name = unicode(cl_user['nom'][0])
        user.email = "%s@crans.org" % unicode(cl_user['mail'][0])
95 96

        user.save()
97

98 99 100 101 102 103
    def get_user(self, uid):
        """Récupère l'objet django correspondant à l'uid"""
        try:
            return User.objects.get(pk=uid)
        except User.DoesNotExist:
            return None