Skip to content

Commit

Permalink
Merge pull request #4633 from opensafely-core/Jongmassey/Pages-with-R…
Browse files Browse the repository at this point in the history
…edirect-Error

Fix circular redirects caused by wildcards in paths
  • Loading branch information
Jongmassey authored Oct 4, 2024
2 parents 4814a7a + 5fe99ae commit f783726
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
9 changes: 5 additions & 4 deletions redirects/middleware.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.db.models import CharField, F, Value
from django.db.models.functions import Length
from django.shortcuts import redirect

Expand Down Expand Up @@ -27,11 +28,11 @@ def __call__(self, request):

# look for a direct or prefix match on the current URL
redirection = (
Redirect.objects.extra(
where=["%s LIKE concat(old_url, '%%')"],
params=[request.path],
Redirect.objects.annotate(
url_length=Length("old_url"),
request_url=Value(request.path, output_field=CharField()),
)
.annotate(url_length=Length("old_url"))
.filter(request_url__startswith=F("old_url"))
.order_by("-url_length")
.first()
)
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/redirects/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,16 @@ def test_redirectsmiddleware_unknown_url(rf):
response = RedirectsMiddleware(get_response)(request)

assert response == "no match"


def test_redirect_with_wildcard_in_path(rf):
w1 = WorkspaceFactory()
w2 = WorkspaceFactory()
RedirectFactory(old_url="/abc/123/test_workspace/", workspace=w1)
RedirectFactory(old_url="/abc/123/test-workspace/", workspace=w2)

request = rf.get("/abc/123/test-workspace/")

response = RedirectsMiddleware(get_response)(request)

assert response.url == w2.get_absolute_url()

0 comments on commit f783726

Please sign in to comment.