2 logger = logging.getLogger('cas_provider.views')
6 from urllib import urlencode
9 from functools import wraps
11 from django.utils.decorators import available_attrs
12 from django.views.decorators.debug import sensitive_post_parameters
13 from django.views.decorators.cache import cache_control
14 from django.utils.cache import patch_cache_control
15 from django.views.decorators.csrf import csrf_protect
17 from django.http import HttpResponse, HttpResponseRedirect
18 from django.conf import settings
19 from django.contrib.auth import login as auth_login, logout as auth_logout
20 from django.core.urlresolvers import get_callable
21 from django.shortcuts import render_to_response
22 from django.template import RequestContext
23 from django.contrib.auth import authenticate
24 from django.core.urlresolvers import reverse
26 from lxml import etree
27 from cas_provider.attribute_formatters import NSMAP, CAS
28 from cas_provider.models import ProxyGrantingTicket, ProxyTicket
29 from cas_provider.models import ServiceTicket
31 from cas_provider.exceptions import SameEmailMismatchedPasswords
32 from cas_provider.forms import LoginForm, MergeLoginForm
36 __all__ = ['login', 'validate', 'logout', 'service_validate']
38 INVALID_TICKET = 'INVALID_TICKET'
39 INVALID_SERVICE = 'INVALID_SERVICE'
40 INVALID_REQUEST = 'INVALID_REQUEST'
41 INTERNAL_ERROR = 'INTERNAL_ERROR'
44 (INVALID_TICKET, u'The provided ticket is invalid.'),
45 (INVALID_SERVICE, u'Service is invalid'),
46 (INVALID_REQUEST, u'Not all required parameters were sent.'),
47 (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
51 logger = logging.getLogger(__name__)
54 _never_cache = cache_control(no_cache=True, must_revalidate=True)
57 def never_cache(view_func):
59 Decorator that adds headers to a response so that it will
62 @wraps(view_func, assigned=available_attrs(view_func))
63 def _wrapped_view_func(request, *args, **kwargs):
64 response = view_func(request, *args, **kwargs)
65 patch_cache_control(response, no_cache=True,
66 must_revalidate=True, proxy_revalidate=True)
67 response['Pragma'] = 'no-cache'
69 return _wrapped_view_func
72 @sensitive_post_parameters()
75 def login(request, template_name='cas/login.html',
76 success_redirect=settings.LOGIN_REDIRECT_URL,
77 warn_template_name='cas/warn.html', **kwargs):
78 merge = kwargs.get('merge', False)
79 logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
80 request.method, merge, template_name)
82 service = request.GET.get('service', None)
83 if service is not None:
84 # Save the service on the session, for later use if we end up
85 # in one of the more complicated workflows.
86 request.session['service'] = service
92 if request.method == 'POST':
94 form = MergeLoginForm(request.POST, request=request)
96 form = LoginForm(request.POST, request=request)
99 service = form.cleaned_data.get('service', None)
101 auth_args = dict(username=form.cleaned_data['email'],
102 password=form.cleaned_data['password'])
104 # We only want to send the merge argument if it's
105 # True. If it it's False, we want it to propagate
106 # through the auth backends properly.
107 auth_args['merge'] = merge
108 user = authenticate(**auth_args)
109 except SameEmailMismatchedPasswords:
110 # Need to merge the accounts?
112 # We shouldn't get here...
115 base_url = reverse('cas_provider_merge')
117 success_redirect=success_redirect,
118 email=form.cleaned_data['email'],
120 if service is not None:
121 args['service'] = service
122 args = urllib.urlencode(args)
124 url = '%s?%s' % (base_url, args)
125 logging.debug('Redirecting to %s', url)
126 return HttpResponseRedirect(url)
129 errors.append('Incorrect username and/or password.')
132 auth_login(request, user)
134 else: # Not a POST...
136 form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
138 form = LoginForm(initial={'service': service})
140 if user is not None and user.is_authenticated():
141 # We have an authenticated user.
142 if not user.is_active:
143 errors.append('This account is disabled.')
145 # Send the on_cas_login signal. If we get an HttpResponse, return that.
146 for receiver, response in signals.on_cas_login.send(sender=login, request=request, **kwargs):
147 if isinstance(response, HttpResponse):
151 # Try and pull the service off the session
152 service = request.session.pop('service', service)
154 signals.on_cas_login_success.send(sender=login, request=request,
155 service=service, **kwargs)
158 # Normal internal success redirection.
159 logging.debug('Redirecting to %s', success_redirect)
160 return HttpResponseRedirect(success_redirect)
162 if request.GET.get('warn', False):
163 return render_to_response(warn_template_name, {
166 }, context_instance=RequestContext(request))
168 # Create a service ticket and redirect to the service.
169 ticket = ServiceTicket.objects.create(service=service, user=user)
170 if 'service' in request.session:
171 # Don't need this any more.
172 del request.session['service']
174 url = ticket.get_redirect_url()
175 logging.debug('Redirecting to %s', url)
176 return HttpResponseRedirect(url)
178 logging.debug('Rendering response on %s, merge is %s', template_name, merge)
179 return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
183 def validate(request):
184 """Validate ticket via CAS v.1 protocol
186 service = request.GET.get('service', None)
187 ticket_string = request.GET.get('ticket', None)
188 logger.info('Validating ticket %s for %s', ticket_string, service)
189 if service is not None and ticket_string is not None:
190 #renew = request.GET.get('renew', True)
192 # TODO: check user SSO session
194 ticket = ServiceTicket.objects.get(ticket=ticket_string)
195 assert ticket.service == service
196 except ServiceTicket.DoesNotExist:
197 logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
198 except Exception as e:
199 logger.exception('Got an exception: %s', e)
201 username = ticket.user.username
204 results = signals.on_cas_collect_histories.send(sender=validate, for_user=ticket.user)
205 histories = '\n'.join('\n'.join(rs) for rc, rs in results)
206 logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
207 return HttpResponse("yes\n%s\n%s" % (username, histories))
209 logger.info('Validation failed.')
210 return HttpResponse("no\n\n")
214 def logout(request, template_name='cas/logout.html',
215 auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
216 url = request.GET.get('url', None)
217 if request.user.is_authenticated():
218 for ticket in ServiceTicket.objects.filter(user=request.user):
221 if url and auto_redirect:
222 return HttpResponseRedirect(url)
223 return render_to_response(template_name, {'url': url},
224 context_instance=RequestContext(request))
229 targetService = request.GET['targetService']
230 pgt_id = request.GET['pgt']
233 proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
234 except ProxyGrantingTicket.DoesNotExist:
235 return _cas2_error_response(INVALID_TICKET)
237 pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
238 user=proxyGrantingTicket.serviceTicket.user,
239 service=targetService)
240 return _cas2_proxy_success(pt.ticket)
243 def ticket_validate(service, ticket_string, pgtUrl):
244 if service is None or ticket_string is None:
245 return _cas2_error_response(INVALID_REQUEST)
248 if ticket_string.startswith('ST'):
249 ticket = ServiceTicket.objects.get(ticket=ticket_string)
250 elif ticket_string.startswith('PT'):
251 ticket = ProxyTicket.objects.get(ticket=ticket_string)
253 return _cas2_error_response(INVALID_TICKET,
254 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
255 'ticket': ticket_string})
256 except ServiceTicket.DoesNotExist:
257 return _cas2_error_response(INVALID_TICKET)
259 ticketUrl = urlparse.urlparse(ticket.service)
260 serviceUrl = urlparse.urlparse(service)
262 if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
263 return _cas2_error_response(INVALID_SERVICE)
267 if pgtUrl is not None:
268 pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
270 pgtIouId = pgt.pgtiou
272 if hasattr(ticket, 'proxyticket'):
273 pgt = ticket.proxyticket.proxyGrantingTicket
274 # I am issued by this proxy granting ticket
275 if hasattr(pgt.serviceTicket, 'proxyticket'):
277 if hasattr(pgt.serviceTicket, 'proxyticket'):
278 proxies += (pgt.serviceTicket.service,)
279 pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
285 return _cas2_sucess_response(user, pgtIouId, proxies)
289 def service_validate(request):
290 """Validate ticket via CAS v.2 protocol"""
291 service = request.GET.get('service', None)
292 ticket_string = request.GET.get('ticket', None)
293 pgtUrl = request.GET.get('pgtUrl', None)
294 if ticket_string.startswith('PT-'):
295 return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
297 return ticket_validate(service, ticket_string, pgtUrl)
301 def proxy_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 return ticket_validate(service, ticket_string, pgtUrl)
309 def generate_proxy_granting_ticket(pgt_url, ticket):
310 proxy_callback_good_status = (200, 202, 301, 302, 304)
311 uri = list(urlparse.urlsplit(pgt_url))
313 pgt = ProxyGrantingTicket()
314 pgt.serviceTicket = ticket
315 pgt.targetService = pgt_url
317 if hasattr(ticket, 'proxyGrantingTicket'):
318 # here we got a proxy ticket! tata!
319 pgt.pgt = ticket.proxyGrantingTicket
321 params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
323 query = dict(urlparse.parse_qsl(uri[4]))
326 uri[3] = urlencode(query)
329 response = urllib2.urlopen(urlparse.urlunsplit(uri))
330 except urllib2.HTTPError as e:
331 if not e.code in proxy_callback_good_status:
332 logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
334 except urllib2.URLError as e:
335 logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
342 def _cas2_proxy_success(pt):
343 return HttpResponse(proxy_success(pt))
346 def _cas2_sucess_response(user, pgt=None, proxies=None):
347 return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
350 def _cas2_error_response(code, message=None):
351 return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
352 <cas:authenticationFailure code="%(code)s">
354 </cas:authenticationFailure>
355 </cas:serviceResponse>''' % {
357 'message': message if message else dict(ERROR_MESSAGES).get(code)
358 }, mimetype='text/xml')
361 def proxy_success(pt):
362 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
363 proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
364 proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
365 proxyTicket.text = pt
366 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
369 def auth_success_response(user, pgt, proxies):
370 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
371 auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
372 username = etree.SubElement(auth_success, CAS + 'user')
373 username.text = user.username
376 for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
380 identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
384 # Singular `identifier`, as that is the name of the element tag(s).
385 attrs['identifier'] = identifiers
388 formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
389 formatter(auth_success, attrs)
392 pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
393 pgtElement.text = pgt
396 proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
397 for proxy in proxies:
398 proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
399 proxyElement.text = proxy
401 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')