1 from django.conf import settings
2 from django.db import models
3 from django.utils.translation import ugettext_lazy as _
4 from random import Random
7 from urllib.parse import urlencode, urlparse, parse_qs, ParseResult
9 from urllib import urlencode
10 from urlparse import urlparse, ParseResult
12 from urlparse import parse_qs
13 except: # Python <2.6 compatibility
14 from cgi import parse_qs
16 __all__ = ['ServiceTicket', 'LoginTicket', 'ProxyGrantingTicket', 'ProxyTicket', 'ProxyGrantingTicketIOU']
18 class BaseTicket(models.Model):
19 ticket = models.CharField(_('ticket'), max_length=32)
20 created = models.DateTimeField(_('created'), auto_now=True)
25 def __init__(self, *args, **kwargs):
26 if 'ticket' not in kwargs:
27 kwargs['ticket'] = self._generate_ticket()
28 super(BaseTicket, self).__init__(*args, **kwargs)
30 def __unicode__(self):
33 def _generate_ticket(self, length=ticket.max_length, chars=string.ascii_letters + string.digits):
34 """ Generates a random string of the requested length. Used for creation of tickets. """
35 return u"%s-%s" % (self.prefix, ''.join(Random().sample(chars, length - (len(self.prefix) + 1))))
38 class ServiceTicket(BaseTicket):
39 user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'))
40 service = models.URLField(_('service'))
45 verbose_name = _('Service Ticket')
46 verbose_name_plural = _('Service Tickets')
48 def get_redirect_url(self):
49 parsed = urlparse(self.service)
50 query = parse_qs(parsed.query)
51 query['ticket'] = [self.ticket]
52 query = [((k, v) if len(v) > 1 else (k, v[0])) for k, v in query.items()]
53 parsed = ParseResult(parsed.scheme, parsed.netloc,
54 parsed.path, parsed.params,
55 urlencode(query), parsed.fragment)
56 return parsed.geturl()
59 class LoginTicket(BaseTicket):
63 verbose_name = _('Login Ticket')
64 verbose_name_plural = _('Login Tickets')
67 class ProxyGrantingTicket(BaseTicket):
68 serviceTicket = models.ForeignKey(ServiceTicket, null=True)
69 pgtiou = models.CharField(max_length=256, verbose_name=_('PGTiou'))
72 def __init__(self, *args, **kwargs):
73 if 'pgtiou' not in kwargs:
74 kwargs['pgtiou'] = u"PGTIOU-%s" % (''.join(Random().sample(string.ascii_letters + string.digits, 50)))
75 super(ProxyGrantingTicket, self).__init__(*args, **kwargs)
78 verbose_name = _('Proxy Granting Ticket')
79 verbose_name_plural = _('Proxy Granting Tickets')
82 class ProxyTicket(ServiceTicket):
83 proxyGrantingTicket = models.ForeignKey(ProxyGrantingTicket, verbose_name=_('Proxy Granting Ticket'))
88 verbose_name = _('Proxy Ticket')
89 verbose_name_plural = _('Proxy Tickets')
92 class ProxyGrantingTicketIOU(BaseTicket):
93 proxyGrantingTicket = models.ForeignKey(ProxyGrantingTicket, verbose_name=_('Proxy Granting Ticket'))
98 verbose_name = _('Proxy Granting Ticket IOU')
99 verbose_name_plural = _('Proxy Granting Tickets IOU')