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