forked from DGNum/gestioCOF
78 lines
2.5 KiB
Python
78 lines
2.5 KiB
Python
from django.contrib.sites.models import Site
|
|
from django.conf import settings
|
|
from django_cas.backends import CASBackend, _verify as CASverify
|
|
from django_cas.models import User
|
|
from django.db import models, connection
|
|
|
|
from gestioncof.models import CofProfile
|
|
|
|
class COFCASBackend(CASBackend):
|
|
def authenticate_cas(self, ticket, service, request):
|
|
"""Verifies CAS ticket and gets or creates User object"""
|
|
|
|
username, attributes = CASverify(ticket, service)
|
|
if attributes:
|
|
request.session['attributes'] = attributes
|
|
if not username:
|
|
return None
|
|
profiles = CofProfile.objects.filter(login_clipper = username)
|
|
if len(profiles) > 0:
|
|
profile = profiles.order_by('-is_cof')[0]
|
|
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):
|
|
"""Authenticates CAS ticket and retrieves user data"""
|
|
user = self.authenticate_cas(ticket, service, request)
|
|
if user is None:
|
|
return user
|
|
try:
|
|
profile = user.get_profile()
|
|
except CofProfile.DoesNotExist:
|
|
profile, created = CofProfile.objects.get_or_create(user = user)
|
|
profile.save()
|
|
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()
|
|
if profile.is_buro and not user.is_superuser:
|
|
user.is_superuser = True
|
|
user.is_staff = True
|
|
user.save()
|
|
return user
|
|
|
|
def context_processor (request):
|
|
'''Append extra data to the context of the given request'''
|
|
data = {
|
|
"user": request.user,
|
|
"site": Site.objects.get_current(),
|
|
}
|
|
return data
|
|
|
|
def lock_table(*models):
|
|
query = "LOCK TABLES "
|
|
for i, model in enumerate(models):
|
|
table = model._meta.db_table
|
|
if i > 0: query += ", "
|
|
query += "%s WRITE" % table
|
|
cursor = connection.cursor()
|
|
cursor.execute(query)
|
|
row = cursor.fetchone()
|
|
return row
|
|
|
|
def unlock_tables(*models):
|
|
cursor = connection.cursor()
|
|
cursor.execute("UNLOCK TABLES")
|
|
row = cursor.fetchone()
|
|
return row
|
|
|
|
unlock_table = unlock_tables
|