Commit | Line | Data |
---|---|---|
cc755b15 CR |
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: | |
6c86ad81 | 24 | remoteUser = RemoteUser.objects.get (email=email, password=md5pass) |
0adf6560 | 25 | except: |
cc755b15 CR |
26 | pass |
27 | try: | |
28 | localUser = DjangoUser.objects.get (username=username) | |
29 | except: pass | |
30 | ||
31 | # Si on a pas besoin du mdp, on doit copier qd meme, | |
32 | # il ne faut jamais retourner un "RemoteUser" ici | |
33 | if not settings.AUTH_PASSWORD_REQUIRED: | |
34 | if remoteUser and not localUser: | |
35 | localUser = DjangoUser (username = username, | |
36 | email = email, | |
37 | first_name = remoteUser.first_name, | |
38 | last_name = remoteUser.last_name, | |
39 | is_staff = False, | |
40 | is_active = True, | |
41 | is_superuser = False) | |
42 | localUser.set_password (password) | |
43 | localUser.save () | |
44 | user = localUser | |
45 | # Gestion des comptes roa vs. local | |
46 | else: | |
47 | # Local existe pas, on doit de tte facon le creer | |
48 | if not localUser: | |
49 | localUser = DjangoUser (username = username, | |
50 | email = email, | |
51 | is_staff = False, | |
52 | is_active = True, | |
53 | is_superuser = False) | |
54 | # Cas du compte local seul, on verifie le mot de passe | |
55 | elif not remoteUser: | |
56 | if localUser.check_password (password): | |
57 | user = localUser | |
58 | # Compte roa, on valide le mot de passe distant et on | |
59 | # met a jour la copie locale | |
60 | if remoteUser: | |
61 | localUser.first_name = remoteUser.first_name | |
62 | localUser.last_name = remoteUser.last_name | |
63 | # pass distant en md5 | |
6c86ad81 CR |
64 | localUser.set_password (password) |
65 | localUser.save () | |
66 | user = localUser | |
cc755b15 CR |
67 | |
68 | return user |