Commit a1e22e2a authored by Guilhem Saurel's avatar Guilhem Saurel
Browse files

fix async middleware

parent 1d538c8f
Pipeline #15350 failed with stage
in 27 seconds
......@@ -4,6 +4,7 @@ from ipaddress import ip_address, ip_network
from django.conf import settings
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import reverse
from django.utils.decorators import sync_and_async_middleware
from rest_framework import permissions
......@@ -16,25 +17,30 @@ def ip_laas(request: HttpRequest) -> bool:
return any(forwarded_for in ip_network(net) for net in settings.LAAS_NETWORKS)
class LAASPermsMiddleware:
sync_capable = True
async_capable = True
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request: HttpRequest) -> HttpResponse:
"""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.
"""
allowed = (any(request.path.startswith(f'/{url}/') for url in ALLOWED_URLS)
or request.user and request.user.is_authenticated
or request.method in permissions.SAFE_METHODS and ip_laas(request))
if allowed:
if asyncio.iscoroutinefunction(self.get_response):
return await self.get_response(request)
else:
return self.get_response(request)
return HttpResponseRedirect(reverse('login'))
def allowed(request: HttpRequest) -> bool:
"""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.
"""
return (any(request.path.startswith(f'/{url}/') for url in ALLOWED_URLS)
or request.user and request.user.is_authenticated
or request.method in permissions.SAFE_METHODS and ip_laas(request))
@sync_and_async_middleware
def laas_perms_middleware(get_response):
# One-time configuration and initialization goes here.
if asyncio.iscoroutinefunction(get_response):
async def middleware(request):
if allowed(request):
return await get_response(request)
return HttpResponseRedirect(reverse('login'))
else:
def middleware(request):
if allowed(request):
return get_response(request)
return HttpResponseRedirect(reverse('login'))
return middleware
......@@ -58,7 +58,7 @@ MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
f'{PROJECT}.middleware.LAASPermsMiddleware',
f'{PROJECT}.middleware.laas_perms_middleware',
]
ROOT_URLCONF = f'{PROJECT}.urls'
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment