server/src/metaeducation/middleware.py
author ymh <ymh.work@gmail.com>
Wed, 22 Jun 2016 00:53:58 +0200
changeset 71 1b93c07510e4
parent 63 6bfac7c633a0
child 122 52eafd39ecdf
permissions -rw-r--r--
add correct object initialization to save

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(object):
    """
    Middleware intended to emulate login_required decorator so we can forward the context query arg
    """
    def process_request(self, request):
        logger.debug("REQUEST: %r ", request.user)
        logger.debug("REQUEST: Session - %r", request.session.get("OAUTH_CONTEXT_BASE_URL", "No OAuth Context in session"))
        cached_user = getattr(request, "_cached_user", "None")
        logger.debug("REQUEST: Cached user - %r", cached_user)
        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", "") and not request.session.get("OAUTH_CONTEXT_BASE_URL", ""):
                    logger.debug("LOGIN_REQUIRED: no context in session, storing context")
                    logger.debug("LOGIN_REQUIRED: context queryarg is %r", request.GET.get("context", None))
                    request.session["OAUTH_CONTEXT_BASE_URL"] = request.GET["context"]
                context = request.session.get("OAUTH_CONTEXT_BASE_URL", "")
                if context:
                    response = redirect(settings.LOGIN_URL)
                    logger.debug("LOGIN_REQUIRED: will redirect to %r", settings.LOGIN_URL)
                    logger.debug("LOGIN_REQUIRED: query args will be %r", {"context": context, "next": settings.BASE_URL+path})
                    response["LOCATION"] += "?"+urlencode({"context": context, "next": settings.BASE_URL+path})
                    return response
                else:
                    logger.debug("LOGIN REQUIRED: User not authenticated, no context in session or queryarg, aborting")