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

Make the middleware more extensible #22

Open
browniebroke opened this issue Oct 21, 2024 · 0 comments
Open

Make the middleware more extensible #22

browniebroke opened this issue Oct 21, 2024 · 0 comments

Comments

@browniebroke
Copy link

browniebroke commented Oct 21, 2024

I have a similar issue as what was raised in #5 and was thinking of adding a LOCKDOWN_HOST_EXCEPTIONS. As the idea was previously rejected, I wanted to try to subclass the LockdownMiddleware and add my own logic before main one, but found that this was a bit more difficult that I thought.

Basically, I was thinking of adding my logic after the initial checks, and before further checks are done:

# Don't lock down if django-lockdown is disabled altogether.
if getattr(settings, 'LOCKDOWN_ENABLED', True) is False:
return None

I think that could be achieved by calling a method on the middleware class which by default wouldn't do anything, but which would enable user to hook into their custom logic by returning something specific.

Changed middleware:

class LockdownMiddleware(object):
    ...
    def process_request(self, request):
        ...
        # Don't lock down if django-lockdown is disabled altogether.
        if getattr(settings, 'LOCKDOWN_ENABLED', True) is False:
            return None

        # NEW: Call hook
        if self.is_request_excluded(request):
            return None

        ...

    def is_request_excluded(self, request):  # New method
        """Hook for users to implement a custom logic to exclude the request."""
        return False

Example implementation in user-land:

from lockdown.middleware import LockdownMiddleware as BaseLockdownMiddleware


class LockdownMiddleware(BaseLockdownMiddleware):
    def is_request_excluded(self, request, response):
        return request.get_host() in ["api.mysite.com"]

What do you think?

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