2 logger = logging.getLogger('cas_provider.views')
6 from urllib import urlencode
10 from django.http import HttpResponse, HttpResponseRedirect
11 from django.conf import settings
12 from django.contrib.auth import login as auth_login, logout as auth_logout
13 from django.core.urlresolvers import get_callable
14 from django.shortcuts import render_to_response
15 from django.template import RequestContext
16 from django.contrib.auth import authenticate
17 from django.core.urlresolvers import reverse
19 from lxml import etree
20 from cas_provider.attribute_formatters import NSMAP, CAS
21 from cas_provider.models import ProxyGrantingTicket, ProxyTicket
22 from cas_provider.models import ServiceTicket
24 from cas_provider.exceptions import SameEmailMismatchedPasswords
25 from cas_provider.forms import LoginForm, MergeLoginForm
29 __all__ = ['login', 'validate', 'logout', 'service_validate']
31 INVALID_TICKET = 'INVALID_TICKET'
32 INVALID_SERVICE = 'INVALID_SERVICE'
33 INVALID_REQUEST = 'INVALID_REQUEST'
34 INTERNAL_ERROR = 'INTERNAL_ERROR'
37 (INVALID_TICKET, u'The provided ticket is invalid.'),
38 (INVALID_SERVICE, u'Service is invalid'),
39 (INVALID_REQUEST, u'Not all required parameters were sent.'),
40 (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
44 logger = logging.getLogger(__name__)
47 def login(request, template_name='cas/login.html',
48 success_redirect=settings.LOGIN_REDIRECT_URL,
49 warn_template_name='cas/warn.html', **kwargs):
50 merge = kwargs.get('merge', False)
51 logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
52 request.method, merge, template_name)
54 service = request.GET.get('service', None)
55 if service is not None:
56 # Save the service on the session, for later use if we end up
57 # in one of the more complicated workflows.
58 request.session['service'] = service
64 if request.method == 'POST':
66 form = MergeLoginForm(request.POST, request=request)
68 form = LoginForm(request.POST, request=request)
71 service = form.cleaned_data.get('service', None)
73 auth_args = dict(username=form.cleaned_data['email'],
74 password=form.cleaned_data['password'])
76 # We only want to send the merge argument if it's
77 # True. If it it's False, we want it to propagate
78 # through the auth backends properly.
79 auth_args['merge'] = merge
80 user = authenticate(**auth_args)
81 except SameEmailMismatchedPasswords:
82 # Need to merge the accounts?
84 # We shouldn't get here...
87 base_url = reverse('cas_provider_merge')
89 success_redirect=success_redirect,
90 email=form.cleaned_data['email'],
92 if service is not None:
93 args['service'] = service
94 args = urllib.urlencode(args)
96 url = '%s?%s' % (base_url, args)
97 logging.debug('Redirecting to %s', url)
98 return HttpResponseRedirect(url)
101 errors.append('Incorrect username and/or password.')
104 auth_login(request, user)
106 else: # Not a POST...
108 form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
110 form = LoginForm(initial={'service': service})
112 if user is not None and user.is_authenticated():
113 # We have an authenticated user.
114 if not user.is_active:
115 errors.append('This account is disabled.')
117 # Send the on_cas_login signal. If we get an HttpResponse, return that.
118 for receiver, response in signals.on_cas_login.send(sender=login, request=request, **kwargs):
119 if isinstance(response, HttpResponse):
123 # Try and pull the service off the session
124 service = request.session.pop('service', service)
126 signals.on_cas_login_success.send(sender=login, request=request,
127 service=service, **kwargs)
130 # Normal internal success redirection.
131 logging.debug('Redirecting to %s', success_redirect)
132 return HttpResponseRedirect(success_redirect)
134 if request.GET.get('warn', False):
135 return render_to_response(warn_template_name, {
138 }, context_instance=RequestContext(request))
140 # Create a service ticket and redirect to the service.
141 ticket = ServiceTicket.objects.create(service=service, user=user)
142 if 'service' in request.session:
143 # Don't need this any more.
144 del request.session['service']
146 url = ticket.get_redirect_url()
147 logging.debug('Redirecting to %s', url)
148 return HttpResponseRedirect(url)
150 logging.debug('Rendering response on %s, merge is %s', template_name, merge)
151 return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
154 def validate(request):
155 """Validate ticket via CAS v.1 protocol
157 service = request.GET.get('service', None)
158 ticket_string = request.GET.get('ticket', None)
159 logger.info('Validating ticket %s for %s', ticket_string, service)
160 if service is not None and ticket_string is not None:
161 #renew = request.GET.get('renew', True)
163 # TODO: check user SSO session
165 ticket = ServiceTicket.objects.get(ticket=ticket_string)
166 assert ticket.service == service
167 except ServiceTicket.DoesNotExist:
168 logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
169 except Exception as e:
170 logger.exception('Got an exception: %s', e)
172 username = ticket.user.username
175 results = signals.on_cas_collect_histories.send(sender=validate, for_user=ticket.user)
176 histories = '\n'.join('\n'.join(rs) for rc, rs in results)
177 logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
178 return HttpResponse("yes\n%s\n%s" % (username, histories))
180 logger.info('Validation failed.')
181 return HttpResponse("no\n\n")
184 def logout(request, template_name='cas/logout.html',
185 auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
186 url = request.GET.get('url', None)
187 if request.user.is_authenticated():
188 for ticket in ServiceTicket.objects.filter(user=request.user):
191 if url and auto_redirect:
192 return HttpResponseRedirect(url)
193 return render_to_response(template_name, {'url': url},
194 context_instance=RequestContext(request))
198 targetService = request.GET['targetService']
199 pgt_id = request.GET['pgt']
202 proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
203 except ProxyGrantingTicket.DoesNotExist:
204 return _cas2_error_response(INVALID_TICKET)
206 pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
207 user=proxyGrantingTicket.serviceTicket.user,
208 service=targetService)
209 return _cas2_proxy_success(pt.ticket)
212 def ticket_validate(service, ticket_string, pgtUrl):
213 if service is None or ticket_string is None:
214 return _cas2_error_response(INVALID_REQUEST)
217 if ticket_string.startswith('ST'):
218 ticket = ServiceTicket.objects.get(ticket=ticket_string)
219 elif ticket_string.startswith('PT'):
220 ticket = ProxyTicket.objects.get(ticket=ticket_string)
222 return _cas2_error_response(INVALID_TICKET,
223 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
224 'ticket': ticket_string})
225 except ServiceTicket.DoesNotExist:
226 return _cas2_error_response(INVALID_TICKET)
228 ticketUrl = urlparse.urlparse(ticket.service)
229 serviceUrl = urlparse.urlparse(service)
231 if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
232 return _cas2_error_response(INVALID_SERVICE)
236 if pgtUrl is not None:
237 pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
239 pgtIouId = pgt.pgtiou
241 if hasattr(ticket, 'proxyticket'):
242 pgt = ticket.proxyticket.proxyGrantingTicket
243 # I am issued by this proxy granting ticket
244 if hasattr(pgt.serviceTicket, 'proxyticket'):
246 if hasattr(pgt.serviceTicket, 'proxyticket'):
247 proxies += (pgt.serviceTicket.service,)
248 pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
254 return _cas2_sucess_response(user, pgtIouId, proxies)
257 def service_validate(request):
258 """Validate ticket via CAS v.2 protocol"""
259 service = request.GET.get('service', None)
260 ticket_string = request.GET.get('ticket', None)
261 pgtUrl = request.GET.get('pgtUrl', None)
262 if ticket_string.startswith('PT-'):
263 return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
265 return ticket_validate(service, ticket_string, pgtUrl)
268 def proxy_validate(request):
269 """Validate ticket via CAS v.2 protocol"""
270 service = request.GET.get('service', None)
271 ticket_string = request.GET.get('ticket', None)
272 pgtUrl = request.GET.get('pgtUrl', None)
273 return ticket_validate(service, ticket_string, pgtUrl)
276 def generate_proxy_granting_ticket(pgt_url, ticket):
277 proxy_callback_good_status = (200, 202, 301, 302, 304)
278 uri = list(urlparse.urlsplit(pgt_url))
280 pgt = ProxyGrantingTicket()
281 pgt.serviceTicket = ticket
282 pgt.targetService = pgt_url
284 if hasattr(ticket, 'proxyGrantingTicket'):
285 # here we got a proxy ticket! tata!
286 pgt.pgt = ticket.proxyGrantingTicket
288 params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
290 query = dict(urlparse.parse_qsl(uri[4]))
293 uri[3] = urlencode(query)
296 response = urllib2.urlopen(urlparse.urlunsplit(uri))
297 except urllib2.HTTPError as e:
298 if not e.code in proxy_callback_good_status:
299 logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
301 except urllib2.URLError as e:
302 logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
309 def _cas2_proxy_success(pt):
310 return HttpResponse(proxy_success(pt))
313 def _cas2_sucess_response(user, pgt=None, proxies=None):
314 return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
317 def _cas2_error_response(code, message=None):
318 return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
319 <cas:authenticationFailure code="%(code)s">
321 </cas:authenticationFailure>
322 </cas:serviceResponse>''' % {
324 'message': message if message else dict(ERROR_MESSAGES).get(code)
325 }, mimetype='text/xml')
328 def proxy_success(pt):
329 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
330 proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
331 proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
332 proxyTicket.text = pt
333 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
336 def auth_success_response(user, pgt, proxies):
337 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
338 auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
339 username = etree.SubElement(auth_success, CAS + 'user')
340 username.text = user.username
343 for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
347 identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
351 attrs['identifiers'] = identifiers
354 formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
355 formatter(auth_success, attrs)
358 pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
359 pgtElement.text = pgt
362 proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
363 for proxy in proxies:
364 proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
365 proxyElement.text = proxy
367 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')