7f63cd4afd7f5599fb49c09316d98bf557a81f50
[django-cas-provider.git] / cas_provider / views.py
1 from django.conf import settings
2 from django.contrib.auth import authenticate, 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 django.utils.translation import ugettext_lazy as _
8 from forms import LoginForm
9 from models import ServiceTicket, LoginTicket
10 from utils import create_service_ticket
11
12
13 __all__ = ['login', 'validate', 'logout', 'service_validate']
14
15
16 def login(request, template_name='cas/login.html', success_redirect='/accounts/'):
17     service = request.GET.get('service', None)
18     if request.user.is_authenticated():
19         if service is not None:
20             ticket = create_service_ticket(request.user, service)
21             if service.find('?') == -1:
22                 return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
23             else:
24                 return HttpResponseRedirect(service + '&ticket=' + ticket.ticket)
25         else:
26             return HttpResponseRedirect(success_redirect)
27     errors = []
28     if request.method == 'POST':
29         username = request.POST.get('username', None)
30         password = request.POST.get('password', None)
31         service = request.POST.get('service', None)
32         lt = request.POST.get('lt', None)
33
34         try:
35             login_ticket = LoginTicket.objects.get(ticket=lt)
36         except:
37             errors.append(_('Login ticket expired. Please try again.'))
38         else:
39             login_ticket.delete()
40             user = authenticate(username=username, password=password)
41             if user is not None:
42                 if user.is_active:
43                     auth_login(request, user)
44                     if service is not None:
45                         ticket = create_service_ticket(user, service)
46                         return HttpResponseRedirect(service + '?ticket=' + ticket.ticket)
47                     else:
48                         return HttpResponseRedirect(success_redirect)
49                 else:
50                     errors.append(_('This account is disabled.'))
51             else:
52                     errors.append(_('Incorrect username and/or password.'))
53     form = LoginForm(service)
54     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
55
56
57 def validate(request):
58     """Validate ticket via CAS v.1 protocol"""
59     service = request.GET.get('service', None)
60     ticket_string = request.GET.get('ticket', None)
61     if service is not None and ticket_string is not None:
62         try:
63             ticket = ServiceTicket.objects.get(ticket=ticket_string)
64             username = ticket.user.username
65             ticket.delete()
66             return HttpResponse("yes\r\n%s\r\n" % username)
67         except:
68             pass
69     return HttpResponse("no\r\n\r\n")
70
71
72 def logout(request, template_name='cas/logout.html'):
73     url = request.GET.get('url', None)
74     auth_logout(request)
75     return render_to_response(template_name, {'url': url}, context_instance=RequestContext(request))
76
77
78 def service_validate(request):
79     """Validate ticket via CAS v.2 protocol"""
80     service = request.GET.get('service', None)
81     ticket_string = request.GET.get('ticket', None)
82     if service is None or ticket_string is None:
83         return _cas2_error_response(u'INVALID_REQUEST', u'Not all required parameters were sent.')
84
85     try:
86         ticket = ServiceTicket.objects.get(ticket=ticket_string)
87     except ServiceTicket.DoesNotExist:
88         return _cas2_error_response(u'INVALID_TICKET', u'The provided ticket is invalid.')
89
90     if settings.CAS_CHECK_SERVICE and ticket.service != service:
91         ticket.delete()
92         return _cas2_error_response('INVALID_SERVICE', u'Service is invalid')
93
94     username = ticket.user.username
95     ticket.delete()
96     return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
97         <cas:authenticationSuccess>
98             <cas:user>%(username)s</cas:user>
99         </cas:authenticationSuccess>
100     </cas:serviceResponse>''' % {'username': username}, mimetype='text/xml')
101
102
103 def _cas2_error_response(code, message):
104     return HttpResponse(u''''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
105             <cas:authenticationFailure code="%s">
106                 %s
107             </cas:authenticationFailure>
108         </cas:serviceResponse>''', mimetype='text/xml')