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']
15 class CASMiddleware(object):
16 """Middleware that allows CAS authentication on admin pages"""
18 def process_request(self, request):
19 """Checks that the authentication middleware is installed"""
21 error = ("The Django CAS middleware requires authentication "
22 "middleware to be installed. Edit your MIDDLEWARE_CLASSES "
23 "setting to insert 'django.contrib.auth.middleware."
24 "AuthenticationMiddleware'.")
25 # assert hasattr(request, 'user'), error
27 def process_view(self, request, view_func, view_args, view_kwargs):
28 """Forwards unauthenticated requests to the admin page to the CAS
29 login URL, as well as calls to django.contrib.auth.views.login and
33 if view_func == login:
34 return cas_login(request, *view_args, **view_kwargs)
35 elif view_func == logout:
36 return cas_logout(request, *view_args, **view_kwargs)
38 if settings.CAS_ADMIN_PREFIX:
39 if not request.path.startswith(settings.CAS_ADMIN_PREFIX):
41 elif not view_func.__module__.startswith('django.contrib.admin.'):
44 if request.user.is_authenticated():
45 if request.user.is_staff:
48 error = ('<h1>Forbidden</h1><p>You do not have staff '
50 return HttpResponseForbidden(error)
51 params = urlencode({REDIRECT_FIELD_NAME: request.get_full_path()})
52 return HttpResponseRedirect(reverse(cas_login) + '?' + params)