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

22

23
import ldap
24
from django.contrib.auth.models import Group, User, Permission
25
from django.contrib.auth.backends import ModelBackend
Daniel STAN's avatar
Daniel STAN committed
26
from django.views.decorators.debug import sensitive_variables
27
from django.contrib.contenttypes.models import ContentType
28 29

# Pour se connecter à la base ldap
Vincent Le gallic's avatar
Vincent Le gallic committed
30
import lc_ldap.shortcuts
31

32
from intranet import conn_pool, settings
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
GROUPES_SPECIAUX = { # Dictionnaire de groupe spéciaux à attribuer selon le test correspondant
"crans_paiement_ok": lambda u: u.paiement_ok(),
"crans_imprimeur_club": lambda u: u.imprimeur_clubs(),
"crans_respo_club": lambda u: u.clubs(),
"crans_adherent": lambda u: 'aid' in u,
"crans_club": lambda u: 'cid' in u,
}


def get_or_create_cransgroup(name):
    """ Crée le groupe crans_name avec le droit crans_name.
    """
    group, created = Group.objects.get_or_create(name=name)
    if created:
        user_type = ContentType.objects.get(app_label="auth", model="user")
        permission,created = Permission.objects.get_or_create(codename=name,
                                       name=name,
                                       content_type=user_type)
        group.permissions.add(permission)
        group.save()
    return group

56 57 58 59 60 61 62 63 64 65 66
def refresh_droits(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
67 68 69 70
    if u"Apprenti" in cl_droits:
            user.is_staff = True
    if u"Imprimeur" in cl_droits:
            user.is_staff = True
71 72 73

    groups = []
    for cl_droit in cl_droits:
74 75 76 77
        groups.append(get_or_create_cransgroup(name=u"crans_%s" % cl_droit.lower()))
    for group in GROUPES_SPECIAUX:
        if GROUPES_SPECIAUX[group](cl_user):
            groups.append(get_or_create_cransgroup(name=group))
78 79 80 81 82 83 84 85 86

    user.groups = [ group for group in user.groups.all() if not group.name.startswith('crans_') ]
    user.groups.add(*groups)
    user.save()

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

87
    user.first_name = unicode(cl_user.get('prenom', [u"club"])[0])
88
    user.last_name = unicode(cl_user['nom'][0])
89
    mail = unicode(cl_user.get('mail', cl_user['uid'])[0])
90 91 92 93 94 95
    if '@' not in mail:  # Ne devrait pas arriver (pour migration)
        mail += u'@crans.org'
    user.email = mail

    user.save()

96 97 98 99 100
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)

101 102
class LDAPUserBackend(ModelBackend):
    """Authentifie un utilisateur à l'aide de la base LDAP"""
Nicolas Dandrimont's avatar
Nicolas Dandrimont committed
103

104
    supports_anonymous_user = False
105

Daniel STAN's avatar
Daniel STAN committed
106
    @sensitive_variables('password')
107 108 109
    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."""
110

111 112
        if not username or not password:
            return None
Vincent Le gallic's avatar
Vincent Le gallic committed
113
        shortcut = lc_ldap.shortcuts.lc_ldap_test if settings.BASE_LDAP_TEST else lc_ldap.shortcuts.lc_ldap
114
        try:
Vincent Le gallic's avatar
Vincent Le gallic committed
115
            conn = shortcut(user = username, cred = password)
116 117
            myself = conn.search(dn = conn.dn, scope = ldap.SCOPE_BASE)
            ldap_user = myself[0]
118 119
        except IndexError:
            return None
120 121
        except ldap.INVALID_CREDENTIALS:
            return None
122

123 124 125 126 127 128 129 130
        # 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
131 132
        refresh_droits(user, ldap_user)
        refresh_fields(user, ldap_user)
133
        return user
134 135 136 137 138 139 140

    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
141