7aeaafb00b62379532de4aa587d05d98fe4662c8
[django-cas-provider.git] / cas_provider / views.py
1 import logging
2 logger = logging.getLogger('cas_provider.views')
3 import urllib
4
5 import logging
6 from urllib import urlencode
7 import urllib2
8 import urlparse
9 from functools import wraps
10
11 from django.utils.decorators import available_attrs
12 from django.views.decorators.debug import sensitive_post_parameters
13 from django.views.decorators.cache import cache_control
14 from django.utils.cache import patch_cache_control
15 from django.views.decorators.csrf import csrf_protect
16
17 from django.http import HttpResponse, HttpResponseRedirect
18 from django.conf import settings
19 from django.contrib.auth import login as auth_login, logout as auth_logout
20 from django.core.urlresolvers import get_callable
21 from django.shortcuts import render_to_response
22 from django.template import RequestContext
23 from django.contrib.auth import authenticate
24 from django.core.urlresolvers import reverse
25
26 from lxml import etree
27 from cas_provider.attribute_formatters import NSMAP, CAS
28 from cas_provider.models import ProxyGrantingTicket, ProxyTicket
29 from cas_provider.models import ServiceTicket
30
31 from cas_provider.exceptions import SameEmailMismatchedPasswords
32 from cas_provider.forms import LoginForm, MergeLoginForm
33
34 from . import signals
35
36 __all__ = ['login', 'validate', 'logout', 'service_validate']
37
38 INVALID_TICKET = 'INVALID_TICKET'
39 INVALID_SERVICE = 'INVALID_SERVICE'
40 INVALID_REQUEST = 'INVALID_REQUEST'
41 INTERNAL_ERROR = 'INTERNAL_ERROR'
42
43 ERROR_MESSAGES = (
44     (INVALID_TICKET, u'The provided ticket is invalid.'),
45     (INVALID_SERVICE, u'Service is invalid'),
46     (INVALID_REQUEST, u'Not all required parameters were sent.'),
47     (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
48     )
49
50
51 logger = logging.getLogger(__name__)
52
53
54 _never_cache = cache_control(no_cache=True, must_revalidate=True)
55
56
57 def never_cache(view_func):
58     """
59     Decorator that adds headers to a response so that it will
60     never be cached.
61     """
62     @wraps(view_func, assigned=available_attrs(view_func))
63     def _wrapped_view_func(request, *args, **kwargs):
64         response = view_func(request, *args, **kwargs)
65         patch_cache_control(response, no_cache=True,
66                             must_revalidate=True, proxy_revalidate=True)
67         response['Pragma'] = 'no-cache'
68         return response
69     return _wrapped_view_func
70
71
72 @sensitive_post_parameters()
73 @csrf_protect
74 @never_cache
75 def login(request, template_name='cas/login.html',
76           success_redirect=settings.LOGIN_REDIRECT_URL,
77           warn_template_name='cas/warn.html', **kwargs):
78     merge = kwargs.get('merge', False)
79     logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
80                   request.method, merge, template_name)
81
82     service = request.GET.get('service', None)
83     if service is not None:
84         # Save the service on the session, for later use if we end up
85         # in one of the more complicated workflows.
86         request.session['service'] = service
87
88     user = request.user
89
90     errors = []
91
92     if request.method == 'POST':
93         if merge:
94             form = MergeLoginForm(request.POST, request=request)
95         else:
96             form = LoginForm(request.POST, request=request)
97
98         if form.is_valid():
99             service = form.cleaned_data.get('service', None)
100             try:
101                 auth_args = dict(username=form.cleaned_data['email'],
102                                  password=form.cleaned_data['password'])
103                 if merge:
104                     # We only want to send the merge argument if it's
105                     # True. If it it's False, we want it to propagate
106                     # through the auth backends properly.
107                     auth_args['merge'] = merge
108                 user = authenticate(**auth_args)
109             except SameEmailMismatchedPasswords:
110                 # Need to merge the accounts?
111                 if merge:
112                     # We shouldn't get here...
113                     raise
114                 else:
115                     base_url = reverse('cas_provider_merge')
116                     args = dict(
117                         success_redirect=success_redirect,
118                         email=form.cleaned_data['email'],
119                         )
120                     if service is not None:
121                         args['service'] = service
122                     args = urllib.urlencode(args)
123
124                     url = '%s?%s' % (base_url, args)
125                     logging.debug('Redirecting to %s', url)
126                     return HttpResponseRedirect(url)
127
128             if user is None:
129                 errors.append('Incorrect username and/or password.')
130             else:
131                 if user.is_active:
132                     auth_login(request, user)
133
134     else:  # Not a POST...
135         if merge:
136             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
137         else:
138             form = LoginForm(initial={'service': service})
139
140     if user is not None and user.is_authenticated():
141         # We have an authenticated user.
142         if not user.is_active:
143             errors.append('This account is disabled.')
144         else:
145             # Send the on_cas_login signal. If we get an HttpResponse, return that.
146             for receiver, response in signals.on_cas_login.send(sender=login, request=request, **kwargs):
147                 if isinstance(response, HttpResponse):
148                     return response
149
150             if service is None:
151                 # Try and pull the service off the session
152                 service = request.session.pop('service', service)
153
154             signals.on_cas_login_success.send(sender=login, request=request,
155                                               service=service, **kwargs)
156
157             if service is None:
158                 # Normal internal success redirection.
159                 logging.debug('Redirecting to %s', success_redirect)
160                 return HttpResponseRedirect(success_redirect)
161             else:
162                 if request.GET.get('warn', False):
163                     return render_to_response(warn_template_name, {
164                         'service': service,
165                         'warn': False
166                     }, context_instance=RequestContext(request))
167
168                 # Create a service ticket and redirect to the service.
169                 ticket = ServiceTicket.objects.create(service=service, user=user)
170                 if 'service' in request.session:
171                     # Don't need this any more.
172                     del request.session['service']
173
174                 url = ticket.get_redirect_url()
175                 logging.debug('Redirecting to %s', url)
176                 return HttpResponseRedirect(url)
177
178     logging.debug('Rendering response on %s, merge is %s', template_name, merge)
179     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
180
181
182 @never_cache
183 def validate(request):
184     """Validate ticket via CAS v.1 protocol
185     """
186     service = request.GET.get('service', None)
187     ticket_string = request.GET.get('ticket', None)
188     logger.info('Validating ticket %s for %s', ticket_string, service)
189     if service is not None and ticket_string is not None:
190         #renew = request.GET.get('renew', True)
191         #if not renew:
192         # TODO: check user SSO session
193         try:
194             ticket = ServiceTicket.objects.get(ticket=ticket_string)
195             assert ticket.service == service
196         except ServiceTicket.DoesNotExist:
197             logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
198         except Exception as e:
199             logger.exception('Got an exception: %s', e)
200         else:
201             username = ticket.user.username
202             ticket.delete()
203
204             results = signals.on_cas_collect_histories.send(sender=validate, for_user=ticket.user)
205             histories = '\n'.join('\n'.join(rs) for rc, rs in results)
206             logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
207             return HttpResponse("yes\n%s\n%s" % (username, histories))
208
209     logger.info('Validation failed.')
210     return HttpResponse("no\n\n")
211
212
213 @never_cache
214 def logout(request, template_name='cas/logout.html',
215            auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
216     url = request.GET.get('url', None)
217     if request.user.is_authenticated():
218         for ticket in ServiceTicket.objects.filter(user=request.user):
219             ticket.delete()
220         auth_logout(request)
221         if url and auto_redirect:
222             return HttpResponseRedirect(url)
223     return render_to_response(template_name, {'url': url},
224         context_instance=RequestContext(request))
225
226
227 @never_cache
228 def proxy(request):
229     targetService = request.GET['targetService']
230     pgt_id = request.GET['pgt']
231
232     try:
233         proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
234     except ProxyGrantingTicket.DoesNotExist:
235         return _cas2_error_response(INVALID_TICKET)
236
237     pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
238         user=proxyGrantingTicket.serviceTicket.user,
239         service=targetService)
240     return _cas2_proxy_success(pt.ticket)
241
242
243 def ticket_validate(service, ticket_string, pgtUrl):
244     if service is None or ticket_string is None:
245         return _cas2_error_response(INVALID_REQUEST)
246
247     try:
248         if ticket_string.startswith('ST'):
249             ticket = ServiceTicket.objects.get(ticket=ticket_string)
250         elif ticket_string.startswith('PT'):
251             ticket = ProxyTicket.objects.get(ticket=ticket_string)
252         else:
253             return _cas2_error_response(INVALID_TICKET,
254                 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
255                     'ticket': ticket_string})
256     except ServiceTicket.DoesNotExist:
257         return _cas2_error_response(INVALID_TICKET)
258
259     ticketUrl = urlparse.urlparse(ticket.service)
260     serviceUrl = urlparse.urlparse(service)
261
262     if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
263         return _cas2_error_response(INVALID_SERVICE)
264
265     pgtIouId = None
266     proxies = ()
267     if pgtUrl is not None:
268         pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
269         if pgt:
270             pgtIouId = pgt.pgtiou
271
272     if hasattr(ticket, 'proxyticket'):
273         pgt = ticket.proxyticket.proxyGrantingTicket
274         # I am issued by this proxy granting ticket
275         if hasattr(pgt.serviceTicket, 'proxyticket'):
276             while pgt:
277                 if hasattr(pgt.serviceTicket, 'proxyticket'):
278                     proxies += (pgt.serviceTicket.service,)
279                     pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
280                 else:
281                     pgt = None
282
283     user = ticket.user
284     ticket.delete()
285     return _cas2_sucess_response(user, pgtIouId, proxies)
286
287
288 @never_cache
289 def service_validate(request):
290     """Validate ticket via CAS v.2 protocol"""
291     service = request.GET.get('service', None)
292     ticket_string = request.GET.get('ticket', None)
293     pgtUrl = request.GET.get('pgtUrl', None)
294     if ticket_string.startswith('PT-'):
295         return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
296     else:
297         return ticket_validate(service, ticket_string, pgtUrl)
298
299
300 @never_cache
301 def proxy_validate(request):
302     """Validate ticket via CAS v.2 protocol"""
303     service = request.GET.get('service', None)
304     ticket_string = request.GET.get('ticket', None)
305     pgtUrl = request.GET.get('pgtUrl', None)
306     return ticket_validate(service, ticket_string, pgtUrl)
307
308
309 def generate_proxy_granting_ticket(pgt_url, ticket):
310     proxy_callback_good_status = (200, 202, 301, 302, 304)
311     uri = list(urlparse.urlsplit(pgt_url))
312
313     pgt = ProxyGrantingTicket()
314     pgt.serviceTicket = ticket
315     pgt.targetService = pgt_url
316
317     if hasattr(ticket, 'proxyGrantingTicket'):
318         # here we got a proxy ticket! tata!
319         pgt.pgt = ticket.proxyGrantingTicket
320
321     params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
322
323     query = dict(urlparse.parse_qsl(uri[4]))
324     query.update(params)
325
326     uri[3] = urlencode(query)
327
328     try:
329         response = urllib2.urlopen(urlparse.urlunsplit(uri))
330     except urllib2.HTTPError as e:
331         if not e.code in proxy_callback_good_status:
332             logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
333             return
334     except urllib2.URLError as e:
335         logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
336         return
337
338     pgt.save()
339     return pgt
340
341
342 def _cas2_proxy_success(pt):
343     return HttpResponse(proxy_success(pt))
344
345
346 def _cas2_sucess_response(user, pgt=None, proxies=None):
347     return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
348
349
350 def _cas2_error_response(code, message=None):
351     return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
352             <cas:authenticationFailure code="%(code)s">
353                 %(message)s
354             </cas:authenticationFailure>
355         </cas:serviceResponse>''' % {
356         'code': code,
357         'message': message if message else dict(ERROR_MESSAGES).get(code)
358     }, mimetype='text/xml')
359
360
361 def proxy_success(pt):
362     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
363     proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
364     proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
365     proxyTicket.text = pt
366     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
367
368
369 def auth_success_response(user, pgt, proxies):
370     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
371     auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
372     username = etree.SubElement(auth_success, CAS + 'user')
373     username.text = user.username
374
375     attrs = {}
376     for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
377         if custom:
378             attrs.update(custom)
379
380     identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
381                    for i in rr]
382
383     if identifiers:
384         # Singular `identifier`, as that is the name of the element tag(s).
385         attrs['identifier'] = identifiers
386
387     if attrs:
388         formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
389         formatter(auth_success, attrs)
390
391     if pgt:
392         pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
393         pgtElement.text = pgt
394
395     if proxies:
396         proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
397         for proxy in proxies:
398             proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
399             proxyElement.text = proxy
400
401     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')