1#!/usr/bin/env python3
 2
 3"""Restrict access to parts of the website."""
 4
 5from django.http import HttpResponse
 6from django.shortcuts import redirect
 7from django.urls import reverse
 8
 9from chart import settings
10
11class LockdownMiddleWare:
12    def __init__(self, get_response):
13        # this function is essential for startup
14        self.get_response = get_response
15
16    def __call__(self, request):
17        # this function is essential
18        # if not request.user.is_authenticated:
19            # return HttpResponse('Resource not available')
20        return self.get_response(request)
21
22    def process_view(self, request, view_func, view_args, view_kwargs):
23        """Allow (by returning None) pages which the user is allowed to see."""
24        # request.lockdown = True
25        # Never block static requests (remember on operational systems they are all visible
26        # via front end web server anyway)
27        # Allow individual pages (i.e. homepage, login and logout) to be visible even when
28        # not authenticated
29        # Anyone logged in can see the website
30
31        # in case urls.py filtering doesn't work
32        #if settings.LOCKDOWN_RESTRICTED_ACCESS and\
33        #   request.resolver_match is not None and\
34        #   len(request.resolver_match.app_names) > 0:
35        #    app_name = request.resolver_match.app_names[0]
36        #    if 'backend' in app_name or\
37        #       'api' in app_name or\
38        #       'templates' in app_name or\
39        #       'jobviewer' in app_name or\
40        #       'schemas' in app_name or\
41        #       'browse' in app_name:
42        #        return HttpResponse()
43
44        # Show the user their page if:
45        # - lockdown is disabled in settings
46        # - It's a request for a static file (probably not needed)
47        # - It's a special page with the no_auth_needed attribute set - basically
48        #   only the login page needs this
49        # - The user is logged in as any valid user
50        if not settings.LOCKDOWN_LOGIN_REQUIRED or\
51           'static' in request.path or \
52           getattr(view_func, 'no_auth_needed', None) is True or\
53           request.user.is_authenticated:
54            # request.lockdown = True
55            return None
56
57        else:
58            # Otherwise give them the login page
59            return redirect(reverse('web:user/login'))
60            # return HttpResponse('Resource unavailable')