1 from __future__ import unicode_literals
4 logger = logging.getLogger('cas_provider.views')
7 from urllib.error import HTTPError, URLError
8 from urllib.parse import parse_qsl, urlencode, urlparse, urlsplit, urlunsplit
9 from urllib.request import urlopen
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
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
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
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 _
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
38 from cas_provider.forms import LoginForm, MergeLoginForm
42 if VERSION >= (1, 10):
43 from django.urls import get_callable, reverse
44 user_is_authenticated = lambda user: user.is_authenticated
46 from django.core.urlresolvers import get_callable, reverse
47 user_is_authenticated = lambda user: user.is_authenticated()
49 __all__ = ['login', 'validate', 'logout', 'service_validate']
51 INVALID_TICKET = 'INVALID_TICKET'
52 INVALID_SERVICE = 'INVALID_SERVICE'
53 INVALID_REQUEST = 'INVALID_REQUEST'
54 INTERNAL_ERROR = 'INTERNAL_ERROR'
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'),
64 logger = logging.getLogger(__name__)
67 _never_cache = cache_control(no_cache=True, must_revalidate=True)
70 def never_cache(view_func):
72 Decorator that adds headers to a response so that it will
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'
82 return _wrapped_view_func
85 @sensitive_post_parameters()
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)
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
105 if request.method == 'POST':
107 form = MergeLoginForm(request.POST, request=request)
109 form = LoginForm(request.POST, request=request)
112 service = form.cleaned_data.get('service', None)
114 auth_args = dict(username=form.cleaned_data['username'],
115 password=form.cleaned_data['password'])
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)
123 # Need to merge the accounts?
125 # We shouldn't get here...
128 base_url = reverse('cas_provider_merge')
130 success_redirect=success_redirect,
131 username=form.cleaned_data['username'],
133 if service is not None:
134 args['service'] = service
135 args = urlencode(args)
137 url = '%s?%s' % (base_url, args)
138 logging.debug('Redirecting to %s', url)
139 return HttpResponseRedirect(url)
142 errors.append(_('Incorrect username and/or password.'))
145 auth_login(request, user)
147 else: # Not a POST...
149 form = MergeLoginForm(initial={'service': service, 'username': request.GET.get('username')})
151 form = LoginForm(initial={'service': service})
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.'))
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):
164 # Try and pull the service off the session
165 service = request.session.pop('service', service)
167 signals.on_cas_login_success.send(sender=login, request=request,
168 service=service, **kwargs)
171 # Normal internal success redirection.
172 logging.debug('Redirecting to %s', success_redirect)
173 return HttpResponseRedirect(success_redirect)
175 if request.GET.get('warn', False):
176 return render(request, warn_template_name, {
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']
187 url = ticket.get_redirect_url()
188 logging.debug('Redirecting to %s', url)
189 return HttpResponseRedirect(url)
191 logging.debug('Rendering response on %s, merge is %s', template_name, merge)
192 return render(request, template_name, {'form': form, 'errors': errors})
196 def validate(request):
197 """Validate ticket via CAS v.1 protocol
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)
205 # TODO: check user SSO session
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)
214 username = ticket.user.username
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))
222 logger.info('Validation failed.')
223 return HttpResponse("no\n\n")
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):
234 if url and auto_redirect:
235 return HttpResponseRedirect(url)
236 return render(request, template_name, {'url': url})
241 targetService = request.GET['targetService']
242 pgt_id = request.GET['pgt']
245 proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
246 except ProxyGrantingTicket.DoesNotExist:
247 return _cas2_error_response(INVALID_TICKET)
249 pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
250 user=proxyGrantingTicket.user,
251 service=targetService)
252 return _cas2_proxy_success(pt.ticket)
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)
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)
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)
271 ticketUrl = urlparse(ticket.service)
272 serviceUrl = urlparse(service)
274 if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
275 return _cas2_error_response(INVALID_SERVICE)
279 if pgtUrl is not None:
280 pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
282 pgtIouId = pgt.pgtiou
285 proxyTicket = ticket.proxyticket
286 except ProxyTicket.DoesNotExist:
289 pgt = proxyTicket.proxyGrantingTicket
290 # I am issued by this proxy granting ticket
291 while pgt.pgt is not None:
292 proxies += (pgt.service,)
297 return _cas2_sucess_response(user, pgtIouId, proxies)
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")
309 return ticket_validate(service, ticket_string, pgtUrl)
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)
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))
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)
331 params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
333 query = dict(parse_qsl(uri[4]))
336 uri[3] = urlencode(query)
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))
344 except URLError as e:
345 logger.debug('Checking Proxy Callback URL {0} raised URLError. Not issuing PGT.'.format(uri))
352 def _cas2_proxy_success(pt):
353 return HttpResponse(proxy_success(pt))
356 def _cas2_sucess_response(user, pgt=None, proxies=None):
357 return HttpResponse(auth_success_response(user, pgt, proxies), content_type='text/xml')
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">
364 </cas:authenticationFailure>
365 </cas:serviceResponse>''' % {
367 'message': message if message else dict(ERROR_MESSAGES).get(code)
368 }, content_type='text/xml')
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')
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
386 for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
390 identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
394 # Singular `identifier`, as that is the name of the element tag(s).
395 attrs['identifier'] = identifiers
398 formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
399 formatter(auth_success, attrs)
402 pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
403 pgtElement.text = pgt
406 proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
407 for proxy in proxies:
408 proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
409 proxyElement.text = proxy
411 return etree.tostring(response, encoding='unicode')