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
10 __all__ = ['ServiceTicket', 'LoginTicket']
13 class BaseTicket(models.Model):
14 ticket = models.CharField(_('ticket'), max_length=32)
15 created = models.DateTimeField(_('created'), auto_now=True)
20 def __init__(self, *args, **kwargs):
21 if 'ticket' not in kwargs:
22 kwargs['ticket'] = self._generate_ticket()
23 super(BaseTicket, self).__init__(*args, **kwargs)
25 def __unicode__(self):
28 def _generate_ticket(self, length=29, chars=string.ascii_letters + string.digits):
29 """ Generates a random string of the requested length. Used for creation of tickets. """
30 return u"%s-%s" % (self.prefix, ''.join(Random().sample(chars, length)))
33 class ServiceTicket(BaseTicket):
34 user = models.ForeignKey(User, verbose_name=_('user'))
35 service = models.URLField(_('service'), verify_exists=False)
40 verbose_name = _('Service Ticket')
41 verbose_name_plural = _('Service Tickets')
43 def get_redirect_url(self):
44 parsed = urlparse.urlparse(self.service)
45 query = urlparse.parse_qs(parsed.query)
46 query['ticket'] = [self.ticket]
47 query = [ ((k, v) if len(v) > 1 else (k, v[0])) for k, v in query.iteritems()]
48 parsed = urlparse.ParseResult(parsed.scheme, parsed.netloc,
49 parsed.path, parsed.params,
50 urllib.urlencode(query), parsed.fragment)
51 return parsed.geturl()
54 class LoginTicket(BaseTicket):
59 verbose_name = _('Login Ticket')
60 verbose_name_plural = _('Login Tickets')