1 from django.contrib.auth.models import User
2 from django.db import models
3 from django.utils.translation import ugettext_lazy as _
4 from random import Random
9 if hasattr(urlparse, 'parse_qs'):
10 parse_qs = urlparse.parse_qs
12 # Python <2.6 compatibility
13 from cgi import parse_qs
15 __all__ = ['ServiceTicket', 'LoginTicket', 'ProxyGrantingTicket', 'ProxyTicket', 'ProxyGrantingTicketIOU']
17 class BaseTicket(models.Model):
18 ticket = models.CharField(_('ticket'), max_length=32)
19 created = models.DateTimeField(_('created'), auto_now=True)
24 def __init__(self, *args, **kwargs):
25 if 'ticket' not in kwargs:
26 kwargs['ticket'] = self._generate_ticket()
27 super(BaseTicket, self).__init__(*args, **kwargs)
29 def __unicode__(self):
32 def _generate_ticket(self, length=ticket.max_length, chars=string.ascii_letters + string.digits):
33 """ Generates a random string of the requested length. Used for creation of tickets. """
34 return u"%s-%s" % (self.prefix, ''.join(Random().sample(chars, length - (len(self.prefix) + 1))))
37 class ServiceTicket(BaseTicket):
38 user = models.ForeignKey(User, verbose_name=_('user'))
39 service = models.URLField(_('service'), verify_exists=False)
44 verbose_name = _('Service Ticket')
45 verbose_name_plural = _('Service Tickets')
47 def get_redirect_url(self):
48 parsed = urlparse.urlparse(self.service)
49 query = parse_qs(parsed.query)
50 query['ticket'] = [self.ticket]
51 query = [((k, v) if len(v) > 1 else (k, v[0])) for k, v in query.iteritems()]
52 parsed = urlparse.ParseResult(parsed.scheme, parsed.netloc,
53 parsed.path, parsed.params,
54 urllib.urlencode(query), parsed.fragment)
55 return parsed.geturl()
58 class LoginTicket(BaseTicket):
62 verbose_name = _('Login Ticket')
63 verbose_name_plural = _('Login Tickets')
66 class ProxyGrantingTicket(BaseTicket):
67 serviceTicket = models.ForeignKey(ServiceTicket, null=True)
68 pgtiou = models.CharField(max_length=256, verbose_name=_('PGTiou'))
71 def __init__(self, *args, **kwargs):
72 if 'pgtiou' not in kwargs:
73 kwargs['pgtiou'] = u"PGTIOU-%s" % (''.join(Random().sample(string.ascii_letters + string.digits, 50)))
74 super(ProxyGrantingTicket, self).__init__(*args, **kwargs)
77 verbose_name = _('Proxy Granting Ticket')
78 verbose_name_plural = _('Proxy Granting Tickets')
81 class ProxyTicket(ServiceTicket):
82 proxyGrantingTicket = models.ForeignKey(ProxyGrantingTicket, verbose_name=_('Proxy Granting Ticket'))
87 verbose_name = _('Proxy Ticket')
88 verbose_name_plural = _('Proxy Tickets')
91 class ProxyGrantingTicketIOU(BaseTicket):
92 proxyGrantingTicket = models.ForeignKey(ProxyGrantingTicket, verbose_name=_('Proxy Granting Ticket'))
97 verbose_name = _('Proxy Granting Ticket IOU')
98 verbose_name_plural = _('Proxy Granting Tickets IOU')