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