Fix standard urls. Test for Django up to 5.0.
[django-cas-provider.git] / cas_provider / views.py
1 import logging
2 logger = logging.getLogger('cas_provider.views')
3
4 from urllib.error import HTTPError, URLError
5 from urllib.parse import parse_qsl, urlencode, urlparse, urlsplit, urlunsplit
6 from urllib.request import urlopen
7 from functools import wraps
8
9 from django.views.decorators.debug import sensitive_post_parameters
10 from django.views.decorators.cache import cache_control
11 from django.utils.cache import patch_cache_control
12 from django.views.decorators.csrf import csrf_protect
13
14 from django.http import HttpResponse, HttpResponseRedirect
15 from django.conf import settings
16 from django.contrib.auth import login as auth_login, logout as auth_logout
17
18 from django.shortcuts import render
19 from django.utils.translation import gettext as _
20 from django.template import RequestContext
21 from django.contrib.auth import authenticate
22
23 from lxml import etree
24 from cas_provider.attribute_formatters import NSMAP, CAS
25 from cas_provider.models import ProxyGrantingTicket, ProxyTicket
26 from cas_provider.models import ServiceTicket
27
28 from cas_provider.forms import LoginForm, MergeLoginForm
29
30 from . import signals
31
32 from django.urls import get_callable, reverse
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, 'The provided ticket is invalid.'),
43     (INVALID_SERVICE, 'Service is invalid'),
44     (INVALID_REQUEST, 'Not all required parameters were sent.'),
45     (INTERNAL_ERROR, '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)
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 = 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(request, warn_template_name, {
162                         'service': service,
163                         'warn': False
164                     })
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(request, template_name, {'form': form, 'errors': errors})
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(request, template_name, {'url': url})
222
223
224 @never_cache
225 def proxy(request):
226     targetService = request.GET['targetService']
227     pgt_id = request.GET['pgt']
228
229     try:
230         proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
231     except ProxyGrantingTicket.DoesNotExist:
232         return _cas2_error_response(INVALID_TICKET)
233
234     pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
235         user=proxyGrantingTicket.user,
236         service=targetService)
237     return _cas2_proxy_success(pt.ticket)
238
239
240 def ticket_validate(service, ticket_string, pgtUrl):
241     if service is None or ticket_string is None:
242         return _cas2_error_response(INVALID_REQUEST)
243
244     try:
245         if ticket_string.startswith('ST'):
246             ticket = ServiceTicket.objects.get(ticket=ticket_string)
247         elif ticket_string.startswith('PT'):
248             ticket = ProxyTicket.objects.get(ticket=ticket_string)
249         else:
250             return _cas2_error_response(INVALID_TICKET,
251                 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
252                     'ticket': ticket_string})
253     except ServiceTicket.DoesNotExist:
254         return _cas2_error_response(INVALID_TICKET)
255
256     ticketUrl = urlparse(ticket.service)
257     serviceUrl = urlparse(service)
258
259     if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
260         return _cas2_error_response(INVALID_SERVICE)
261
262     pgtIouId = None
263     proxies = ()
264     if pgtUrl is not None:
265         pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
266         if pgt:
267             pgtIouId = pgt.pgtiou
268
269     try:
270         proxyTicket = ticket.proxyticket
271     except ProxyTicket.DoesNotExist:
272         pass
273     else:
274         pgt = proxyTicket.proxyGrantingTicket
275         # I am issued by this proxy granting ticket
276         while pgt.pgt is not None:
277             proxies += (pgt.service,)
278             pgt = pgt.pgt
279
280     user = ticket.user
281     ticket.delete()
282     return _cas2_sucess_response(user, pgtIouId, proxies)
283
284
285 @never_cache
286 def service_validate(request):
287     """Validate ticket via CAS v.2 protocol"""
288     service = request.GET.get('service', None)
289     ticket_string = request.GET.get('ticket', None)
290     pgtUrl = request.GET.get('pgtUrl', None)
291     if ticket_string.startswith('PT-'):
292         return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
293     else:
294         return ticket_validate(service, ticket_string, pgtUrl)
295
296
297 @never_cache
298 def proxy_validate(request):
299     """Validate ticket via CAS v.2 protocol"""
300     service = request.GET.get('service', None)
301     ticket_string = request.GET.get('ticket', None)
302     pgtUrl = request.GET.get('pgtUrl', None)
303     return ticket_validate(service, ticket_string, pgtUrl)
304
305
306 def generate_proxy_granting_ticket(pgt_url, ticket):
307     proxy_callback_good_status = (200, 202, 301, 302, 304)
308     uri = list(urlsplit(pgt_url))
309
310     pgt = ProxyGrantingTicket()
311     pgt.user = ticket.user
312     pgt.service = ticket.service
313     # Remember if it's a chained PGT.
314     pgt.pgt = getattr(ticket, 'proxyGrantingTicket', None)
315
316     params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
317
318     query = dict(parse_qsl(uri[4]))
319     query.update(params)
320
321     uri[3] = urlencode(query)
322
323     try:
324         urlopen(urlunsplit(uri))
325     except HTTPError as e:
326         if not e.code in proxy_callback_good_status:
327             logger.debug('Checking Proxy Callback URL {0} returned {1}. Not issuing PGT.'.format(uri, e.code))
328             return
329     except URLError as e:
330         logger.debug('Checking Proxy Callback URL {0} raised URLError. Not issuing PGT.'.format(uri))
331         return
332
333     pgt.save()
334     return pgt
335
336
337 def _cas2_proxy_success(pt):
338     return HttpResponse(proxy_success(pt))
339
340
341 def _cas2_sucess_response(user, pgt=None, proxies=None):
342     return HttpResponse(auth_success_response(user, pgt, proxies), content_type='text/xml')
343
344
345 def _cas2_error_response(code, message=None):
346     return HttpResponse('''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
347             <cas:authenticationFailure code="%(code)s">
348                 %(message)s
349             </cas:authenticationFailure>
350         </cas:serviceResponse>''' % {
351         'code': code,
352         'message': message if message else dict(ERROR_MESSAGES).get(code)
353     }, content_type='text/xml')
354
355
356 def proxy_success(pt):
357     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
358     proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
359     proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
360     proxyTicket.text = pt
361     return etree.tostring(response, encoding='unicode')
362
363
364 def auth_success_response(user, pgt, proxies):
365     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
366     auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
367     username = etree.SubElement(auth_success, CAS + 'user')
368     username.text = user.username
369
370     attrs = {}
371     for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
372         if custom:
373             attrs.update(custom)
374
375     identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
376                    for i in rr]
377
378     if identifiers:
379         # Singular `identifier`, as that is the name of the element tag(s).
380         attrs['identifier'] = identifiers
381
382     if attrs:
383         formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
384         formatter(auth_success, attrs)
385
386     if pgt:
387         pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
388         pgtElement.text = pgt
389
390     if proxies:
391         proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
392         for proxy in proxies:
393             proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
394             proxyElement.text = proxy
395
396     return etree.tostring(response, encoding='unicode')