예제 #1
0
def check_sites_middleware(app_configs, **kwargs):
    if SITE_PERMISSION_MIDDLEWARE not in get_middleware_setting():
        return [Warning(SITE_PERMISSION_MIDDLEWARE +
                        " missing from settings.MIDDLEWARE - per site"
                        " permissions not applied",
                        id="mezzanine.core.W04")]
    return []
예제 #2
0
def check_sites_middleware(app_configs, **kwargs):
    if SITE_PERMISSION_MIDDLEWARE not in get_middleware_setting():
        return [
            Warning(SITE_PERMISSION_MIDDLEWARE +
                    " missing from settings.MIDDLEWARE - per site"
                    " permissions not applied",
                    id="mezzanine.core.W04")
        ]
    return []
예제 #3
0
def has_site_permission(user):
    """
    Checks if a staff user has staff-level access for the current site.
    The actual permission lookup occurs in ``SitePermissionMiddleware``
    which then marks the request with the ``has_site_permission`` flag,
    so that we only query the db once per request, so this function
    serves as the entry point for everything else to check access. We
    also fall back to an ``is_staff`` check if the middleware is not
    installed, to ease migration.
    """
    if SITE_PERMISSION_MIDDLEWARE not in get_middleware_setting():
        return user.is_staff and user.is_active
    return getattr(user, "has_site_permission", False)
예제 #4
0
def has_site_permission(user):
    """
    Checks if a staff user has staff-level access for the current site.
    The actual permission lookup occurs in ``SitePermissionMiddleware``
    which then marks the request with the ``has_site_permission`` flag,
    so that we only query the db once per request, so this function
    serves as the entry point for everything else to check access. We
    also fall back to an ``is_staff`` check if the middleware is not
    installed, to ease migration.
    """
    if SITE_PERMISSION_MIDDLEWARE not in get_middleware_setting():
        return user.is_staff and user.is_active
    return getattr(user, "has_site_permission", False)
예제 #5
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET"
             and not is_authenticated(request.user)):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         # We need to force a csrf token here, as new sessions
         # won't receieve one on their first request, with cache
         # middleware running.
         csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
         if csrf_mw_name in get_middleware_setting():
             csrf_mw = CsrfViewMiddleware()
             csrf_mw.process_view(request, lambda x: None, None, None)
             get_token(request)
         if response is None:
             request._update_cache = True
         else:
             return HttpResponse(response)
예제 #6
0
def has_site_permission(user):
    """
    Checks if a staff user has staff-level access for the current site.
    The actual permission lookup occurs in ``SitePermissionMiddleware``
    which then marks the request with the ``has_site_permission`` flag,
    so that we only query the db once per request, so this function
    serves as the entry point for everything else to check access. We
    also fall back to an ``is_staff`` check if the middleware is not
    installed, to ease migration.
    """
    mw = "mezzanine.core.middleware.SitePermissionMiddleware"
    if mw not in get_middleware_setting():
        from warnings import warn
        warn(mw + " missing from settings.MIDDLEWARE - per site"
             "permissions not applied")
        return user.is_staff and user.is_active
    return getattr(user, "has_site_permission", False)
예제 #7
0
def has_site_permission(user):
    """
    Checks if a staff user has staff-level access for the current site.
    The actual permission lookup occurs in ``SitePermissionMiddleware``
    which then marks the request with the ``has_site_permission`` flag,
    so that we only query the db once per request, so this function
    serves as the entry point for everything else to check access. We
    also fall back to an ``is_staff`` check if the middleware is not
    installed, to ease migration.
    """
    mw = "mezzanine.core.middleware.SitePermissionMiddleware"
    if mw not in get_middleware_setting():
        from warnings import warn
        warn(mw + " missing from settings.MIDDLEWARE - per site"
             "permissions not applied")
        return user.is_staff and user.is_active
    return getattr(user, "has_site_permission", False)
예제 #8
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET" and
             not is_authenticated(request.user)):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         # We need to force a csrf token here, as new sessions
         # won't receieve one on their first request, with cache
         # middleware running.
         csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
         if csrf_mw_name in get_middleware_setting():
             csrf_mw = CsrfViewMiddleware()
             csrf_mw.process_view(request, lambda x: None, None, None)
             get_token(request)
         if response is None:
             request._update_cache = True
         else:
             return HttpResponse(response)
