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