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