7a3e69037cac98d017475365e6c3d29275aa7d80
[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                 form_class=LoginForm):
31     service = request.GET.get('service', None)
32     if request.user.is_authenticated():
33         if service is not None:
34             if request.GET.get('warn', False):
35                 return render_to_response(warn_template_name, {
36                     'service': service,
37                     'warn': False
38                 }, context_instance=RequestContext(request))
39             ticket = ServiceTicket.objects.create(service=service, user=request.user)
40             return HttpResponseRedirect(ticket.get_redirect_url())
41         else:
42             return HttpResponseRedirect(success_redirect)
43     if request.method == 'POST':
44         form = form_class(data=request.POST, request=request)
45         if form.is_valid():
46             user = form.get_user()
47             auth_login(request, user)
48             service = form.cleaned_data.get('service')
49             if service is not None:
50                 ticket = ServiceTicket.objects.create(service=service, user=user)
51                 success_redirect = ticket.get_redirect_url()
52             return HttpResponseRedirect(success_redirect)
53     else:
54         form = form_class(request=request, initial={
55             'service': service,
56             'lt': LoginTicket.objects.create()
57         })
58     if hasattr(request, 'session') and hasattr(request.session, 'set_test_cookie'):
59         request.session.set_test_cookie()
60     return render_to_response(template_name, {
61         'form': form,
62         'errors': form.get_errors() if hasattr(form, 'get_errors') else None,
63     }, context_instance=RequestContext(request))
64
65
66 def validate(request):
67     """Validate ticket via CAS v.1 protocol"""
68     service = request.GET.get('service', None)
69     ticket_string = request.GET.get('ticket', None)
70     if service is not None and ticket_string is not None:
71         #renew = request.GET.get('renew', True)
72         #if not renew:
73         # TODO: check user SSO session
74         try:
75             ticket = ServiceTicket.objects.get(ticket=ticket_string)
76             assert ticket.service == service
77             username = ticket.user.username
78             ticket.delete()
79             return HttpResponse("yes\n%s\n" % username)
80         except:
81             pass
82     return HttpResponse("no\n\n")
83
84
85 def logout(request, template_name='cas/logout.html', \
86                 auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
87     url = request.GET.get('url', None)
88     if request.user.is_authenticated():
89         auth_logout(request)
90         if url and auto_redirect:
91             return HttpResponseRedirect(url)
92     return render_to_response(template_name, {'url': url}, \
93                               context_instance=RequestContext(request))
94
95
96 def service_validate(request):
97     """Validate ticket via CAS v.2 protocol"""
98     service = request.GET.get('service', None)
99     ticket_string = request.GET.get('ticket', None)
100     if service is None or ticket_string is None:
101         return _cas2_error_response(INVALID_REQUEST)
102
103     try:
104         ticket = ServiceTicket.objects.get(ticket=ticket_string)
105     except ServiceTicket.DoesNotExist:
106         return _cas2_error_response(INVALID_TICKET)
107
108     if ticket.service != service:
109         ticket.delete()
110         return _cas2_error_response(INVALID_SERVICE)
111
112     user = ticket.user
113     ticket.delete()
114     return _cas2_sucess_response(user)
115
116
117 def _cas2_error_response(code):
118     return HttpResponse(u''''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
119             <cas:authenticationFailure code="%(code)s">
120                 %(message)s
121             </cas:authenticationFailure>
122         </cas:serviceResponse>''' % {
123             'code': code,
124             'message': dict(ERROR_MESSAGES).get(code)
125     }, mimetype='text/xml')
126
127
128 def _cas2_sucess_response(user):
129     return HttpResponse(auth_success_response(user), mimetype='text/xml')
130
131
132 def auth_success_response(user):
133     from attribute_formatters import CAS, NSMAP, etree
134
135     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
136     auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
137     username = etree.SubElement(auth_success, CAS + 'user')
138     username.text = user.username
139
140     if settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK:
141         callback = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK)
142         attrs = callback(user)
143         if len(attrs) > 0:
144             formater = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
145             formater(auth_success, attrs)
146     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')