Skip to content

Commit

Permalink
refactor: check for redirect url resolvable before redirecting
Browse files Browse the repository at this point in the history
  • Loading branch information
theShinigami committed Dec 6, 2024
1 parent 20eca71 commit 96df581
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
30 changes: 20 additions & 10 deletions djangocms_versioning/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -1031,26 +1031,20 @@ def publish_view(self, request, object_id):
)

requested_redirect = request.GET.get("next", None)

if conf.ON_PUBLISH_REDIRECT in ("preview", "published"):
redirect_url=get_preview_url(version.content)

if requested_redirect:
try:
resolve(requested_redirect)
except Resolver404:
requested_redirect = version_list_url(version.content)

else:
redirect_url=version_list_url(version.content)

if not version.can_be_published():
self.message_user(request, _("Version cannot be published"), messages.ERROR)
return redirect(requested_redirect or redirect_url)
return self._internal_redirect(requested_redirect, redirect_url)
try:
version.check_publish(request.user)
except ConditionFailed as e:
self.message_user(request, force_str(e), messages.ERROR)
return redirect(requested_redirect or redirect_url)
return self._internal_redirect(requested_redirect, redirect_url)

# Publish the version
version.publish(request.user)
Expand All @@ -1063,7 +1057,23 @@ def publish_view(self, request, object_id):
if hasattr(version.content, "get_absolute_url"):
redirect_url = version.content.get_absolute_url() or redirect_url

return redirect(requested_redirect or redirect_url)
return self._internal_redirect(requested_redirect, redirect_url)


def _internal_redirect(self, url, fallback):
"""Helper function to check if the give URL is resolvable
If resolvable, return the URL; otherwise, returns the fallback URL.
"""
if not url:
return redirect(fallback)

try:
resolve(url)
except Resolver404:
return redirect(fallback)

return redirect(url)


def unpublish_view(self, request, object_id):
"""Unpublishes the specified version and redirects back to the
Expand Down
2 changes: 1 addition & 1 deletion tests/test_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -1418,7 +1418,7 @@ def test_publish_resolvable_redirect_url(self):
with self.login_user_context(user):
response = self.client.post(not_resolvable_url)

self.assertEqual(response.url, version_list_url(poll_version.content))
self.assertEqual(response.url, helpers.get_preview_url(poll_version.content))

conf.ON_PUBLISH_REDIRECT = original_setting

Expand Down

0 comments on commit 96df581

Please sign in to comment.