login.py 5.59 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
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,
}
41 42 43 44 45 46 47 48 49 50 51
USER_TYPE = ContentType.objects.get(app_label="auth", model="user")
CRANS_MULTIMACHINES,created = Permission.objects.get_or_create(codename=u"crans_multimachines",
                                       name=u"crans_multimachines",
                                       content_type=USER_TYPE)

DROITS_SPECIAUX = { # Dictionnaire de groupe devant contenir les droits correspondant
"crans_cableur": [CRANS_MULTIMACHINES],
"crans_imprimeur": [CRANS_MULTIMACHINES],
"crans_apprenti": [CRANS_MULTIMACHINES],
"crans_bureau": [CRANS_MULTIMACHINES],
}
52 53 54 55 56 57 58 59 60


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:
        permission,created = Permission.objects.get_or_create(codename=name,
                                       name=name,
61
                                       content_type=USER_TYPE)
62
        group.permissions.add(permission)
63 64
	if name in DROITS_SPECIAUX:
		group.permissions.add(*DROITS_SPECIAUX[name])
65 66 67
        group.save()
    return group

68 69 70 71 72 73 74 75 76 77 78
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
79 80 81 82
    if u"Apprenti" in cl_droits:
            user.is_staff = True
    if u"Imprimeur" in cl_droits:
            user.is_staff = True
83 84 85

    groups = []
    for cl_droit in cl_droits:
86 87 88 89
        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))
90 91 92 93 94 95 96 97 98

    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)"""

99
    user.first_name = unicode(cl_user.get('prenom', [u"club"])[0])
100
    user.last_name = unicode(cl_user['nom'][0])
101
    mail = unicode(cl_user.get('mail', cl_user['uid'])[0])
102 103 104 105 106 107
    if '@' not in mail:  # Ne devrait pas arriver (pour migration)
        mail += u'@crans.org'
    user.email = mail

    user.save()

108 109 110 111 112
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)

113 114
class LDAPUserBackend(ModelBackend):
    """Authentifie un utilisateur à l'aide de la base LDAP"""
Nicolas Dandrimont's avatar
Nicolas Dandrimont committed
115

116
    supports_anonymous_user = False
117

Daniel STAN's avatar
Daniel STAN committed
118
    @sensitive_variables('password')
119 120 121
    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."""
122

123 124
        if not username or not password:
            return None
Vincent Le gallic's avatar
Vincent Le gallic committed
125
        shortcut = lc_ldap.shortcuts.lc_ldap_test if settings.BASE_LDAP_TEST else lc_ldap.shortcuts.lc_ldap
126
        try:
Vincent Le gallic's avatar
Vincent Le gallic committed
127
            conn = shortcut(user = username, cred = password)
128 129
            myself = conn.search(dn = conn.dn, scope = ldap.SCOPE_BASE)
            ldap_user = myself[0]
130 131
        except IndexError:
            return None
132 133
        except ldap.INVALID_CREDENTIALS:
            return None
134

135 136 137 138 139 140 141 142
        # 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
143 144
        refresh_droits(user, ldap_user)
        refresh_fields(user, ldap_user)
145
        return user
146 147 148 149 150 151 152

    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
153