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']
11 def _verify_cas1(ticket, service):
12 """Verifies CAS 1.0 authentication ticket.
14 Returns username on success and None on failure.
17 params = {'ticket': ticket, 'service': service}
18 url = (urljoin(settings.CAS_SERVER_URL, 'validate') + '?' +
22 verified = page.readline().strip()
24 return page.readline().strip()
31 def _verify_cas2(ticket, service):
32 """Verifies CAS 2.0+ XML-based authentication ticket.
34 Returns username on success and None on failure.
38 from lxml import etree as ElementTree
40 from elementtree import ElementTree
42 params = {'ticket': ticket, 'service': service}
43 url = (urljoin(settings.CAS_SERVER_URL, 'serviceValidate') + '?' +
47 response = page.read()
48 tree = ElementTree.fromstring(response)
49 if tree[0].tag.endswith('authenticationSuccess'):
50 return tree[0][0].text
63 _PROTOCOLS = {'1': _verify_cas1, '2': _verify_cas2}
65 if settings.CAS_VERSION not in _PROTOCOLS:
66 raise ValueError('Unsupported CAS_VERSION %r' % settings.CAS_VERSION)
68 _verify = _PROTOCOLS[settings.CAS_VERSION]
71 class CASBackend(object):
72 """CAS authentication backend"""
74 def authenticate(self, ticket, service):
75 """Verifies CAS ticket and gets or creates User object"""
77 username = _verify(ticket, service)
81 user = User.objects.get(username__iexact=username)
82 except User.DoesNotExist:
83 # user will have an "unusable" password
84 user = User.objects.create_user(username, '')
88 def get_user(self, user_id):
89 """Retrieve the user's entry in the User model if it exists"""
92 return User.objects.get(pk=user_id)
93 except User.DoesNotExist: