AttrCASBackend: Save user instance only when necessary
[fnpdjango.git] / fnpdjango / auth_backends.py
1 from django.conf import settings
2 from django_cas.backends import CASBackend
3
4 attr_map = getattr(settings, 'CAS_USER_ATTRS_MAP', {
5     'email': 'email',
6     'firstname': 'first_name',
7     'lastname': 'last_name',
8 })
9
10 class AttrCASBackend(CASBackend):
11     def authenticate(self, ticket, service, request):
12         user = super(AttrCASBackend, self).authenticate(ticket, service, request)
13         dirty = False
14         for attr, value in request.session.get('attributes', {}).items():
15             try:
16                 local_attr = attr_map[attr]
17             except KeyError:
18                 pass
19             else:
20                 if getattr(user, local_attr, None) != value:
21                     setattr(user, local_attr, value)
22                     dirty = True
23         if dirty:
24             user.save()
25         return user
26