예제 #9
0
class CSRFTestCase(TestCase):
    @classmethod
    def tearDownClass(cls):
        # Initialize nevercache again now that @override_settings is finished
        cache_installed.cache_clear()
        initialize_nevercache()

    @override_settings(
        **{
            "ROOT_URLCONF":
            CSRFTestViews,
            "CACHES": {
                'default': {
                    'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
                }
            },
            get_middleware_setting_name():
            ('mezzanine.core.middleware.UpdateCacheMiddleware', ) +
            get_middleware_setting() +
            ('mezzanine.core.middleware.FetchFromCacheMiddleware', ),
            "TESTING":
            False
        })
    def test_csrf_cookie_with_nevercache(self):
        """
        Test that the CSRF cookie is properly set when using nevercache.
        """

        # Clear the cached value for cache_installed and initialize nevercache
        cache_installed.cache_clear()
        initialize_nevercache()

        # Test uses an authenticated user as the middleware behavior differs
        self.client.login(username=self._username, password=self._password)
        response = self.client.get("/nevercache_view/")

        # CSRF token is expected to be rendered
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "csrfmiddlewaretoken")

        # The CSRF cookie should be present
        csrf_cookie = response.cookies.get(settings.CSRF_COOKIE_NAME, False)
        self.assertNotEqual(csrf_cookie, False)
예제 #10
0
def cache_installed():
    """
    Returns ``True`` if a cache backend is configured, and the
    cache middleware classes or subclasses thereof are present.
    This will be evaluated once per run, and then cached.
    """
    has_key = bool(getattr(settings, "NEVERCACHE_KEY", ""))

    def flatten(seqs):
        return (item for seq in seqs for item in seq)

    middleware_classes = map(import_string, get_middleware_setting())
    middleware_ancestors = set(flatten(map(getmro, middleware_classes)))

    mezzanine_cache_middleware_classes = {
        import_string("mezzanine.core.middleware.UpdateCacheMiddleware"),
        import_string("mezzanine.core.middleware.FetchFromCacheMiddleware"),
    }

    return (has_key and settings.CACHES and not settings.TESTING and
            mezzanine_cache_middleware_classes.issubset(middleware_ancestors))
예제 #11
0
 def installed(cls):
     """
     Used in ``mezzanine.pages.views.page`` to ensure
     ``PageMiddleware`` or a subclass has been installed. We cache
     the result on the ``PageMiddleware._installed`` to only run
     this once. Short path is to just check for the dotted path to
     ``PageMiddleware`` in ``MIDDLEWARE_CLASSES`` - if not found,
     we need to load each middleware class to match a subclass.
     """
     try:
         return cls._installed
     except AttributeError:
         name = "mezzanine.pages.middleware.PageMiddleware"
         mw_setting = get_middleware_setting()
         installed = name in mw_setting
         if not installed:
             for name in mw_setting:
                 if issubclass(import_dotted_path(name), cls):
                     installed = True
                     break
         setattr(cls, "_installed", installed)
         return installed
예제 #12
0
파일: conf.py 프로젝트: neuroloops/blog
def middlewares_or_subclasses_installed(needed_middlewares):
    """
    When passed an iterable of dotted strings, returns True if all
    of the middlewares (or their subclasses) are installed.
    """
    middleware_setting = set(get_middleware_setting())

    # Shortcut case, check by string
    if all(m in middleware_setting for m in needed_middlewares):
        return True

    def flatten(seqs):
        return (item for seq in seqs for item in seq)

    middleware_items = map(import_string, middleware_setting)
    middleware_classes = filter(lambda m: isinstance(m, six.class_types),
                                middleware_items)
    middleware_ancestors = set(flatten(map(getmro, middleware_classes)))

    needed_middlewares = set(map(import_string, needed_middlewares))

    return needed_middlewares.issubset(middleware_ancestors)
예제 #13
0
 def installed(cls):
     """
     Used in ``mezzanine.pages.views.page`` to ensure
     ``PageMiddleware`` or a subclass has been installed. We cache
     the result on the ``PageMiddleware._installed`` to only run
     this once. Short path is to just check for the dotted path to
     ``PageMiddleware`` in ``MIDDLEWARE_CLASSES`` - if not found,
     we need to load each middleware class to match a subclass.
     """
     try:
         return cls._installed
     except AttributeError:
         name = "mezzanine.pages.middleware.PageMiddleware"
         mw_setting = get_middleware_setting()
         installed = name in mw_setting
         if not installed:
             for name in mw_setting:
                 if issubclass(import_dotted_path(name), cls):
                     installed = True
                     break
         setattr(cls, "_installed", installed)
         return installed
