server/src/metaeducation/middleware.py
changeset 1 5f50937893ac
child 4 8bc8b208441d
equal deleted inserted replaced
0:71a42c20fc86 1:5f50937893ac
       
     1 from django.shortcuts import redirect
       
     2 from django.conf import settings
       
     3 from urllib.parse import urlencode
       
     4 from re import compile
       
     5 
       
     6 EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
       
     7 if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
       
     8     EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
       
     9 
       
    10 class MtdcLoginRequiredWithContextMiddleware:
       
    11     """
       
    12     Middleware intended to emulate login_required decorator so we can forward the context query arg
       
    13     """
       
    14     def process_request(self, request):
       
    15         if not request.user.is_authenticated():
       
    16             path = request.path_info.lstrip('/')
       
    17             if not any(m.match(path) for m in EXEMPT_URLS):
       
    18                 if request.GET.get("context", ""):
       
    19                     context = request.GET["context"]
       
    20                     response = redirect(settings.LOGIN_URL)
       
    21                     response["LOCATION"] += "?"+urlencode({"context": context})
       
    22                     print(response["LOCATION"])
       
    23                     return response