translating error messages
[django-cas-provider.git] / cas_provider / views.py
1 import logging
2 logger = logging.getLogger('cas_provider.views')
3 import urllib
4
5 from urllib import urlencode
6 import urllib2
7 import urlparse
8 from functools import wraps
9
10 from django.utils.decorators import available_attrs
11 from django.views.decorators.debug import sensitive_post_parameters
12 from django.views.decorators.cache import cache_control
13 from django.utils.cache import patch_cache_control
14 from django.views.decorators.csrf import csrf_protect
15
16 from django.http import HttpResponse, HttpResponseRedirect
17 from django.conf import settings
18 from django.contrib.auth import login as auth_login, logout as auth_logout
19 from django.core.urlresolvers import get_callable
20 from django.shortcuts import render_to_response
21 from django.template import RequestContext
22 from django.contrib.auth import authenticate
23 from django.core.urlresolvers import reverse
24 from django.utils.translation import ugettext as _
25
26 from lxml import etree
27 from cas_provider.attribute_formatters import NSMAP, CAS
28 from cas_provider.models import ProxyGrantingTicket, ProxyTicket
29 from cas_provider.models import ServiceTicket
30
31 from cas_provider.forms import LoginForm, MergeLoginForm
32
33 from . import signals
34
35 __all__ = ['login', 'validate', 'logout', 'service_validate']
36
37 INVALID_TICKET = 'INVALID_TICKET'
38 INVALID_SERVICE = 'INVALID_SERVICE'
39 INVALID_REQUEST = 'INVALID_REQUEST'
40 INTERNAL_ERROR = 'INTERNAL_ERROR'
41
42 ERROR_MESSAGES = (
43     (INVALID_TICKET, u'The provided ticket is invalid.'),
44     (INVALID_SERVICE, u'Service is invalid'),
45     (INVALID_REQUEST, u'Not all required parameters were sent.'),
46     (INTERNAL_ERROR, u'An internal error occurred during ticket validation'),
47     )
48
49
50 logger = logging.getLogger(__name__)
51
52
53 _never_cache = cache_control(no_cache=True, must_revalidate=True)
54
55
56 def never_cache(view_func):
57     """
58     Decorator that adds headers to a response so that it will
59     never be cached.
60     """
61     @wraps(view_func, assigned=available_attrs(view_func))
62     def _wrapped_view_func(request, *args, **kwargs):
63         response = view_func(request, *args, **kwargs)
64         patch_cache_control(response, no_cache=True,
65                             must_revalidate=True, proxy_revalidate=True)
66         response['Pragma'] = 'no-cache'
67         return response
68     return _wrapped_view_func
69
70
71 @sensitive_post_parameters()
72 @csrf_protect
73 @never_cache
74 def login(request, template_name='cas/login.html',
75           success_redirect=settings.LOGIN_REDIRECT_URL,
76           warn_template_name='cas/warn.html', **kwargs):
77     merge = kwargs.get('merge', False)
78     logging.debug('CAS Provider Login view. Method is %s, merge is %s, template is %s.',
79                   request.method, merge, template_name)
80
81     service = request.GET.get('service', None)
82     if service is not None:
83         # Save the service on the session, for later use if we end up
84         # in one of the more complicated workflows.
85         request.session['service'] = service
86
87     user = request.user
88
89     errors = []
90
91     if request.method == 'POST':
92         if merge:
93             form = MergeLoginForm(request.POST, request=request)
94         else:
95             form = LoginForm(request.POST, request=request)
96
97         if form.is_valid():
98             service = form.cleaned_data.get('service', None)
99             try:
100                 auth_args = dict(username=form.cleaned_data['username'],
101                                  password=form.cleaned_data['password'])
102                 if merge:
103                     # We only want to send the merge argument if it's
104                     # True. If it it's False, we want it to propagate
105                     # through the auth backends properly.
106                     auth_args['merge'] = merge
107                 user = authenticate(**auth_args)
108             except:
109                 # Need to merge the accounts?
110                 if merge:
111                     # We shouldn't get here...
112                     raise
113                 else:
114                     base_url = reverse('cas_provider_merge')
115                     args = dict(
116                         success_redirect=success_redirect,
117                         username=form.cleaned_data['username'],
118                         )
119                     if service is not None:
120                         args['service'] = service
121                     args = urllib.urlencode(args)
122
123                     url = '%s?%s' % (base_url, args)
124                     logging.debug('Redirecting to %s', url)
125                     return HttpResponseRedirect(url)
126
127             if user is None:
128                 errors.append(_('Incorrect username and/or password.'))
129             else:
130                 if user.is_active:
131                     auth_login(request, user)
132
133     else:  # Not a POST...
134         if merge:
135             form = MergeLoginForm(initial={'service': service, 'username': request.GET.get('username')})
136         else:
137             form = LoginForm(initial={'service': service})
138
139     if user is not None and user.is_authenticated():
140         # We have an authenticated user.
141         if not user.is_active:
142             errors.append(_('This account is disabled. Please contact us if you feel it should be enabled again.'))
143         else:
144             # Send the on_cas_login signal. If we get an HttpResponse, return that.
145             for receiver, response in signals.on_cas_login.send(sender=login, request=request, **kwargs):
146                 if isinstance(response, HttpResponse):
147                     return response
148
149             if service is None:
150                 # Try and pull the service off the session
151                 service = request.session.pop('service', service)
152
153             signals.on_cas_login_success.send(sender=login, request=request,
154                                               service=service, **kwargs)
155
156             if service is None:
157                 # Normal internal success redirection.
158                 logging.debug('Redirecting to %s', success_redirect)
159                 return HttpResponseRedirect(success_redirect)
160             else:
161                 if request.GET.get('warn', False):
162                     return render_to_response(warn_template_name, {
163                         'service': service,
164                         'warn': False
165                     }, context_instance=RequestContext(request))
166
167                 # Create a service ticket and redirect to the service.
168                 ticket = ServiceTicket.objects.create(service=service, user=user)
169                 if 'service' in request.session:
170                     # Don't need this any more.
171                     del request.session['service']
172
173                 url = ticket.get_redirect_url()
174                 logging.debug('Redirecting to %s', url)
175                 return HttpResponseRedirect(url)
176
177     logging.debug('Rendering response on %s, merge is %s', template_name, merge)
178     return render_to_response(template_name, {'form': form, 'errors': errors}, context_instance=RequestContext(request))
179
180
181 @never_cache
182 def validate(request):
183     """Validate ticket via CAS v.1 protocol
184     """
185     service = request.GET.get('service', None)
186     ticket_string = request.GET.get('ticket', None)
187     logger.info('Validating ticket %s for %s', ticket_string, service)
188     if service is not None and ticket_string is not None:
189         #renew = request.GET.get('renew', True)
190         #if not renew:
191         # TODO: check user SSO session
192         try:
193             ticket = ServiceTicket.objects.get(ticket=ticket_string)
194             assert ticket.service == service
195         except ServiceTicket.DoesNotExist:
196             logger.exception("Tried to validate with an invalid ticket %s for %s", ticket_string, service)
197         except Exception as e:
198             logger.exception('Got an exception: %s', e)
199         else:
200             username = ticket.user.username
201             ticket.delete()
202
203             results = signals.on_cas_collect_histories.send(sender=validate, for_user=ticket.user)
204             histories = '\n'.join('\n'.join(rs) for rc, rs in results)
205             logger.info('Validated %s %s', username, "(also %s)" % histories if histories else '')
206             return HttpResponse("yes\n%s\n%s" % (username, histories))
207
208     logger.info('Validation failed.')
209     return HttpResponse("no\n\n")
210
211
212 @never_cache
213 def logout(request, template_name='cas/logout.html',
214            auto_redirect=settings.CAS_AUTO_REDIRECT_AFTER_LOGOUT):
215     url = request.GET.get('url', None)
216     if request.user.is_authenticated():
217         for ticket in ServiceTicket.objects.filter(user=request.user):
218             ticket.delete()
219         auth_logout(request)
220         if url and auto_redirect:
221             return HttpResponseRedirect(url)
222     return render_to_response(template_name, {'url': url},
223         context_instance=RequestContext(request))
224
225
226 @never_cache
227 def proxy(request):
228     targetService = request.GET['targetService']
229     pgt_id = request.GET['pgt']
230
231     try:
232         proxyGrantingTicket = ProxyGrantingTicket.objects.get(ticket=pgt_id)
233     except ProxyGrantingTicket.DoesNotExist:
234         return _cas2_error_response(INVALID_TICKET)
235
236     pt = ProxyTicket.objects.create(proxyGrantingTicket=proxyGrantingTicket,
237         user=proxyGrantingTicket.serviceTicket.user,
238         service=targetService)
239     return _cas2_proxy_success(pt.ticket)
240
241
242 def ticket_validate(service, ticket_string, pgtUrl):
243     if service is None or ticket_string is None:
244         return _cas2_error_response(INVALID_REQUEST)
245
246     try:
247         if ticket_string.startswith('ST'):
248             ticket = ServiceTicket.objects.get(ticket=ticket_string)
249         elif ticket_string.startswith('PT'):
250             ticket = ProxyTicket.objects.get(ticket=ticket_string)
251         else:
252             return _cas2_error_response(INVALID_TICKET,
253                 '%(ticket)s is neither Service (ST-...) nor Proxy Ticket (PT-...)' % {
254                     'ticket': ticket_string})
255     except ServiceTicket.DoesNotExist:
256         return _cas2_error_response(INVALID_TICKET)
257
258     ticketUrl = urlparse.urlparse(ticket.service)
259     serviceUrl = urlparse.urlparse(service)
260
261     if not(ticketUrl.hostname == serviceUrl.hostname and ticketUrl.path == serviceUrl.path and ticketUrl.port == serviceUrl.port):
262         return _cas2_error_response(INVALID_SERVICE)
263
264     pgtIouId = None
265     proxies = ()
266     if pgtUrl is not None:
267         pgt = generate_proxy_granting_ticket(pgtUrl, ticket)
268         if pgt:
269             pgtIouId = pgt.pgtiou
270
271     if hasattr(ticket, 'proxyticket'):
272         pgt = ticket.proxyticket.proxyGrantingTicket
273         # I am issued by this proxy granting ticket
274         if hasattr(pgt.serviceTicket, 'proxyticket'):
275             while pgt:
276                 if hasattr(pgt.serviceTicket, 'proxyticket'):
277                     proxies += (pgt.serviceTicket.service,)
278                     pgt = pgt.serviceTicket.proxyticket.proxyGrantingTicket
279                 else:
280                     pgt = None
281
282     user = ticket.user
283     ticket.delete()
284     return _cas2_sucess_response(user, pgtIouId, proxies)
285
286
287 @never_cache
288 def service_validate(request):
289     """Validate ticket via CAS v.2 protocol"""
290     service = request.GET.get('service', None)
291     ticket_string = request.GET.get('ticket', None)
292     pgtUrl = request.GET.get('pgtUrl', None)
293     if ticket_string.startswith('PT-'):
294         return _cas2_error_response(INVALID_TICKET, "serviceValidate cannot verify proxy tickets")
295     else:
296         return ticket_validate(service, ticket_string, pgtUrl)
297
298
299 @never_cache
300 def proxy_validate(request):
301     """Validate ticket via CAS v.2 protocol"""
302     service = request.GET.get('service', None)
303     ticket_string = request.GET.get('ticket', None)
304     pgtUrl = request.GET.get('pgtUrl', None)
305     return ticket_validate(service, ticket_string, pgtUrl)
306
307
308 def generate_proxy_granting_ticket(pgt_url, ticket):
309     proxy_callback_good_status = (200, 202, 301, 302, 304)
310     uri = list(urlparse.urlsplit(pgt_url))
311
312     pgt = ProxyGrantingTicket()
313     pgt.serviceTicket = ticket
314     pgt.targetService = pgt_url
315
316     if hasattr(ticket, 'proxyGrantingTicket'):
317         # here we got a proxy ticket! tata!
318         pgt.pgt = ticket.proxyGrantingTicket
319
320     params = {'pgtId': pgt.ticket, 'pgtIou': pgt.pgtiou}
321
322     query = dict(urlparse.parse_qsl(uri[4]))
323     query.update(params)
324
325     uri[3] = urlencode(query)
326
327     try:
328         urllib2.urlopen(urlparse.urlunsplit(uri))
329     except urllib2.HTTPError as e:
330         if not e.code in proxy_callback_good_status:
331             logger.debug('Checking Proxy Callback URL {} returned {}. Not issuing PGT.'.format(uri, e.code))
332             return
333     except urllib2.URLError as e:
334         logger.debug('Checking Proxy Callback URL {} raised URLError. Not issuing PGT.'.format(uri))
335         return
336
337     pgt.save()
338     return pgt
339
340
341 def _cas2_proxy_success(pt):
342     return HttpResponse(proxy_success(pt))
343
344
345 def _cas2_sucess_response(user, pgt=None, proxies=None):
346     return HttpResponse(auth_success_response(user, pgt, proxies), mimetype='text/xml')
347
348
349 def _cas2_error_response(code, message=None):
350     return HttpResponse(u'''<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
351             <cas:authenticationFailure code="%(code)s">
352                 %(message)s
353             </cas:authenticationFailure>
354         </cas:serviceResponse>''' % {
355         'code': code,
356         'message': message if message else dict(ERROR_MESSAGES).get(code)
357     }, mimetype='text/xml')
358
359
360 def proxy_success(pt):
361     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
362     proxySuccess = etree.SubElement(response, CAS + 'proxySuccess')
363     proxyTicket = etree.SubElement(proxySuccess, CAS + 'proxyTicket')
364     proxyTicket.text = pt
365     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')
366
367
368 def auth_success_response(user, pgt, proxies):
369     response = etree.Element(CAS + 'serviceResponse', nsmap=NSMAP)
370     auth_success = etree.SubElement(response, CAS + 'authenticationSuccess')
371     username = etree.SubElement(auth_success, CAS + 'user')
372     username.text = user.username
373
374     attrs = {}
375     for receiver, custom in signals.cas_collect_custom_attributes.send(sender=auth_success_response, user=user):
376         if custom:
377             attrs.update(custom)
378
379     identifiers = [i for sr, rr in signals.on_cas_collect_histories.send(sender=validate, for_user=user)
380                    for i in rr]
381
382     if identifiers:
383         # Singular `identifier`, as that is the name of the element tag(s).
384         attrs['identifier'] = identifiers
385
386     if attrs:
387         formatter = get_callable(settings.CAS_CUSTOM_ATTRIBUTES_FORMATER)
388         formatter(auth_success, attrs)
389
390     if pgt:
391         pgtElement = etree.SubElement(auth_success, CAS + 'proxyGrantingTicket')
392         pgtElement.text = pgt
393
394     if proxies:
395         proxiesElement = etree.SubElement(auth_success, CAS + "proxies")
396         for proxy in proxies:
397             proxyElement = etree.SubElement(proxiesElement, CAS + "proxy")
398             proxyElement.text = proxy
399
400     return unicode(etree.tostring(response, encoding='utf-8'), 'utf-8')