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