5d09912b3be5e1e6a210f350723f04f147339aa8
[cas.git] / provider / cas_provider / models.py
1 from django.db import models
2 from django.contrib.auth.models import User
3 from django.conf import settings
4 from django.core.urlresolvers import get_callable
5
6 from cas_provider.etree import etree, register_namespace, ElementRoot
7
8 class ServiceTicket(models.Model):
9     user = models.ForeignKey(User)
10     service = models.URLField(verify_exists=False)
11     ticket = models.CharField(max_length=256)
12     created = models.DateTimeField(auto_now=True)
13     
14     def __unicode__(self):
15         return "%s (%s) - %s" % (self.user.username, self.service, self.created)
16         
17 class LoginTicket(models.Model):
18     ticket = models.CharField(max_length=32)
19     created = models.DateTimeField(auto_now=True)
20     
21     def __unicode__(self):
22         return "%s - %s" % (self.ticket, self.created)
23
24 CAS_URI = 'http://www.yale.edu/tp/cas'
25 register_namespace('cas', CAS_URI)
26 CAS = '{%s}' % CAS_URI
27
28 def auth_success_response(user):
29     attrs = {}
30     if settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK:
31         callback = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK)
32         attrs = callback(user)
33     
34     response = ElementRoot(CAS + 'serviceResponse')
35     auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
36     username = etree.SubElement(auth_success, CAS + 'user')
37     username.text = user.username
38     for name, value in attrs.items():
39         element = etree.SubElement(auth_success, name)
40         element.text = value
41     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')