2 logger = logging.getLogger('cas_provider.views')
5 from urllib import urlencode
8 from functools import wraps
10 from django.utils.decorators import available_attrs
11 from django.views.decorators.debug import sensitive_post_parameters
12 from django.views.decorators.cache import cache_control
13 from django.utils.cache import patch_cache_control
14 from django.views.decorators.csrf import csrf_protect
16 from django.http import HttpResponse, HttpResponseRedirect
17 from django.conf import settings
18 from django.contrib.auth import login as auth_login, logout as auth_logout
19 from django.core.urlresolvers import get_callable
20 from django.shortcuts import render_to_response
21 from django.template import RequestContext
22 from django.contrib.auth import authenticate
23 from django.core.urlresolvers import reverse
25 from lxml import etree
26 from cas_provider.attribute_formatters import NSMAP, CAS
27 from cas_provider.models import ProxyGrantingTicket, ProxyTicket
28 from cas_provider.models import ServiceTicket
30 from cas_provider.forms import LoginForm, MergeLoginForm
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, u'The provided ticket is invalid.'),
43 (INVALID_SERVICE, u'Service is invalid'),
44 (INVALID_REQUEST, u'Not all required parameters were sent.'),
45 (INTERNAL_ERROR, u'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
60 @wraps(view_func, assigned=available_attrs(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'
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 = urllib.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_to_response(warn_template_name, {
164 }, context_instance=RequestContext(request))
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_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
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_to_response(template_name, {'url': url},
222 context_instance=RequestContext(request))
227 targetService = request.GET['targetService']
228 pgt_id = request.GET['pgt']
231 proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
232 except ProxyGrantingTicket.DoesNotExist:
233 return _cas2_error_response(INVALID_TICKET)
235 pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
236 user=proxyGrantingTicket.serviceTicket.user,
237 service=targetService)
238 return _cas2_proxy_success(pt.ticket)
241 def ticket_validate(service, ticket_string, pgtUrl):
242 if service is None or ticket_string is None:
243 return _cas2_error_response(INVALID_REQUEST)
246 if ticket_string.startswith('ST'):
247 ticket = ServiceTicket.objects.get(ticket=ticket_string)
248 elif ticket_string.startswith('PT'):
249 ticket = ProxyTicket.objects.get(ticket=ticket_string)
251 return _cas2_error_response(INVALID_TICKET,
252 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
253 'ticket': ticket_string})
254 except ServiceTicket.DoesNotExist:
255 return _cas2_error_response(INVALID_TICKET)
257 ticketUrl = urlparse.urlparse(ticket.service)
258 serviceUrl = urlparse.urlparse(service)
260 if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
261 return _cas2_error_response(INVALID_SERVICE)
265 if pgtUrl is not None:
266 pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
268 pgtIouId = pgt.pgtiou
270 if hasattr(ticket, 'proxyticket'):
271 pgt = ticket.proxyticket.proxyGrantingTicket
272 # I am issued by this proxy granting ticket
273 if hasattr(pgt.serviceTicket, 'proxyticket'):
275 if hasattr(pgt.serviceTicket, 'proxyticket'):
276 proxies += (pgt.serviceTicket.service,)
277 pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
283 return _cas2_sucess_response(user, pgtIouId, proxies)
287 def service_validate(request):
288 """Validate ticket via CAS v.2 protocol"""
289 service = request.GET.get('service', None)
290 ticket_string = request.GET.get('ticket', None)
291 pgtUrl = request.GET.get('pgtUrl', None)
292 if ticket_string.startswith('PT-'):
293 return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
295 return ticket_validate(service, ticket_string, pgtUrl)
299 def proxy_validate(request):
300 """Validate ticket via CAS v.2 protocol"""
301 service = request.GET.get('service', None)
302 ticket_string = request.GET.get('ticket', None)
303 pgtUrl = request.GET.get('pgtUrl', None)
304 return ticket_validate(service, ticket_string, pgtUrl)
307 def generate_proxy_granting_ticket(pgt_url, ticket):
308 proxy_callback_good_status = (200, 202, 301, 302, 304)
309 uri = list(urlparse.urlsplit(pgt_url))
311 pgt = ProxyGrantingTicket()
312 pgt.serviceTicket = ticket
313 pgt.targetService = pgt_url
315 if hasattr(ticket, 'proxyGrantingTicket'):
316 # here we got a proxy ticket! tata!
317 pgt.pgt = ticket.proxyGrantingTicket
319 params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
321 query = dict(urlparse.parse_qsl(uri[4]))
324 uri[3] = urlencode(query)
327 urllib2.urlopen(urlparse.urlunsplit(uri))
328 except urllib2.HTTPError as e:
329 if not e.code in proxy_callback_good_status:
330 logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
332 except urllib2.URLError as e:
333 logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
340 def _cas2_proxy_success(pt):
341 return HttpResponse(proxy_success(pt))
344 def _cas2_sucess_response(user, pgt=None, proxies=None):
345 return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
348 def _cas2_error_response(code, message=None):
349 return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
350 <cas:authenticationFailure code="%(code)s">
352 </cas:authenticationFailure>
353 </cas:serviceResponse>''' % {
355 'message': message if message else dict(ERROR_MESSAGES).get(code)
356 }, mimetype='text/xml')
359 def proxy_success(pt):
360 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
361 proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
362 proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
363 proxyTicket.text = pt
364 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
367 def auth_success_response(user, pgt, proxies):
368 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
369 auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
370 username = etree.SubElement(auth_success, CAS + 'user')
371 username.text = user.username
374 for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
378 identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
382 # Singular `identifier`, as that is the name of the element tag(s).
383 attrs['identifier'] = identifiers
386 formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
387 formatter(auth_success, attrs)
390 pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
391 pgtElement.text = pgt
394 proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
395 for proxy in proxies:
396 proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
397 proxyElement.text = proxy
399 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')