1 """CAS authentication backend"""
3 from urllib import urlencode, urlopen
4 from urlparse import urljoin
5 from django.conf import settings
6 from django_cas.models import User
8 __all__ = ['CASBackend']
10 def _verify_cas1(ticket, service):
11 """Verifies CAS 1.0 authentication ticket.
13 Returns username on success and None on failure.
16 params = {'ticket': ticket, 'service': service}
17 url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' +
21 verified = page.readline().strip()
23 return page.readline().strip()
30 def _verify_cas2(ticket, service):
31 """Verifies CAS 2.0+ XML-based authentication ticket.
33 Returns username on success and None on failure.
37 from lxml import etree as ElementTree
39 from elementtree import ElementTree
41 params = {'ticket': ticket, 'service': service}
42 url = (urljoin(settings.CAS_SERVER_URL, 'serviceValidate') + '?' +
46 response = page.read()
47 tree = ElementTree.fromstring(response)
48 if tree[0].tag.endswith('authenticationSuccess'):
49 return tree[0][0].text
62 _PROTOCOLS = {'1': _verify_cas1, '2': _verify_cas2}
64 if settings.CAS_VERSION not in _PROTOCOLS:
65 raise ValueError('Unsupported CAS_VERSION %r' % settings.CAS_VERSION)
67 _verify = _PROTOCOLS[settings.CAS_VERSION]
70 class CASBackend(object):
71 """CAS authentication backend"""
73 def authenticate(self, ticket, service):
74 """Verifies CAS ticket and gets or creates User object"""
76 username = _verify(ticket, service)
80 user = User.objects.get(username__iexact = username)
81 except User.DoesNotExist:
82 # user will have an "unusable" password
83 user = User.objects.create_user(username, '')
87 def get_user(self, user_id):
88 """Retrieve the user's entry in the User model if it exists"""
91 return User.objects.get(pk = user_id)
92 except User.DoesNotExist: