2 from urllib import urlencode
5 from django.conf import settings
6 from django.contrib.auth import login as auth_login, logout as auth_logout
7 from django.core.urlresolvers import get_callable
8 from django.http import HttpResponse, HttpResponseRedirect
9 from django.shortcuts import render_to_response
10 from django.template import RequestContext
11 from cas_provider.attribute_formatters import NSMAP, CAS
12 from cas_provider.models import ProxyGrantingTicket, ProxyTicket
13 from forms import LoginForm
14 from models import ServiceTicket, LoginTicket
17 __all__ = ['login', 'validate', 'logout', 'service_validate']
19 INVALID_TICKET = 'INVALID_TICKET'
20 INVALID_SERVICE = 'INVALID_SERVICE'
21 INVALID_REQUEST = 'INVALID_REQUEST'
22 INTERNAL_ERROR = 'INTERNAL_ERROR'
25 (INVALID_TICKET, u'The provided ticket is invalid.'),
26 (INVALID_SERVICE, u'Service is invalid'),
27 (INVALID_REQUEST, u'Not all required parameters were sent.'),
28 (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
32 def login(request, template_name='cas/login.html',\
33 success_redirect=settings.LOGIN_REDIRECT_URL,
34 warn_template_name='cas/warn.html',
35 form_class=LoginForm):
36 service = request.GET.get('service', None)
37 if request.user.is_authenticated():
38 if service is not None:
39 if request.GET.get('warn', False):
40 return render_to_response(warn_template_name, {
43 }, context_instance=RequestContext(request))
44 ticket = ServiceTicket.objects.create(service=service, user=request.user)
45 return HttpResponseRedirect(ticket.get_redirect_url())
47 return HttpResponseRedirect(success_redirect)
48 if request.method == 'POST':
49 form = form_class(data=request.POST, request=request)
51 user = form.get_user()
52 auth_login(request, user)
53 service = form.cleaned_data.get('service')
54 if service is not None:
55 ticket = ServiceTicket.objects.create(service=service, user=user)
56 success_redirect = ticket.get_redirect_url()
57 return HttpResponseRedirect(success_redirect)
59 form = form_class(request=request, initial={
61 'lt': LoginTicket.objects.create()
63 if hasattr(request, 'session') and hasattr(request.session, 'set_test_cookie'):
64 request.session.set_test_cookie()
65 return render_to_response(template_name, {
67 'errors': form.get_errors() if hasattr(form, 'get_errors') else None,
68 }, context_instance=RequestContext(request))
71 def validate(request):
72 """Validate ticket via CAS v.1 protocol"""
73 service = request.GET.get('service', None)
74 ticket_string = request.GET.get('ticket', None)
75 if service is not None and ticket_string is not None:
76 #renew = request.GET.get('renew', True)
78 # TODO: check user SSO session
80 ticket = ServiceTicket.objects.get(ticket=ticket_string)
81 assert ticket.service == service
82 username = ticket.user.username
83 return HttpResponse("yes\n%s\n" % username)
86 return HttpResponse("no\n\n")
89 def logout(request, template_name='cas/logout.html',
90 auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
91 url = request.GET.get('url', None)
92 if request.user.is_authenticated():
93 for ticket in ServiceTicket.objects.filter(user = request.user):
96 if url and auto_redirect:
97 return HttpResponseRedirect(url)
98 return render_to_response(template_name, {'url': url},\
99 context_instance=RequestContext(request))
102 targetService = request.GET['targetService']
103 pgtiou = request.GET['pgt']
106 proxyGrantingTicket = ProxyGrantingTicket.objects.get(pgtiou=pgtiou)
107 except ProxyGrantingTicket.DoesNotExist:
108 return _cas2_error_response(INVALID_TICKET)
110 pt = ProxyTicket.objects.create(proxyGrantingTicket = proxyGrantingTicket,
111 user=proxyGrantingTicket.serviceTicket.user,
112 service=targetService)
113 return _cas2_proxy_success(pt.ticket)
116 def ticket_validate(service, ticket_string, pgtUrl):
117 if service is None or ticket_string is None:
118 return _cas2_error_response(INVALID_REQUEST)
121 ticket = ServiceTicket.objects.get(ticket=ticket_string)
122 except ServiceTicket.DoesNotExist:
123 return _cas2_error_response(INVALID_TICKET)
125 if ticket.service != service:
126 return _cas2_error_response(INVALID_SERVICE)
131 if pgtUrl is not None:
132 pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
134 pgtIouId = pgt.pgtiou
137 proxies += (pgt.serviceTicket.service,)
138 pgt = pgt.serviceTicket.proxyGrantingTicket if hasattr(pgt.serviceTicket, 'proxyGrantingTicket') else None
142 return _cas2_sucess_response(user, pgtIouId, proxies)
145 def service_validate(request):
146 """Validate ticket via CAS v.2 protocol"""
147 service = request.GET.get('service', None)
148 ticket_string = request.GET.get('ticket', None)
149 pgtUrl = request.GET.get('pgtUrl', None)
150 if ticket_string.startswith('PT-'):
151 return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
153 return ticket_validate(service, ticket_string, pgtUrl)
156 def proxy_validate(request):
157 """Validate ticket via CAS v.2 protocol"""
158 service = request.GET.get('service', None)
159 ticket_string = request.GET.get('ticket', None)
160 pgtUrl = request.GET.get('pgtUrl', None)
161 return ticket_validate(service, ticket_string, pgtUrl)
163 def generate_proxy_granting_ticket(pgt_url, ticket):
164 proxy_callback_good_status = (200, 202, 301, 302, 304)
165 uri = list(urlparse.urlsplit(pgt_url))
167 pgt = ProxyGrantingTicket()
168 pgt.serviceTicket = ticket
170 if hasattr(ticket, 'proxyGrantingTicket'):
171 # here we got a proxy ticket! tata!
172 pgt.pgt = ticket.proxyGrantingTicket
174 params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
176 query = dict(urlparse.parse_qsl(uri[4]))
179 uri[4] = urlencode(query)
183 response = urllib2.urlopen(urlparse.urlunsplit(uri))
184 except urllib2.HTTPError, e:
185 if not e.code in proxy_callback_good_status:
187 except urllib2.URLError, e:
194 def _cas2_proxy_success(pt):
195 return HttpResponse(proxy_success(pt))
197 def _cas2_sucess_response(user, pgt = None, proxies = None):
198 return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
200 def _cas2_error_response(code, message = None):
201 return HttpResponse(u''''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
202 <cas:authenticationFailure code="%(code)s">
204 </cas:authenticationFailure>
205 </cas:serviceResponse>''' % {
207 'message': message if message else dict(ERROR_MESSAGES).get(code)
208 }, mimetype='text/xml')
210 def proxy_success(pt):
211 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
212 proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
213 proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
214 proxyTicket.text = pt
215 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
217 def auth_success_response(user, pgt, proxies):
220 response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
221 auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
222 username = etree.SubElement(auth_success, CAS + 'user')
223 username.text = user.username
225 if settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK:
226 callback = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_CALLBACK)
227 attrs = callback(user)
229 formater = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
230 formater(auth_success, attrs)
234 pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
235 pgtElement.text = pgt
238 proxiesElement = etree.SubElement(auth_success , CAS + "proxies")
239 for proxy in proxies:
240 proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
241 proxyElement.text = proxy
245 return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')