server/src/metaeducation/middleware.py
author durandn
Mon, 14 Mar 2016 14:17:29 +0100
changeset 32 eb9e83610c99
parent 27 c3c6f2f85680
child 35 e82a0ac6cc2c
permissions -rw-r--r--
added logging and logs config

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