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)
127 # Normal internal success redirection.
128 logging.debug('Redirecting to %s', success_redirect)
129 return HttpResponseRedirect(success_redirect)
131 if request.GET.get('warn', False):
132 return render_to_response(warn_template_name, {
135 }, context_instance=RequestContext(request))
137 # Create a service ticket and redirect to the service.
138 ticket = ServiceTicket.objects.create(service=service, user=user)
139 if 'service' in request.session:
140 # Don't need this any more.
141 del request.session['service']
143 url = ticket.get_redirect_url()
144 logging.debug('Redirecting to %s', url)
145 return HttpResponseRedirect(url)
147 logging.debug('Rendering response on %s, merge is %s', template_name, merge)
148 return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
151 def validate(request):
152 """Validate ticket via CAS v.1 protocol
154 service = request.GET.get('service', None)
155 ticket_string = request.GET.get('ticket', None)
156 logger.info('Validating ticket %s for %s', ticket_string, service)
157 if service is not None and ticket_string is not None:
158 #renew = request.GET.get('renew', True)
160 # TODO: check user SSO session
162 ticket = ServiceTicket.objects.get(ticket=ticket_string)
163 assert ticket.service == service
164 except ServiceTicket.DoesNotExist:
165 logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
166 except Exception as e:
167 logger.exception('Got an exception: %s', e)
169 username = ticket.user.username
172 results = signals.on_cas_collect_histories.send(sender=validate, for_user=ticket.user)
173 histories = '\n'.join('\n'.join(rs) for rc, rs in results)
174 logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
175 return HttpResponse("yes\n%s\n%s" % (username, histories))
177 logger.info('Validation failed.')
178 return HttpResponse("no\n\n")
181 def logout(request, template_name='cas/logout.html',
182 auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
183 url = request.GET.get('url', None)
184 if request.user.is_authenticated():
185 for ticket in ServiceTicket.objects.filter(user=request.user):
188 if url and auto_redirect:
189 return HttpResponseRedirect(url)
190 return render_to_response(template_name, {'url': url},
191 context_instance=RequestContext(request))
195 targetService = request.GET['targetService']
196 pgt_id = request.GET['pgt']
199 proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
200 except ProxyGrantingTicket.DoesNotExist:
201 return _cas2_error_response(INVALID_TICKET)
203 pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
204 user=proxyGrantingTicket.serviceTicket.user,
205 service=targetService)
206 return _cas2_proxy_success(pt.ticket)
209 def ticket_validate(service, ticket_string, pgtUrl):
210 if service is None or ticket_string is None:
211 return _cas2_error_response(INVALID_REQUEST)
214 if ticket_string.startswith('ST'):
215 ticket = ServiceTicket.objects.get(ticket=ticket_string)
216 elif ticket_string.startswith('PT'):
217 ticket = ProxyTicket.objects.get(ticket=ticket_string)
219 return _cas2_error_response(INVALID_TICKET,
220 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
221 'ticket': ticket_string})
222 except ServiceTicket.DoesNotExist:
223 return _cas2_error_response(INVALID_TICKET)
225 ticketUrl = urlparse.urlparse(ticket.service)
226 serviceUrl = urlparse.urlparse(service)
228 if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
229 return _cas2_error_response(INVALID_SERVICE)
233 if pgtUrl is not None:
234 pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
236 pgtIouId = pgt.pgtiou
238 if hasattr(ticket, 'proxyticket'):
239 pgt = ticket.proxyticket.proxyGrantingTicket
240 # I am issued by this proxy granting ticket
241 if hasattr(pgt.serviceTicket, 'proxyticket'):
243 if hasattr(pgt.serviceTicket, 'proxyticket'):
244 proxies += (pgt.serviceTicket.service,)
245 pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
251 return _cas2_sucess_response(user, pgtIouId, proxies)
254 def service_validate(request):
255 """Validate ticket via CAS v.2 protocol"""
256 service = request.GET.get('service', None)
257 ticket_string = request.GET.get('ticket', None)
258 pgtUrl = request.GET.get('pgtUrl', None)
259 if ticket_string.startswith('PT-'):
260 return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
262 return ticket_validate(service, ticket_string, pgtUrl)
265 def proxy_validate(request):
266 """Validate ticket via CAS v.2 protocol"""
267 service = request.GET.get('service', None)
268 ticket_string = request.GET.get('ticket', None)
269 pgtUrl = request.GET.get('pgtUrl', None)
270 return ticket_validate(service, ticket_string, pgtUrl)
273 def generate_proxy_granting_ticket(pgt_url, ticket):
274 proxy_callback_good_status = (200, 202, 301, 302, 304)
275 uri = list(urlparse.urlsplit(pgt_url))
277 pgt = ProxyGrantingTicket()
278 pgt.serviceTicket = ticket
279 pgt.targetService = pgt_url
281 if hasattr(ticket, 'proxyGrantingTicket'):
282 # here we got a proxy ticket! tata!
283 pgt.pgt = ticket.proxyGrantingTicket
285 params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
287 query = dict(urlparse.parse_qsl(uri[4]))
290 uri[3] = urlencode(query)
293 response = urllib2.urlopen(urlparse.urlunsplit(uri))
294 except urllib2.HTTPError as e:
295 if not e.code in proxy_callback_good_status:
296 logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
298 except urllib2.URLError as e:
299 logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
306 def _cas2_proxy_success(pt):
307 return HttpResponse(proxy_success(pt))
310 def _cas2_sucess_response(user, pgt=None, proxies=None):
311 return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
314 def _cas2_error_response(code, message=None):
315 return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
316 <cas:authenticationFailure code="%(code)s">
318 </cas:authenticationFailure>
319 </cas:serviceResponse>''' % {
321 'message': message if message else dict(ERROR_MESSAGES).get(code)
322 }, mimetype='text/xml')
325 def proxy_success(pt):
326 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
327 proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
328 proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
329 proxyTicket.text = pt
330 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
333 def auth_success_response(user, pgt, proxies):
334 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
335 auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
336 username = etree.SubElement(auth_success, CAS + 'user')
337 username.text = user.username
340 for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
344 identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
347 attrs['identifiers'] = identifiers
350 formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
351 formatter(auth_success, attrs)
354 pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
355 pgtElement.text = pgt
358 proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
359 for proxy in proxies:
360 proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
361 proxyElement.text = proxy
363 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')