452c071b50a64f37cf983c51c5f6deb6c0ed5a43
[django-cas-provider.git] / cas_provider / views.py
1 from django.conf import settings
2 from django.contrib.auth import login as auth_login, \
3     logout as auth_logout
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 def login(request, template_name='cas/login.html', \
15                 success_redirect=settings.LOGIN_REDIRECT_URL):
16     service = request.GET.get('service', None)
17     if request.user.is_authenticated():
18         if service is not None:
19             ticket = ServiceTicket.objects.create(service=service, user=request.user)
20             return HttpResponseRedirect(ticket.get_redirect_url())
21         else:
22             return HttpResponseRedirect(success_redirect)
23     if request.method == 'POST':
24         form = LoginForm(request.POST)
25         if form.is_valid():
26             user = form.get_user()
27             auth_login(request, user)
28             service = form.cleaned_data.get('service')
29             if service is not None:
30                 ticket = ServiceTicket.objects.create(service=service, user=user)
31                 success_redirect = ticket.get_redirect_url()
32             return HttpResponseRedirect(success_redirect)
33     else:
34         form = LoginForm(initial={
35             'service': service,
36             'lt': LoginTicket.objects.create()
37         })
38     return render_to_response(template_name, {
39         'form': form,
40         'errors': form.get_errors()
41     }, context_instance=RequestContext(request))
42
43
44 def validate(request):
45     """Validate ticket via CAS v.1 protocol"""
46     service = request.GET.get('service', None)
47     ticket_string = request.GET.get('ticket', None)
48     if service is not None and ticket_string is not None:
49         try:
50             ticket = ServiceTicket.objects.get(ticket=ticket_string)
51             username = ticket.user.username
52             ticket.delete()
53             return HttpResponse("yes\r\n%s\r\n" % username)
54         except:
55             pass
56     return HttpResponse("no\r\n\r\n")
57
58
59 def logout(request, template_name='cas/logout.html'):
60     url = request.GET.get('url', None)
61     auth_logout(request)
62     return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))
63
64
65 def service_validate(request):
66     """Validate ticket via CAS v.2 protocol"""
67     service = request.GET.get('service', None)
68     ticket_string = request.GET.get('ticket', None)
69     if service is None or ticket_string is None:
70         return _cas2_error_response(u'INVALID_REQUEST', u'Not all required parameters were sent.')
71
72     try:
73         ticket = ServiceTicket.objects.get(ticket=ticket_string)
74     except ServiceTicket.DoesNotExist:
75         return _cas2_error_response(u'INVALID_TICKET', u'The provided ticket is invalid.')
76
77     if settings.CAS_CHECK_SERVICE and ticket.service != service:
78         ticket.delete()
79         return _cas2_error_response('INVALID_SERVICE', u'Service is invalid')
80
81     username = ticket.user.username
82     ticket.delete()
83     return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
84         <cas:authenticationSuccess>
85             <cas:user>%(username)s</cas:user>
86         </cas:authenticationSuccess>
87     </cas:serviceResponse>''' % {'username': username}, mimetype='text/xml')
88
89
90 def _cas2_error_response(code, message):
91     return HttpResponse(u''''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
92             <cas:authenticationFailure code="%s">
93                 %s
94             </cas:authenticationFailure>
95         </cas:serviceResponse>''', mimetype='text/xml')