예제 #14
0
    def process_response(self, request, response):

        # Caching is only applicable for text-based, non-streaming
        # responses. We also skip it for non-200 statuses during
        # development, so that stack traces are correctly rendered.
        is_text = response.get("content-type", "").startswith("text")
        valid_status = response.status_code == 200
        streaming = getattr(response, "streaming", False)
        if not is_text or streaming or (settings.DEBUG and not valid_status):
            return response

        # Cache the response if all the required conditions are met.
        # Response must be marked for updating by the
        # ``FetchFromCacheMiddleware`` having a cache get miss, the
        # user must not be authenticated, the HTTP status must be OK
        # and the response mustn't include an expiry age, indicating it
        # shouldn't be cached.
        marked_for_update = getattr(request, "_update_cache", False)
        anon = hasattr(request, "user") and not is_authenticated(request.user)
        timeout = get_max_age(response)
        if timeout is None:
            timeout = settings.CACHE_MIDDLEWARE_SECONDS
        if anon and valid_status and marked_for_update and timeout:
            cache_key = cache_key_prefix(request) + request.get_full_path()
            _cache_set = lambda r: cache_set(cache_key, r.content, timeout)
            if callable(getattr(response, "render", None)):
                response.add_post_render_callback(_cache_set)
            else:
                _cache_set(response)

        # Second phase rendering for non-cached template code and
        # content. Split on the delimiter the ``nevercache`` tag
        # wrapped its contents in, and render only the content
        # enclosed by it, to avoid possible template code injection.
        token = nevercache_token()
        try:
            token = token.encode('utf-8')
        except AttributeError:
            pass
        parts = response.content.split(token)
        # Restore csrf token from cookie - check the response
        # first as it may be being set for the first time.
        csrf_token = None
        try:
            csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value
        except KeyError:
            try:
                csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                pass
        if csrf_token:
            request.META["CSRF_COOKIE"] = csrf_token
        context = RequestContext(request)
        for i, part in enumerate(parts):
            if i % 2:
                part = Template(part).render(context).encode("utf-8")
            parts[i] = part
        response.content = b"".join(parts)
        response["Content-Length"] = len(response.content)
        if hasattr(request, '_messages'):
            # Required to clear out user messages.
            request._messages.update(response)
        # Response needs to be run-through the CSRF middleware again so
        # that if there was a {% csrf_token %} inside of the nevercache
        # the cookie will be correctly set for the the response
        csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
        if csrf_mw_name in get_middleware_setting():
            response.csrf_processing_done = False
            csrf_mw = CsrfViewMiddleware()
            csrf_mw.process_response(request, response)
        return response
예제 #15
0
    def process_response(self, request, response):

        # Caching is only applicable for text-based, non-streaming
        # responses. We also skip it for non-200 statuses during
        # development, so that stack traces are correctly rendered.
        is_text = response.get("content-type", "").startswith("text")
        valid_status = response.status_code == 200
        streaming = getattr(response, "streaming", False)
        if not is_text or streaming or (settings.DEBUG and not valid_status):
            return response

        # Cache the response if all the required conditions are met.
        # Response must be marked for updating by the
        # ``FetchFromCacheMiddleware`` having a cache get miss, the
        # user must not be authenticated, the HTTP status must be OK
        # and the response mustn't include an expiry age, indicating it
        # shouldn't be cached.
        marked_for_update = getattr(request, "_update_cache", False)
        anon = hasattr(request, "user") and not is_authenticated(request.user)
        timeout = get_max_age(response)
        if timeout is None:
            timeout = settings.CACHE_MIDDLEWARE_SECONDS
        if anon and valid_status and marked_for_update and timeout:
            cache_key = cache_key_prefix(request) + request.get_full_path()
            _cache_set = lambda r: cache_set(cache_key, r.content, timeout)
            if callable(getattr(response, "render", None)):
                response.add_post_render_callback(_cache_set)
            else:
                _cache_set(response)

        # Second phase rendering for non-cached template code and
        # content. Split on the delimiter the ``nevercache`` tag
        # wrapped its contents in, and render only the content
        # enclosed by it, to avoid possible template code injection.
        token = nevercache_token()
        try:
            token = token.encode('utf-8')
        except AttributeError:
            pass
        parts = response.content.split(token)
        # Restore csrf token from cookie - check the response
        # first as it may be being set for the first time.
        csrf_token = None
        try:
            csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value
        except KeyError:
            try:
                csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                pass
        if csrf_token:
            request.META["CSRF_COOKIE"] = csrf_token
        context = RequestContext(request)
        for i, part in enumerate(parts):
            if i % 2:
                part = Template(part).render(context).encode("utf-8")
            parts[i] = part
        response.content = b"".join(parts)
        response["Content-Length"] = len(response.content)
        if hasattr(request, '_messages'):
            # Required to clear out user messages.
            request._messages.update(response)
        # Response needs to be run-through the CSRF middleware again so
        # that if there was a {% csrf_token %} inside of the nevercache
        # the cookie will be correctly set for the the response
        csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
        if csrf_mw_name in get_middleware_setting():
            response.csrf_processing_done = False
            csrf_mw = CsrfViewMiddleware()
            csrf_mw.process_response(request, response)
        return response