8215567f95a9adf19ac35aea446752a36a99fca0
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / authentification.py
1 # -*- encoding: utf-8 -*-
2 import hashlib, sys
3
4 import settings
5 from django.contrib.auth.backends import ModelBackend
6 from django.contrib.auth.models import User as DjangoUser, check_password
7
8 from chercheurs.models import Utilisateur as RemoteUser
9
10 class CascadeBackend(ModelBackend):
11 def authenticate(self, username=None, password=None):
12 user = None
13 email = username
14
15 # Cherche les comptes roa+locaux
16 remoteUser = localUser = None
17 try:
18 remoteUser = RemoteUser.objects.get(courriel=email, actif=True)
19 if settings.AUTH_PASSWORD_REQUIRED and not remoteUser.check_password(password):
20 remoteUser = None
21 except:
22 pass
23 try:
24 localUser = DjangoUser.objects.get (username=username)
25 except: pass
26
27 # Si on a pas besoin du mdp, on doit copier qd meme,
28 # il ne faut jamais retourner un "RemoteUser" ici
29 if not settings.AUTH_PASSWORD_REQUIRED:
30 if remoteUser and not localUser:
31 localUser = DjangoUser (username = username,
32 email = username,
33 first_name = remoteUser.prenom,
34 last_name = remoteUser.nom,
35 is_staff = settings.USERS_AS_STAFF,
36 is_active = True,
37 is_superuser = False)
38 localUser.set_password (password)
39 localUser.save ()
40 user = localUser
41 # Gestion des comptes roa vs. local
42 else:
43 # Local existe pas, on doit de tte facon le creer
44 if not localUser:
45 localUser = DjangoUser (username = username,
46 email = email,
47 is_staff = settings.USERS_AS_STAFF,
48 is_active = True,
49 is_superuser = False)
50 # Cas du compte local seul, on verifie le mot de passe
51 elif not remoteUser:
52 if localUser.check_password (password):
53 user = localUser
54 # Compte roa, on valide le mot de passe distant et on
55 # met a jour la copie locale
56 if remoteUser:
57 localUser.first_name = remoteUser.prenom
58 localUser.last_name = remoteUser.nom
59 # pass distant en md5
60 localUser.set_password (password)
61 localUser.save ()
62 user = localUser
63
64 return user