c9a44dbd0b3a88d52b0bb08c20c3939af83d096a
[django-cas-provider.git] / cas_provider / views.py
1 from django.conf import settings
2 from django.contrib.auth import login as auth_login, logout as auth_logout
3 from django.core.urlresolvers import get_callable
4 from django.http import HttpResponse, HttpResponseRedirect
5 from django.shortcuts import render_to_response
6 from django.template import RequestContext
7 from forms import LoginForm
8 from models import ServiceTicket, LoginTicket
9
10
11 __all__ = ['login', 'validate', 'logout', 'service_validate']
12
13
14 INVALID_TICKET = 'INVALID_TICKET'
15 INVALID_SERVICE = 'INVALID_SERVICE'
16 INVALID_REQUEST = 'INVALID_REQUEST'
17 INTERNAL_ERROR = 'INTERNAL_ERROR'
18
19 ERROR_MESSAGES = (
20     (INVALID_TICKET, u'The provided ticket is invalid.'),
21     (INVALID_SERVICE, u'Service is invalid'),
22     (INVALID_REQUEST, u'Not all required parameters were sent.'),
23     (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
24 )
25
26
27 def login(request, template_name='cas/login.html', \
28                 success_redirect=settings.LOGIN_REDIRECT_URL,
29                 warn_template_name='cas/warn.html'):
30     service = request.GET.get('service', None)
31     if request.user.is_authenticated():
32         if service is not None:
33             if request.GET.get('warn', False):
34                 return render_to_response(warn_template_name, {
35                     'service': service,
36                     'warn': False
37                 }, context_instance=RequestContext(request))
38             ticket = ServiceTicket.objects.create(service=service, user=request.user)
39             return HttpResponseRedirect(ticket.get_redirect_url())
40         else:
41             return HttpResponseRedirect(success_redirect)
42     if request.method == 'POST':
43         form = LoginForm(request.POST)
44         if form.is_valid():
45             user = form.get_user()
46             auth_login(request, user)
47             service = form.cleaned_data.get('service')
48             if service is not None:
49                 ticket = ServiceTicket.objects.create(service=service, user=user)
50                 success_redirect = ticket.get_redirect_url()
51             return HttpResponseRedirect(success_redirect)
52     else:
53         form = LoginForm(initial={
54             'service': service,
55             'lt': LoginTicket.objects.create()
56         })
57     return render_to_response(template_name, {
58         'form': form,
59         'errors': form.get_errors()
60     }, context_instance=RequestContext(request))
61
62
63 def validate(request):
64     """Validate ticket via CAS v.1 protocol"""
65     service = request.GET.get('service', None)
66     ticket_string = request.GET.get('ticket', None)
67     if service is not None and ticket_string is not None:
68         #renew = request.GET.get('renew', True)
69         #if not renew:
70         # TODO: check user SSO session
71         try:
72             ticket = ServiceTicket.objects.get(ticket=ticket_string)
73             assert ticket.service == service
74             username = ticket.user.username
75             ticket.delete()
76             return HttpResponse("yes\n%s\n" % username)
77         except:
78             pass
79     return HttpResponse("no\n\n")
80
81
82 def logout(request, template_name='cas/logout.html', \
83                 auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
84     url = request.GET.get('url', None)
85     if request.user.is_authenticated():
86         auth_logout(request)
87         if url and auto_redirect:
88             return HttpResponseRedirect(url)
89     return render_to_response(template_name, {'url': url}, \
90                               context_instance=RequestContext(request))
91
92
93 def service_validate(request):
94     """Validate ticket via CAS v.2 protocol"""
95     service = request.GET.get('service', None)
96     ticket_string = request.GET.get('ticket', None)
97     if service is None or ticket_string is None:
98         return _cas2_error_response(INVALID_REQUEST)
99
100     try:
101         ticket = ServiceTicket.objects.get(ticket=ticket_string)
102     except ServiceTicket.DoesNotExist:
103         return _cas2_error_response(INVALID_TICKET)
104
105     if ticket.service != service:
106         ticket.delete()
107         return _cas2_error_response(INVALID_SERVICE)
108
109     user = ticket.user
110     ticket.delete()
111     return _cas2_sucess_response(user)
112
113
114 def _cas2_error_response(code):
115     return HttpResponse(u''''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
116             <cas:authenticationFailure code="%(code)s">
117                 %(message)s
118             </cas:authenticationFailure>
119         </cas:serviceResponse>''' % {
120             'code': code,
121             'message': dict(ERROR_MESSAGES).get(code)
122     }, mimetype='text/xml')
123
124
125 def _cas2_sucess_response(user):
126     return HttpResponse(auth_success_response(user), mimetype='text/xml')
127
128
129 def auth_success_response(user):
130     from attribute_formatters import CAS, NSMAP, etree
131
132     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
133     auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
134     username = etree.SubElement(auth_success, CAS + 'user')
135     username.text = user.username
136
137     if settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK:
138         callback = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK)
139         attrs = callback(user)
140         if len(attrs) > 0:
141             formater = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
142             formater(auth_success, attrs)
143     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')