Première version : mise en route du suivi.
[auf_roa_authentification_backend.git] / auf_roa_authentification_backend / 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 AufUser 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 remoteUser = RemoteUser.objects.get (email=email)
25 except Exception as inst:
26 #print type(inst) # the exception instance
27 #print inst.args # arguments stored in .args
28 #print inst
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.first_name,
41 last_name = remoteUser.last_name,
42 is_staff = False,
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 = False,
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.first_name
65 localUser.last_name = remoteUser.last_name
66 # pass distant en md5
67 if remoteUser.password == md5pass:
68 localUser.set_password (password)
69 localUser.save ()
70 user = localUser
71
72 return user