import logging
from re import compile
from urllib.parse import urlencode
from django.conf import settings
from django.shortcuts import redirect
logger = logging.getLogger(__name__)
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'OAUTH_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.OAUTH_EXEMPT_URLS]
class MtdcLoginRequiredWithContextMiddleware:
"""
Middleware intended to emulate login_required decorator so we can forward the context query arg
"""
def process_request(self, request):
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
logger.debug("LOGIN_REQUIRED: User is not logged and this request triggered Oauth redirects")
if request.GET.get("context", ""):
context = request.GET["context"]
response = redirect(settings.LOGIN_URL)
logger.debug("LOGIN_REQUIRED: will redirect to "+settings.LOGIN_URL)
logger.debug("LOGIN_REQUIRED: query args will be "+str({"context": context, "next": settings.BASE_URL+path}))
response["LOCATION"] += "?"+urlencode({"context": context, "next": settings.BASE_URL+path})
return response