Make the middleware more extensible
I have a similar issue as what was raised in https://github.com/Dunedan/django-lockdown/issues/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:
https://github.com/Dunedan/django-lockdown/blob/be8224ecbca2a7f39f9d0d0c84fe6921fb1fed83/lockdown/middleware.py#L92-L94
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?
@browniebroke: Sorry for the late response. How did you work around the limitation in the meantime?
Extensibility wasn't a big concern so far for django-lockdown, but if there are use cases and it doesn't add too much additionally complexity, I'd be open for adding it.
My use case was to bypass lockdown on an API client like Postman/Insomnia where the ability to submit a form is sometimes limited. I was thinking of using that to disable lockdown api.example.com.
Right now, I workaround it by opening the page on a real browser, submit the form and copy/paste the session ID from the browser to Postman. Adds a bit of friction but it hasn't bothered me enough to do a more proper fix.