Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Everything BUT Staticfile Requests are routing through Whitenoise Middleware #266

Closed
omarsumadi opened this issue Nov 11, 2020 · 1 comment

Comments

@omarsumadi
Copy link

omarsumadi commented Nov 11, 2020

Hello, and apologies in advanced for being a Django noob,

I think that perhaps this might be a noob question, but I am using Whitenoise with the django-cookie-cutter project setup with Docker to serve only my static files. One caveat though: I am using ASGI, but as seen in issue #251 it seems as if Whitenoise effectively simulates synchronous loading perhaps ruling out ASGI as the source of my problems.

I'm trying to implement a system in which only authenticated users can access certain static files, as detailed here, but cut-down to show a demonstration. In addition, I am not worrying about performance as this is just for a very specific demo purpose that unfortunately I am having a lot more difficulty than I expected:

Here's the middleware I'm using:

from whitenoise.middleware import WhiteNoiseMiddleware
import datetime
# this is a sample code, you can change for your use case
class ProtectedStaticFileMiddleware(WhiteNoiseMiddleware):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def __call__(self, request):
        response = super().__call__(request)
        print("Request: ", request)
        print("Response ", response)
       # This is where I would check if the response is from a authorized user
        response = self.process_response(request, response)
        return response

    def process_response(self, request, response):
        print("Response, Completed: ", response)
        # Resetting cache as you said in #124 
        response['Cache-Control'] = datetime.datetime.now()
        response['Expires'] = datetime.datetime.now()
        return response

I was expecting to see for every static file a printed print(response) and print(request) output, but here's what I receive:
image

The only request the comes through the middleware is the GET request to "/", or 127.0.0.1:8000 (the main path), which means that I can't control who is authorized and who isn't. However - as you can see - my static files are being handled correctly! However, I can't get a hold of any of the static file request using even #124 which you said was a good idea to be able to authorize them.

Here are the relevant settings:

  • Running this only 127.0.0.1 using uvicorn, collect static has been run with CompressedManifestStaticFilesStorage.
whitenoise==5.2.0  # https://github.com/evansd/whitenoise
django==3.0.11  # https://www.djangoproject.com/
DEBUG = False
ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
APPS_DIR = ROOT_DIR / "edsproject"
STATIC_ROOT = str(ROOT_DIR / "staticfiles")
STATIC_URL = "/static/"
STATICFILES_DIRS = [str(APPS_DIR / "static"), str(ROOT_DIR / "ui" /"dist")]
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.common.BrokenLinkEmailsMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    # Must go down here to pick up request object
    "users.middleware.ProtectedStaticFileMiddleware",
]
INSTALLED_APPS = ["whitenoise.runserver_nostatic"] + INSTALLED_APPS
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"```
@omarsumadi
Copy link
Author

omarsumadi commented Nov 11, 2020

Had the wrong order of Middleware - custom middleware should be before the whitenoise middleware to override the handling of requests otherwise whitenoise will complete them and my custom middleware won't run.

I'll keep this open incase comments from anyone for a short period of time, but #124 was incredibly helpful for running before authentication middleware. Also works on ASGI.

Also forgot to remove whitenoise middleware, thus having two middlewares by accident after setting my custom middleware before whitenoise. For future reference to myself, the custom middleware is just a customized version of whitenoise, therefore, we don't include it twice.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant