2 logger = logging.getLogger('cas_provider.views')
6 from urllib import urlencode
10 from django.views.decorators.debug import sensitive_post_parameters
11 from django.views.decorators.cache import never_cache
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
17 from django.core.urlresolvers import get_callable
18 from django.shortcuts import render_to_response
19 from django.template import RequestContext
20 from django.contrib.auth import authenticate
21 from django.core.urlresolvers import reverse
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.exceptions import SameEmailMismatchedPasswords
29 from cas_provider.forms import LoginForm, MergeLoginForm
33 __all__ = ['login', 'validate', 'logout', 'service_validate']
35 INVALID_TICKET = 'INVALID_TICKET'
36 INVALID_SERVICE = 'INVALID_SERVICE'
37 INVALID_REQUEST = 'INVALID_REQUEST'
38 INTERNAL_ERROR = 'INTERNAL_ERROR'
41 (INVALID_TICKET, u'The provided ticket is invalid.'),
42 (INVALID_SERVICE, u'Service is invalid'),
43 (INVALID_REQUEST, u'Not all required parameters were sent.'),
44 (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
48 logger = logging.getLogger(__name__)
51 @sensitive_post_parameters()
54 def login(request, template_name='cas/login.html',
55 success_redirect=settings.LOGIN_REDIRECT_URL,
56 warn_template_name='cas/warn.html', **kwargs):
57 merge = kwargs.get('merge', False)
58 logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
59 request.method, merge, template_name)
61 service = request.GET.get('service', None)
62 if service is not None:
63 # Save the service on the session, for later use if we end up
64 # in one of the more complicated workflows.
65 request.session['service'] = service
71 if request.method == 'POST':
73 form = MergeLoginForm(request.POST, request=request)
75 form = LoginForm(request.POST, request=request)
78 service = form.cleaned_data.get('service', None)
80 auth_args = dict(username=form.cleaned_data['email'],
81 password=form.cleaned_data['password'])
83 # We only want to send the merge argument if it's
84 # True. If it it's False, we want it to propagate
85 # through the auth backends properly.
86 auth_args['merge'] = merge
87 user = authenticate(**auth_args)
88 except SameEmailMismatchedPasswords:
89 # Need to merge the accounts?
91 # We shouldn't get here...
94 base_url = reverse('cas_provider_merge')
96 success_redirect=success_redirect,
97 email=form.cleaned_data['email'],
99 if service is not None:
100 args['service'] = service
101 args = urllib.urlencode(args)
103 url = '%s?%s' % (base_url, args)
104 logging.debug('Redirecting to %s', url)
105 return HttpResponseRedirect(url)
108 errors.append('Incorrect username and/or password.')
111 auth_login(request, user)
113 else: # Not a POST...
115 form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
117 form = LoginForm(initial={'service': service})
119 if user is not None and user.is_authenticated():
120 # We have an authenticated user.
121 if not user.is_active:
122 errors.append('This account is disabled.')
124 # Send the on_cas_login signal. If we get an HttpResponse, return that.
125 for receiver, response in signals.on_cas_login.send(sender=login, request=request, **kwargs):
126 if isinstance(response, HttpResponse):
130 # Try and pull the service off the session
131 service = request.session.pop('service', service)
133 signals.on_cas_login_success.send(sender=login, request=request,
134 service=service, **kwargs)
137 # Normal internal success redirection.
138 logging.debug('Redirecting to %s', success_redirect)
139 return HttpResponseRedirect(success_redirect)
141 if request.GET.get('warn', False):
142 return render_to_response(warn_template_name, {
145 }, context_instance=RequestContext(request))
147 # Create a service ticket and redirect to the service.
148 ticket = ServiceTicket.objects.create(service=service, user=user)
149 if 'service' in request.session:
150 # Don't need this any more.
151 del request.session['service']
153 url = ticket.get_redirect_url()
154 logging.debug('Redirecting to %s', url)
155 return HttpResponseRedirect(url)
157 logging.debug('Rendering response on %s, merge is %s', template_name, merge)
158 return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
161 def validate(request):
162 """Validate ticket via CAS v.1 protocol
164 service = request.GET.get('service', None)
165 ticket_string = request.GET.get('ticket', None)
166 logger.info('Validating ticket %s for %s', ticket_string, service)
167 if service is not None and ticket_string is not None:
168 #renew = request.GET.get('renew', True)
170 # TODO: check user SSO session
172 ticket = ServiceTicket.objects.get(ticket=ticket_string)
173 assert ticket.service == service
174 except ServiceTicket.DoesNotExist:
175 logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
176 except Exception as e:
177 logger.exception('Got an exception: %s', e)
179 username = ticket.user.username
182 results = signals.on_cas_collect_histories.send(sender=validate, for_user=ticket.user)
183 histories = '\n'.join('\n'.join(rs) for rc, rs in results)
184 logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
185 return HttpResponse("yes\n%s\n%s" % (username, histories))
187 logger.info('Validation failed.')
188 return HttpResponse("no\n\n")
191 def logout(request, template_name='cas/logout.html',
192 auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
193 url = request.GET.get('url', None)
194 if request.user.is_authenticated():
195 for ticket in ServiceTicket.objects.filter(user=request.user):
198 if url and auto_redirect:
199 return HttpResponseRedirect(url)
200 return render_to_response(template_name, {'url': url},
201 context_instance=RequestContext(request))
205 targetService = request.GET['targetService']
206 pgt_id = request.GET['pgt']
209 proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
210 except ProxyGrantingTicket.DoesNotExist:
211 return _cas2_error_response(INVALID_TICKET)
213 pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
214 user=proxyGrantingTicket.serviceTicket.user,
215 service=targetService)
216 return _cas2_proxy_success(pt.ticket)
219 def ticket_validate(service, ticket_string, pgtUrl):
220 if service is None or ticket_string is None:
221 return _cas2_error_response(INVALID_REQUEST)
224 if ticket_string.startswith('ST'):
225 ticket = ServiceTicket.objects.get(ticket=ticket_string)
226 elif ticket_string.startswith('PT'):
227 ticket = ProxyTicket.objects.get(ticket=ticket_string)
229 return _cas2_error_response(INVALID_TICKET,
230 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
231 'ticket': ticket_string})
232 except ServiceTicket.DoesNotExist:
233 return _cas2_error_response(INVALID_TICKET)
235 ticketUrl = urlparse.urlparse(ticket.service)
236 serviceUrl = urlparse.urlparse(service)
238 if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
239 return _cas2_error_response(INVALID_SERVICE)
243 if pgtUrl is not None:
244 pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
246 pgtIouId = pgt.pgtiou
248 if hasattr(ticket, 'proxyticket'):
249 pgt = ticket.proxyticket.proxyGrantingTicket
250 # I am issued by this proxy granting ticket
251 if hasattr(pgt.serviceTicket, 'proxyticket'):
253 if hasattr(pgt.serviceTicket, 'proxyticket'):
254 proxies += (pgt.serviceTicket.service,)
255 pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
261 return _cas2_sucess_response(user, pgtIouId, proxies)
264 def service_validate(request):
265 """Validate ticket via CAS v.2 protocol"""
266 service = request.GET.get('service', None)
267 ticket_string = request.GET.get('ticket', None)
268 pgtUrl = request.GET.get('pgtUrl', None)
269 if ticket_string.startswith('PT-'):
270 return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
272 return ticket_validate(service, ticket_string, pgtUrl)
275 def proxy_validate(request):
276 """Validate ticket via CAS v.2 protocol"""
277 service = request.GET.get('service', None)
278 ticket_string = request.GET.get('ticket', None)
279 pgtUrl = request.GET.get('pgtUrl', None)
280 return ticket_validate(service, ticket_string, pgtUrl)
283 def generate_proxy_granting_ticket(pgt_url, ticket):
284 proxy_callback_good_status = (200, 202, 301, 302, 304)
285 uri = list(urlparse.urlsplit(pgt_url))
287 pgt = ProxyGrantingTicket()
288 pgt.serviceTicket = ticket
289 pgt.targetService = pgt_url
291 if hasattr(ticket, 'proxyGrantingTicket'):
292 # here we got a proxy ticket! tata!
293 pgt.pgt = ticket.proxyGrantingTicket
295 params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
297 query = dict(urlparse.parse_qsl(uri[4]))
300 uri[3] = urlencode(query)
303 response = urllib2.urlopen(urlparse.urlunsplit(uri))
304 except urllib2.HTTPError as e:
305 if not e.code in proxy_callback_good_status:
306 logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
308 except urllib2.URLError as e:
309 logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
316 def _cas2_proxy_success(pt):
317 return HttpResponse(proxy_success(pt))
320 def _cas2_sucess_response(user, pgt=None, proxies=None):
321 return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
324 def _cas2_error_response(code, message=None):
325 return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
326 <cas:authenticationFailure code="%(code)s">
328 </cas:authenticationFailure>
329 </cas:serviceResponse>''' % {
331 'message': message if message else dict(ERROR_MESSAGES).get(code)
332 }, mimetype='text/xml')
335 def proxy_success(pt):
336 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
337 proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
338 proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
339 proxyTicket.text = pt
340 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
343 def auth_success_response(user, pgt, proxies):
344 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
345 auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
346 username = etree.SubElement(auth_success, CAS + 'user')
347 username.text = user.username
350 for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
354 identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
358 # Singular `identifier`, as that is the name of the element tag(s).
359 attrs['identifier'] = identifiers
362 formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
363 formatter(auth_success, attrs)
366 pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
367 pgtElement.text = pgt
370 proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
371 for proxy in proxies:
372 proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
373 proxyElement.text = proxy
375 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')