gestioCOF/gestion/backends.py

58 lines
2 KiB
Python
Raw Normal View History

2016-07-15 00:02:56 +02:00
# -*- coding: utf-8 -*-
2012-06-27 23:28:35 +02:00
from django.conf import settings
from django_cas_ng.backends import CASBackend
from django_cas_ng.utils import get_cas_client
from django.contrib.auth import get_user_model
2012-07-11 17:39:20 +02:00
from gestion.models import Profile
2012-07-11 17:39:20 +02:00
User = get_user_model()
2012-06-27 23:28:35 +02:00
class COFCASBackend(CASBackend):
2013-10-01 15:27:19 +02:00
def authenticate_cas(self, ticket, service, request):
"""Verifies CAS ticket and gets or creates User object"""
client = get_cas_client(service_url=service)
username, attributes, _ = client.verify_ticket(ticket)
2013-10-01 15:27:19 +02:00
if attributes:
request.session['attributes'] = attributes
if not username:
return None
# Le CAS de l'ENS accepte les logins avec des espaces au début
# et à la fin, ainsi quavec une casse variable. On normalise pour
# éviter les doublons.
username = username.strip().lower()
profiles = Profile.objects.filter(login_clipper=username)
2013-10-01 15:27:19 +02:00
if len(profiles) > 0:
# XXX. We have to deal with multiple profiles, this should not
# happen
# profile = profiles.order_by('-is_cof')[0]
profile = profiles.first()
2013-10-01 15:27:19 +02:00
user = profile.user
return user
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# user will have an "unusable" password
user = User.objects.create_user(username, '')
user.save()
return user
def authenticate(self, ticket, service, request):
2012-06-27 23:28:35 +02:00
"""Authenticates CAS ticket and retrieves user data"""
2013-10-01 15:27:19 +02:00
user = self.authenticate_cas(ticket, service, request)
if user is None:
return user
profile = user.profile
2012-06-27 23:28:35 +02:00
if not profile.login_clipper:
profile.login_clipper = user.username
profile.save()
if not user.email:
user.email = settings.CAS_EMAIL_FORMAT % profile.login_clipper
user.save()
return user