2 logger = logging.getLogger('cas_provider.views')
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
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
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
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
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
28 from cas_provider.forms import LoginForm, MergeLoginForm
32 from django.urls import get_callable, reverse
34 __all__ = ['login', 'validate', 'logout', 'service_validate']
36 INVALID_TICKET = 'INVALID_TICKET'
37 INVALID_SERVICE = 'INVALID_SERVICE'
38 INVALID_REQUEST = 'INVALID_REQUEST'
39 INTERNAL_ERROR = 'INTERNAL_ERROR'
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'),
49 logger = logging.getLogger(__name__)
52 _never_cache = cache_control(no_cache=True, must_revalidate=True)
55 def never_cache(view_func):
57 Decorator that adds headers to a response so that it will
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'
67 return _wrapped_view_func
70 @sensitive_post_parameters()
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)
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
90 if request.method == 'POST':
92 form = MergeLoginForm(request.POST, request=request)
94 form = LoginForm(request.POST, request=request)
97 service = form.cleaned_data.get('service', None)
99 auth_args = dict(username=form.cleaned_data['username'],
100 password=form.cleaned_data['password'])
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)
108 # Need to merge the accounts?
110 # We shouldn't get here...
113 base_url = reverse('cas_provider_merge')
115 success_redirect=success_redirect,
116 username=form.cleaned_data['username'],
118 if service is not None:
119 args['service'] = service
120 args = urlencode(args)
122 url = '%s?%s' % (base_url, args)
123 logging.debug('Redirecting to %s', url)
124 return HttpResponseRedirect(url)
127 errors.append(_('Incorrect username and/or password.'))
130 auth_login(request, user)
132 else: # Not a POST...
134 form = MergeLoginForm(initial={'service': service, 'username': request.GET.get('username')})
136 form = LoginForm(initial={'service': service})
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.'))
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):
149 # Try and pull the service off the session
150 service = request.session.pop('service', service)
152 signals.on_cas_login_success.send(sender=login, request=request,
153 service=service, **kwargs)
156 # Normal internal success redirection.
157 logging.debug('Redirecting to %s', success_redirect)
158 return HttpResponseRedirect(success_redirect)
160 if request.GET.get('warn', False):
161 return render(request, warn_template_name, {
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']
172 url = ticket.get_redirect_url()
173 logging.debug('Redirecting to %s', url)
174 return HttpResponseRedirect(url)
176 logging.debug('Rendering response on %s, merge is %s', template_name, merge)
177 return render(request, template_name, {'form': form, 'errors': errors})
181 def validate(request):
182 """Validate ticket via CAS v.1 protocol
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)
190 # TODO: check user SSO session
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)
199 username = ticket.user.username
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))
207 logger.info('Validation failed.')
208 return HttpResponse("no\n\n")
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):
219 if url and auto_redirect:
220 return HttpResponseRedirect(url)
221 return render(request, template_name, {'url': url})
226 targetService = request.GET['targetService']
227 pgt_id = request.GET['pgt']
230 proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
231 except ProxyGrantingTicket.DoesNotExist:
232 return _cas2_error_response(INVALID_TICKET)
234 pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
235 user=proxyGrantingTicket.user,
236 service=targetService)
237 return _cas2_proxy_success(pt.ticket)
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)
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)
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)
256 ticketUrl = urlparse(ticket.service)
257 serviceUrl = urlparse(service)
259 if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
260 return _cas2_error_response(INVALID_SERVICE)
264 if pgtUrl is not None:
265 pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
267 pgtIouId = pgt.pgtiou
270 proxyTicket = ticket.proxyticket
271 except ProxyTicket.DoesNotExist:
274 pgt = proxyTicket.proxyGrantingTicket
275 # I am issued by this proxy granting ticket
276 while pgt.pgt is not None:
277 proxies += (pgt.service,)
282 return _cas2_sucess_response(user, pgtIouId, proxies)
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")
294 return ticket_validate(service, ticket_string, pgtUrl)
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)
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))
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)
316 params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
318 query = dict(parse_qsl(uri[4]))
321 uri[3] = urlencode(query)
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))
329 except URLError as e:
330 logger.debug('Checking Proxy Callback URL {0} raised URLError. Not issuing PGT.'.format(uri))
337 def _cas2_proxy_success(pt):
338 return HttpResponse(proxy_success(pt))
341 def _cas2_sucess_response(user, pgt=None, proxies=None):
342 return HttpResponse(auth_success_response(user, pgt, proxies), content_type='text/xml')
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">
349 </cas:authenticationFailure>
350 </cas:serviceResponse>''' % {
352 'message': message if message else dict(ERROR_MESSAGES).get(code)
353 }, content_type='text/xml')
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')
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
371 for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
375 identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
379 # Singular `identifier`, as that is the name of the element tag(s).
380 attrs['identifier'] = identifiers
383 formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
384 formatter(auth_success, attrs)
387 pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
388 pgtElement.text = pgt
391 proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
392 for proxy in proxies:
393 proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
394 proxyElement.text = proxy
396 return etree.tostring(response, encoding='unicode')