3883ed02bb050329a6c111409b06a7de8ce77a12
[django-cas-provider.git] / cas_provider / views.py
1 import logging
2 logger = logging.getLogger('cas_provider.views')
3 import urllib
4
5 import logging
6 from urllib import urlencode
7 import urllib2
8 import urlparse
9
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
13
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
22
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
27
28 from cas_provider.exceptions import SameEmailMismatchedPasswords
29 from cas_provider.forms import LoginForm, MergeLoginForm
30
31 from . import signals
32
33 __all__ = ['login', 'validate', 'logout', 'service_validate']
34
35 INVALID_TICKET = 'INVALID_TICKET'
36 INVALID_SERVICE = 'INVALID_SERVICE'
37 INVALID_REQUEST = 'INVALID_REQUEST'
38 INTERNAL_ERROR = 'INTERNAL_ERROR'
39
40 ERROR_MESSAGES = (
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'),
45     )
46
47
48 logger = logging.getLogger(__name__)
49
50
51 @sensitive_post_parameters()
52 @csrf_protect
53 @never_cache
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)
60
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
66
67     user = request.user
68
69     errors = []
70
71     if request.method == 'POST':
72         if merge:
73             form = MergeLoginForm(request.POST, request=request)
74         else:
75             form = LoginForm(request.POST, request=request)
76
77         if form.is_valid():
78             service = form.cleaned_data.get('service', None)
79             try:
80                 auth_args = dict(username=form.cleaned_data['email'],
81                                  password=form.cleaned_data['password'])
82                 if merge:
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?
90                 if merge:
91                     # We shouldn't get here...
92                     raise
93                 else:
94                     base_url = reverse('cas_provider_merge')
95                     args = dict(
96                         success_redirect=success_redirect,
97                         email=form.cleaned_data['email'],
98                         )
99                     if service is not None:
100                         args['service'] = service
101                     args = urllib.urlencode(args)
102
103                     url = '%s?%s' % (base_url, args)
104                     logging.debug('Redirecting to %s', url)
105                     return HttpResponseRedirect(url)
106             
107             if user is None:
108                 errors.append('Incorrect username and/or password.')
109             else:
110                 if user.is_active:
111                     auth_login(request, user)
112
113     else:  # Not a POST...
114         if merge:
115             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
116         else:
117             form = LoginForm(initial={'service': service})
118
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.')
123         else:
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):
127                     return response
128             
129             if service is None:
130                 # Try and pull the service off the session
131                 service = request.session.pop('service', service)
132             
133             signals.on_cas_login_success.send(sender=login, request=request,
134                                               service=service, **kwargs)
135
136             if service is None:
137                 # Normal internal success redirection.
138                 logging.debug('Redirecting to %s', success_redirect)
139                 return HttpResponseRedirect(success_redirect)
140             else:
141                 if request.GET.get('warn', False):
142                     return render_to_response(warn_template_name, {
143                         'service': service,
144                         'warn': False
145                     }, context_instance=RequestContext(request))
146                 
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']
152
153                 url = ticket.get_redirect_url()
154                 logging.debug('Redirecting to %s', url)
155                 return HttpResponseRedirect(url)
156
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))
159
160
161 def validate(request):
162     """Validate ticket via CAS v.1 protocol
163     """
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)
169         #if not renew:
170         # TODO: check user SSO session
171         try:
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)
178         else:
179             username = ticket.user.username
180             ticket.delete()
181
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))
186
187     logger.info('Validation failed.')
188     return HttpResponse("no\n\n")
189     
190
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):
196             ticket.delete()
197         auth_logout(request)
198         if url and auto_redirect:
199             return HttpResponseRedirect(url)
200     return render_to_response(template_name, {'url': url},
201         context_instance=RequestContext(request))
202
203
204 def proxy(request):
205     targetService = request.GET['targetService']
206     pgt_id = request.GET['pgt']
207
208     try:
209         proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
210     except ProxyGrantingTicket.DoesNotExist:
211         return _cas2_error_response(INVALID_TICKET)
212
213     pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
214         user=proxyGrantingTicket.serviceTicket.user,
215         service=targetService)
216     return _cas2_proxy_success(pt.ticket)
217
218
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)
222
223     try:
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)
228         else:
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)
234
235     ticketUrl = urlparse.urlparse(ticket.service)
236     serviceUrl = urlparse.urlparse(service)
237
238     if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
239         return _cas2_error_response(INVALID_SERVICE)
240
241     pgtIouId = None
242     proxies = ()
243     if pgtUrl is not None:
244         pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
245         if pgt:
246             pgtIouId = pgt.pgtiou
247
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'):
252             while pgt:
253                 if hasattr(pgt.serviceTicket, 'proxyticket'):
254                     proxies += (pgt.serviceTicket.service,)
255                     pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
256                 else:
257                     pgt = None
258
259     user = ticket.user
260     ticket.delete()
261     return _cas2_sucess_response(user, pgtIouId, proxies)
262
263
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")
271     else:
272         return ticket_validate(service, ticket_string, pgtUrl)
273
274
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)
281
282
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))
286
287     pgt = ProxyGrantingTicket()
288     pgt.serviceTicket = ticket
289     pgt.targetService = pgt_url
290
291     if hasattr(ticket, 'proxyGrantingTicket'):
292         # here we got a proxy ticket! tata!
293         pgt.pgt = ticket.proxyGrantingTicket
294
295     params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
296
297     query = dict(urlparse.parse_qsl(uri[4]))
298     query.update(params)
299
300     uri[3] = urlencode(query)
301
302     try:
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))
307             return
308     except urllib2.URLError as e:
309         logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
310         return
311
312     pgt.save()
313     return pgt
314
315
316 def _cas2_proxy_success(pt):
317     return HttpResponse(proxy_success(pt))
318
319
320 def _cas2_sucess_response(user, pgt=None, proxies=None):
321     return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
322
323
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">
327                 %(message)s
328             </cas:authenticationFailure>
329         </cas:serviceResponse>''' % {
330         'code': code,
331         'message': message if message else dict(ERROR_MESSAGES).get(code)
332     }, mimetype='text/xml')
333
334
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')
341
342
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
348
349     attrs = {}
350     for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
351         if custom:
352             attrs.update(custom)
353
354     identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
355                    for i in rr]
356
357     if identifiers:
358         # Singular `identifier`, as that is the name of the element tag(s).
359         attrs['identifier'] = identifiers
360
361     if attrs:
362         formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
363         formatter(auth_success, attrs)
364
365     if pgt:
366         pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
367         pgtElement.text = pgt
368
369     if proxies:
370         proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
371         for proxy in proxies:
372             proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
373             proxyElement.text = proxy
374
375     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')