1 from django.conf import settings
2 from django.contrib.auth import login as auth_login, logout as auth_logout
3 from django.core.urlresolvers import get_callable
4 from django.http import HttpResponse, HttpResponseRedirect
5 from django.shortcuts import render_to_response
6 from django.template import RequestContext
7 from forms import LoginForm
8 from models import ServiceTicket, LoginTicket
11 __all__ = ['login', 'validate', 'logout', 'service_validate']
14 INVALID_TICKET = 'INVALID_TICKET'
15 INVALID_SERVICE = 'INVALID_SERVICE'
16 INVALID_REQUEST = 'INVALID_REQUEST'
17 INTERNAL_ERROR = 'INTERNAL_ERROR'
20 (INVALID_TICKET, u'The provided ticket is invalid.'),
21 (INVALID_SERVICE, u'Service is invalid'),
22 (INVALID_REQUEST, u'Not all required parameters were sent.'),
23 (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
27 def login(request, template_name='cas/login.html', \
28 success_redirect=settings.LOGIN_REDIRECT_URL,
29 warn_template_name='cas/warn.html',
30 form_class=LoginForm):
31 service = request.GET.get('service', None)
32 if request.user.is_authenticated():
33 if service is not None:
34 if request.GET.get('warn', False):
35 return render_to_response(warn_template_name, {
38 }, context_instance=RequestContext(request))
39 ticket = ServiceTicket.objects.create(service=service, user=request.user)
40 return HttpResponseRedirect(ticket.get_redirect_url())
42 return HttpResponseRedirect(success_redirect)
43 if request.method == 'POST':
44 form = form_class(data=request.POST, request=request)
46 user = form.get_user()
47 auth_login(request, user)
48 service = form.cleaned_data.get('service')
49 if service is not None:
50 ticket = ServiceTicket.objects.create(service=service, user=user)
51 success_redirect = ticket.get_redirect_url()
52 return HttpResponseRedirect(success_redirect)
54 form = form_class(request=request, initial={
56 'lt': LoginTicket.objects.create()
58 if hasattr(request, 'session') and hasattr(request.session, 'set_test_cookie'):
59 request.session.set_test_cookie()
60 return render_to_response(template_name, {
62 'errors': form.get_errors() if hasattr(form, 'get_errors') else None,
63 }, context_instance=RequestContext(request))
66 def validate(request):
67 """Validate ticket via CAS v.1 protocol"""
68 service = request.GET.get('service', None)
69 ticket_string = request.GET.get('ticket', None)
70 if service is not None and ticket_string is not None:
71 #renew = request.GET.get('renew', True)
73 # TODO: check user SSO session
75 ticket = ServiceTicket.objects.get(ticket=ticket_string)
76 assert ticket.service == service
77 username = ticket.user.username
79 return HttpResponse("yes\n%s\n" % username)
82 return HttpResponse("no\n\n")
85 def logout(request, template_name='cas/logout.html', \
86 auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
87 url = request.GET.get('url', None)
88 if request.user.is_authenticated():
90 if url and auto_redirect:
91 return HttpResponseRedirect(url)
92 return render_to_response(template_name, {'url': url}, \
93 context_instance=RequestContext(request))
96 def service_validate(request):
97 """Validate ticket via CAS v.2 protocol"""
98 service = request.GET.get('service', None)
99 ticket_string = request.GET.get('ticket', None)
100 if service is None or ticket_string is None:
101 return _cas2_error_response(INVALID_REQUEST)
104 ticket = ServiceTicket.objects.get(ticket=ticket_string)
105 except ServiceTicket.DoesNotExist:
106 return _cas2_error_response(INVALID_TICKET)
108 if ticket.service != service:
110 return _cas2_error_response(INVALID_SERVICE)
114 return _cas2_sucess_response(user)
117 def _cas2_error_response(code):
118 return HttpResponse(u''''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
119 <cas:authenticationFailure code="%(code)s">
121 </cas:authenticationFailure>
122 </cas:serviceResponse>''' % {
124 'message': dict(ERROR_MESSAGES).get(code)
125 }, mimetype='text/xml')
128 def _cas2_sucess_response(user):
129 return HttpResponse(auth_success_response(user), mimetype='text/xml')
132 def auth_success_response(user):
133 from attribute_formatters import CAS, NSMAP, etree
135 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
136 auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
137 username = etree.SubElement(auth_success, CAS + 'user')
138 username.text = user.username
140 if settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK:
141 callback = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK)
142 attrs = callback(user)
144 formater = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
145 formater(auth_success, attrs)
146 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')