make dvcs models abstract,
[redakcja.git] / apps / django_cas / middleware.py
1 """CAS authentication middleware"""
2
3 from urllib import urlencode
4
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
10
11 from django_cas.views import login as cas_login, logout as cas_logout
12
13 __all__ = ['CASMiddleware']
14
15
16 class CASMiddleware(object):
17     """Middleware that allows CAS authentication on admin pages"""
18
19     def process_request(self, request):
20         """Checks that the authentication middleware is installed"""
21
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
27
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
31         logout.
32         """
33
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)
38
39         if settings.CAS_ADMIN_PREFIX:
40             if not request.path.startswith(settings.CAS_ADMIN_PREFIX):
41                 return None
42         elif not view_func.__module__.startswith('django.contrib.admin.'):
43             return None
44
45         if request.user.is_authenticated():
46             if request.user.is_staff:
47                 return None
48             else:
49                 error = ('<h1>Forbidden</h1><p>You do not have staff '
50                          'privileges.</p>')
51                 return HttpResponseForbidden(error)
52         params = urlencode({REDIRECT_FIELD_NAME: request.get_full_path()})
53         return HttpResponseRedirect(reverse(cas_login) + '?' + params)