harbor run -t openthoughts/tasktrove-exp-flat25-stackoverflow-v2-5k-stackoverflow-0734harbor download openthoughts/tasktrove-exp-flat25-stackoverflow-v2-5k-stackoverflow-0734Title: Implement Django AuthenticationMiddleware to handle TokenExpiredError and redirect based on request path
Body: I’m building a Django project that uses a custom authentication proxy and tests patch this proxy to simulate expired tokens. I need to implement a middleware AuthenticationMiddleware (in sso/middleware.py) with a parameterless constructor and a process_request(self, request) method that:
Specific test requirements to satisfy:
Acceptance criteria (tests that should pass after implementation):
Notes:
Code skeleton (for reference; you’ll implement the full logic in sso/middleware.py):
# sso/middleware.py
from django.conf import settings
from django.http import HttpResponseRedirect
from django.urls import reverse, resolve
from oauthlib.oauth2.rfc6749.errors import TokenExpiredError
# auth proxy must be importable as sso.middleware.auth for tests to patch
import django.contrib.auth as auth
class AuthenticationMiddleware:
def __init__(self):
pass
def process_request(self, request):
try:
user = auth.authenticate(request)
except TokenExpiredError:
path = request.path
# Implement redirect logic as described:
# - /django-admin/ -> reverse('admin:index')
# - /admin/ -> settings.LOGIN_URL
# - else -> try app namespace and reverse('{namespace}:login'), fallback to settings.LOGIN_URL
# Return HttpResponseRedirect(login_url)
# Do not catch other exceptions
else:
if user is not None:
request.user = user
return None
# If no user, continue (no redirect unless TokenExpiredError is raised)
return None
What I’m hoping to get: