1 """CAS authentication middleware"""
3 from urllib import urlencode
5 from django.http import HttpResponseRedirect, HttpResponseForbidden
6 from django.conf import settings
7 from django.contrib.auth import REDIRECT_FIELD_NAME
8 from django.contrib.auth.views import login, logout
9 from django.core.urlresolvers import reverse
11 from django_cas.views import login as cas_login, logout as cas_logout
13 __all__ = ['CASMiddleware']
16 class CASMiddleware(object):
17 """Middleware that allows CAS authentication on admin pages"""
19 def process_request(self, request):
20 """Checks that the authentication middleware is installed"""
22 error = ("The Django CAS middleware requires authentication "
23 "middleware to be installed. Edit your MIDDLEWARE_CLASSES "
24 "setting to insert 'django.contrib.auth.middleware."
25 "AuthenticationMiddleware'.")
26 # assert hasattr(request, 'user'), error
28 def process_view(self, request, view_func, view_args, view_kwargs):
29 """Forwards unauthenticated requests to the admin page to the CAS
30 login URL, as well as calls to django.contrib.auth.views.login and
34 if view_func == login:
35 return cas_login(request, *view_args, **view_kwargs)
36 elif view_func == logout:
37 return cas_logout(request, *view_args, **view_kwargs)
39 if settings.CAS_ADMIN_PREFIX:
40 if not request.path.startswith(settings.CAS_ADMIN_PREFIX):
42 elif not view_func.__module__.startswith('django.contrib.admin.'):
45 if request.user.is_authenticated():
46 if request.user.is_staff:
49 error = ('<h1>Forbidden</h1><p>You do not have staff '
51 return HttpResponseForbidden(error)
52 params = urlencode({REDIRECT_FIELD_NAME: request.get_full_path()})
53 return HttpResponseRedirect(reverse(cas_login) + '?' + params)