This repository has been archived by the owner on Apr 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware.py
62 lines (49 loc) · 2.2 KB
/
middleware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""CAS authentication middleware"""
from urllib import urlencode
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import login, logout
from django.core.urlresolvers import reverse
try:
from django.utils.deprecation import MiddlewareMixin as base_class
except ImportError:
base_class = object
from django_cas.views import login as cas_login, logout as cas_logout, _service_url
__all__ = ['CASMiddleware']
class CASMiddleware(base_class):
"""Middleware that allows CAS authentication on admin pages"""
def process_request(self, request):
"""Logs in the user if a ticket is append as parameter"""
if request.method == 'POST':
ticket = request.POST.get('ticket')
else:
ticket = request.GET.get('ticket')
if ticket:
from django.contrib import auth
user = auth.authenticate(ticket=ticket, service=_service_url(request))
if user is not None:
auth.login(request, user)
def process_view(self, request, view_func, view_args, view_kwargs):
"""Forwards unauthenticated requests to the admin page to the CAS
login URL, as well as calls to django.contrib.auth.views.login and
logout.
"""
if view_func == login:
return cas_login(request, *view_args, **view_kwargs)
elif view_func == logout:
return cas_logout(request, *view_args, **view_kwargs)
if settings.CAS_ADMIN_PREFIX:
if not request.path.startswith(settings.CAS_ADMIN_PREFIX):
return None
elif not view_func.__module__.startswith('django.contrib.admin.'):
return None
if request.user.is_authenticated():
if request.user.is_staff:
return None
else:
error = ('<h1>Forbidden</h1><p>You do not have staff '
'privileges.</p>')
return HttpResponseForbidden(error)
params = urlencode({REDIRECT_FIELD_NAME: request.get_full_path()})
return HttpResponseRedirect(reverse(cas_login) + '?' + params)