82ebd099fce05db95b1685422b12e76bada8ad50
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / authentification.py
1 # -*- encoding: utf-8 -*-
2 import re
3 from datamaster_modeles.models import Authentification as AUFUser, Employe
4 from django.conf import settings
5 from django.contrib.auth.backends import ModelBackend
6 from django.contrib.auth.models import User
7 from hashlib import md5
8
9 def get_django_user_for_email(email):
10 """Retourne un utilisateur Django avec le courriel donné.
11
12 S'il y a déjà un utilisateur avec ce courriel, on s'assure qu'il est activé.
13
14 Sinon, on crée un nouvel utilisateur."""
15 try:
16 user = User.objects.get(email=email)
17 if not user.is_active:
18 user.is_active = True
19 user.save()
20 except User.DoesNotExist:
21 username = email.split('@')[0]
22 username = re.sub('\W', '_', username)[:30]
23 i = 1
24 while User.objects.filter(username=username).count() > 0:
25 suffix = '_' + str(i)
26 username = username[:30-len(suffix)] + suffix
27 i += 1
28 # XXX: possible race condition here...
29 user = User.objects.create_user(username, email)
30 user.save()
31 return user
32
33 class AUFBackend(ModelBackend):
34 """Authentifie un employé de l'AUF."""
35
36 def authenticate(self, username=None, password=None):
37 try:
38 auf_user = AUFUser.objects.get(courriel=username, actif=True)
39 except AUFUser.DoesNotExist:
40 return None
41 if not settings.AUTH_PASSWORD_REQUIRED or md5(password).hexdigest() == auf_user.motdepasse:
42 return get_django_user_for_email(username)
43
44 class EmailBackend(ModelBackend):
45 """Authentifie un utilisateur par son courriel."""
46
47 def authenticate(self, username=None, password=None):
48 try:
49 user = User.objects.get(email=username, is_active=True)
50 except User.DoesNotExist:
51 return None
52 if not settings.AUTH_PASSWORD_REQUIRED or user.check_password(password):
53 return user