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