Unicode errors in gallery, colors, added south, <out-of-flow> removal.
[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 class CASMiddleware(object):
16     """Middleware that allows CAS authentication on admin pages"""
17
18     def process_request(self, request):
19         """Checks that the authentication middleware is installed"""
20
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
26
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
30         logout.
31         """
32
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)
37
38         if settings.CAS_ADMIN_PREFIX:
39             if not request.path.startswith(settings.CAS_ADMIN_PREFIX):
40                 return None
41         elif not view_func.__module__.startswith('django.contrib.admin.'):
42             return None
43
44         if request.user.is_authenticated():
45             if request.user.is_staff:
46                 return None
47             else:
48                 error = ('<h1>Forbidden</h1><p>You do not have staff '
49                          'privileges.</p>')
50                 return HttpResponseForbidden(error)
51         params = urlencode({REDIRECT_FIELD_NAME: request.get_full_path()})
52         return HttpResponseRedirect(reverse(cas_login) + '?' + params)