66327228d2446d9c1fa3646f48bf27f284381bad
[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.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
18
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
23
24 from cas_provider.exceptions import SameEmailMismatchedPasswords
25 from cas_provider.forms import LoginForm, MergeLoginForm
26
27 from . import signals
28
29 __all__ = ['login', 'validate', 'logout', 'service_validate']
30
31 INVALID_TICKET = 'INVALID_TICKET'
32 INVALID_SERVICE = 'INVALID_SERVICE'
33 INVALID_REQUEST = 'INVALID_REQUEST'
34 INTERNAL_ERROR = 'INTERNAL_ERROR'
35
36 ERROR_MESSAGES = (
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'),
41     )
42
43
44 logger = logging.getLogger(__name__)
45
46
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)
53
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
59
60     user = request.user
61
62     errors = []
63
64     if request.method == 'POST':
65         if merge:
66             form = MergeLoginForm(request.POST, request=request)
67         else:
68             form = LoginForm(request.POST, request=request)
69
70         if form.is_valid():
71             service = form.cleaned_data.get('service', None)
72             try:
73                 auth_args = dict(username=form.cleaned_data['email'],
74                                  password=form.cleaned_data['password'])
75                 if merge:
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?
83                 if merge:
84                     # We shouldn't get here...
85                     raise
86                 else:
87                     base_url = reverse('cas_provider_merge')
88                     args = dict(
89                         success_redirect=success_redirect,
90                         email=form.cleaned_data['email'],
91                         )
92                     if service is not None:
93                         args['service'] = service
94                     args = urllib.urlencode(args)
95
96                     url = '%s?%s' % (base_url, args)
97                     logging.debug('Redirecting to %s', url)
98                     return HttpResponseRedirect(url)
99             
100             if user is None:
101                 errors.append('Incorrect username and/or password.')
102             else:
103                 if user.is_active:
104                     auth_login(request, user)
105
106     else:  # Not a POST...
107         if merge:
108             form = MergeLoginForm(initial={'service': service, 'email': request.GET.get('email')})
109         else:
110             form = LoginForm(initial={'service': service})
111
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.')
116         else:
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):
120                     return response
121             
122             if service is None:
123                 # Try and pull the service off the session
124                 service = request.session.pop('service', service)
125             
126             if service is None:
127                 # Normal internal success redirection.
128                 logging.debug('Redirecting to %s', success_redirect)
129                 return HttpResponseRedirect(success_redirect)
130             else:
131                 if request.GET.get('warn', False):
132                     return render_to_response(warn_template_name, {
133                         'service': service,
134                         'warn': False
135                     }, context_instance=RequestContext(request))
136                 
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']
142
143                 url = ticket.get_redirect_url()
144                 logging.debug('Redirecting to %s', url)
145                 return HttpResponseRedirect(url)
146
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))
149
150
151 def validate(request):
152     """Validate ticket via CAS v.1 protocol
153     """
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)
159         #if not renew:
160         # TODO: check user SSO session
161         try:
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)
168         else:
169             username = ticket.user.username
170             ticket.delete()
171
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))
176
177     logger.info('Validation failed.')
178     return HttpResponse("no\n\n")
179     
180
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):
186             ticket.delete()
187         auth_logout(request)
188         if url and auto_redirect:
189             return HttpResponseRedirect(url)
190     return render_to_response(template_name, {'url': url},
191         context_instance=RequestContext(request))
192
193
194 def proxy(request):
195     targetService = request.GET['targetService']
196     pgt_id = request.GET['pgt']
197
198     try:
199         proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
200     except ProxyGrantingTicket.DoesNotExist:
201         return _cas2_error_response(INVALID_TICKET)
202
203     pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
204         user=proxyGrantingTicket.serviceTicket.user,
205         service=targetService)
206     return _cas2_proxy_success(pt.ticket)
207
208
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)
212
213     try:
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)
218         else:
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)
224
225     ticketUrl = urlparse.urlparse(ticket.service)
226     serviceUrl = urlparse.urlparse(service)
227
228     if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
229         return _cas2_error_response(INVALID_SERVICE)
230
231     pgtIouId = None
232     proxies = ()
233     if pgtUrl is not None:
234         pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
235         if pgt:
236             pgtIouId = pgt.pgtiou
237
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'):
242             while pgt:
243                 if hasattr(pgt.serviceTicket, 'proxyticket'):
244                     proxies += (pgt.serviceTicket.service,)
245                     pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
246                 else:
247                     pgt = None
248
249     user = ticket.user
250     ticket.delete()
251     return _cas2_sucess_response(user, pgtIouId, proxies)
252
253
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")
261     else:
262         return ticket_validate(service, ticket_string, pgtUrl)
263
264
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)
271
272
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))
276
277     pgt = ProxyGrantingTicket()
278     pgt.serviceTicket = ticket
279     pgt.targetService = pgt_url
280
281     if hasattr(ticket, 'proxyGrantingTicket'):
282         # here we got a proxy ticket! tata!
283         pgt.pgt = ticket.proxyGrantingTicket
284
285     params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
286
287     query = dict(urlparse.parse_qsl(uri[4]))
288     query.update(params)
289
290     uri[3] = urlencode(query)
291
292     try:
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))
297             return
298     except urllib2.URLError as e:
299         logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
300         return
301
302     pgt.save()
303     return pgt
304
305
306 def _cas2_proxy_success(pt):
307     return HttpResponse(proxy_success(pt))
308
309
310 def _cas2_sucess_response(user, pgt=None, proxies=None):
311     return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
312
313
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">
317                 %(message)s
318             </cas:authenticationFailure>
319         </cas:serviceResponse>''' % {
320         'code': code,
321         'message': message if message else dict(ERROR_MESSAGES).get(code)
322     }, mimetype='text/xml')
323
324
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')
331
332
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
338
339     attrs = {}
340     for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
341         if custom:
342             attrs.update(custom)
343
344     identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
345                    for i in rr]
346
347     if identifiers:
348         attrs['identifiers'] = identifiers
349
350     if attrs:
351         formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
352         formatter(auth_success, attrs)
353
354     if pgt:
355         pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
356         pgtElement.text = pgt
357
358     if proxies:
359         proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
360         for proxy in proxies:
361             proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
362             proxyElement.text = proxy
363
364     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')