middleware.py 1.23 KB
Newer Older
Guilhem Saurel's avatar
Guilhem Saurel committed
1
2
3
from ipaddress import ip_address, ip_network

from django.conf import settings
Guilhem Saurel's avatar
Guilhem Saurel committed
4
5
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import reverse
Guilhem Saurel's avatar
flake8    
Guilhem Saurel committed
6

Guilhem Saurel's avatar
Guilhem Saurel committed
7
8
from rest_framework import permissions

Guilhem Saurel's avatar
flake8    
Guilhem Saurel committed
9
10
ALLOWED_URLS = ('admin', 'accounts', 'gh')

Guilhem Saurel's avatar
Guilhem Saurel committed
11
12

def ip_laas(request: HttpRequest) -> bool:
Guilhem Saurel's avatar
Guilhem Saurel committed
13
    """check if request comes from settings.LAAS_NETWORKS."""
Tom Pillot's avatar
Tom Pillot committed
14
    forwarded_for = ip_address(request.META.get('HTTP_X_FORWARDED_FOR').split(', ')[0])
Guilhem Saurel's avatar
Guilhem Saurel committed
15
16
17
18
19
20
21
22
    return any(forwarded_for in ip_network(net) for net in settings.LAAS_NETWORKS)


class LAASPermsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request: HttpRequest) -> HttpResponse:
Guilhem Saurel's avatar
Guilhem Saurel committed
23
24
25
26
        """Allow access to pages protected at a higher application level,
        or if the user is authenticated,
        or if the request comes from a trusted IP.
        """
Guilhem Saurel's avatar
Guilhem Saurel committed
27
        allowed = (any(request.path.startswith(f'/{url}/') for url in ALLOWED_URLS)
Guilhem Saurel's avatar
Guilhem Saurel committed
28
29
30
                   or request.user and request.user.is_authenticated
                   or request.method in permissions.SAFE_METHODS and ip_laas(request))

Guilhem Saurel's avatar
Guilhem Saurel committed
31
32
        if allowed:
            return self.get_response(request)
Guilhem Saurel's avatar
Guilhem Saurel committed
33
        return HttpResponseRedirect(reverse('login'))