diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index c30908d0..9f05d488 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -27,16 +27,16 @@ jobs: uses: actions/checkout@v4 - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} queries: +security-and-quality - name: Autobuild - uses: github/codeql-action/autobuild@v2 + uses: github/codeql-action/autobuild@v3 if: ${{ matrix.language == 'javascript' || matrix.language == 'python' }} - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 with: category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index c393f081..2fceee19 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -19,7 +19,7 @@ jobs: python-version: '3.11' cache: 'pip' - name: Cache dependencies - uses: actions/cache@v4.0.1 + uses: actions/cache@v4.0.2 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('docs/requirements.txt') }} @@ -44,7 +44,7 @@ jobs: python-version: '3.11' cache: 'pip' - name: Cache dependencies - uses: actions/cache@v4.0.1 + uses: actions/cache@v4.0.2 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('docs/requirements.txt') }} diff --git a/CHANGELOG.rst b/CHANGELOG.rst index f7ab8665..f21c5790 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -2,6 +2,26 @@ Changelog ========= +2.0.1 (2024-03-29) +================== + +* feat: Add content object level publish permissions by @fsbraun in https://github.com/django-cms/djangocms-versioning/pull/390 +* fix: Create missing __init__.py in management folder by @fsbraun in https://github.com/django-cms/djangocms-versioning/pull/366 +* fix #363: Better UX in versioning listview by @jrief in https://github.com/django-cms/djangocms-versioning/pull/364 +* fix: Several fixes for the versioning forms: #382, #383, #384 by @fsbraun in https://github.com/django-cms/djangocms-versioning/pull/386 +* fix: For Django CMS 4.1.1 and later do not automatically register versioned CMS Menu by @fsbraun in https://github.com/django-cms/djangocms-versioning/pull/388 +* fix: Post requests from the side frame were sent to wrong URL by @fsbraun in https://github.com/django-cms/djangocms-versioning/pull/396 +* fix: Consistent use of action buttons by @fsbraun in https://github.com/django-cms/djangocms-versioning/pull/392 +* fix: Avoid duplication of placeholder checks for locked versions by @fsbraun in https://github.com/django-cms/djangocms-versioning/pull/393 +* ci: Add testing against django main by @marksweb in https://github.com/django-cms/djangocms-versioning/pull/353 +* ci: Improve efficiency of ruff workflow by @marksweb in https://github.com/django-cms/djangocms-versioning/pull/378 +* Chore: update ruff and pre-commit hook by @raffaellasuardini in https://github.com/django-cms/djangocms-versioning/pull/381 +* build(deps): bump actions/cache from 4.0.1 to 4.0.2 by @dependabot in https://github.com/django-cms/djangocms-versioning/pull/397 + +New Contributors + +* @raffaellasuardini made their first contribution in https://github.com/django-cms/djangocms-versioning/pull/381 +* @jrief made their first contribution in https://github.com/django-cms/djangocms-versioning/pull/364 2.0.0 (2023-12-29) ================== diff --git a/djangocms_versioning/__init__.py b/djangocms_versioning/__init__.py index 8c0d5d5b..159d48b8 100644 --- a/djangocms_versioning/__init__.py +++ b/djangocms_versioning/__init__.py @@ -1 +1 @@ -__version__ = "2.0.0" +__version__ = "2.0.1" diff --git a/djangocms_versioning/admin.py b/djangocms_versioning/admin.py index 6b2a7e71..1d0ce04d 100644 --- a/djangocms_versioning/admin.py +++ b/djangocms_versioning/admin.py @@ -608,6 +608,9 @@ class VersionAdmin(ChangeListActionsMixin, admin.ModelAdmin, metaclass=MediaDefi # def get_queryset(self, request): # return super().get_queryset(request).prefetch_related('content') + class Media: + js = ["djangocms_versioning/js/versioning.js"] + def get_changelist(self, request, **kwargs): return VersionChangeList @@ -682,13 +685,13 @@ def _get_archive_link(self, obj, request, disabled=False): icon="archive", title=_("Archive"), name="archive", - disabled=not obj.can_be_archived(), + disabled=not obj.check_archive.as_bool(request.user), ) def _get_publish_link(self, obj, request): """Helper function to get the html link to the publish action """ - if not obj.check_publish.as_bool(request.user): + if not obj.can_be_published(): # Don't display the link if it can't be published return "" publish_url = reverse( @@ -701,14 +704,14 @@ def _get_publish_link(self, obj, request): title=_("Publish"), name="publish", action="post", - disabled=not obj.can_be_published(), + disabled=not obj.check_publish.as_bool(request.user), keepsideframe=False, ) def _get_unpublish_link(self, obj, request, disabled=False): """Helper function to get the html link to the unpublish action """ - if not obj.check_unpublish.as_bool(request.user): + if not obj.can_be_unpublished(): # Don't display the link if it can't be unpublished return "" unpublish_url = reverse( @@ -720,15 +723,12 @@ def _get_unpublish_link(self, obj, request, disabled=False): icon="unpublish", title=_("Unpublish"), name="unpublish", - disabled=not obj.can_be_unpublished(), + disabled=not obj.check_unpublish.as_bool(request.user), ) def _get_edit_link(self, obj, request, disabled=False): """Helper function to get the html link to the edit action """ - if not obj.check_edit_redirect.as_bool(request.user): - return "" - # Only show if no draft exists if obj.state == PUBLISHED: pks_for_grouper = obj.versionable.for_content_grouping_values( @@ -758,14 +758,14 @@ def _get_edit_link(self, obj, request, disabled=False): title=_("Edit") if icon == "pencil" else _("New Draft"), name="edit", action="post", - disabled=disabled, + disabled=not obj.check_edit_redirect.as_bool(request.user) or disabled, keepsideframe=keepsideframe, ) def _get_revert_link(self, obj, request, disabled=False): """Helper function to get the html link to the revert action """ - if not obj.check_revert.as_bool(request.user): + if obj.state in (PUBLISHED, DRAFT): # Don't display the link if it's a draft or published return "" @@ -778,13 +778,13 @@ def _get_revert_link(self, obj, request, disabled=False): icon="undo", title=_("Revert"), name="revert", - disabled=disabled, + disabled=not obj.check_revert.as_bool(request.user) or disabled, ) def _get_discard_link(self, obj, request, disabled=False): """Helper function to get the html link to the discard action """ - if not obj.check_discard.as_bool(request.user): + if obj.state != DRAFT: # Don't display the link if it's not a draft return "" @@ -797,7 +797,7 @@ def _get_discard_link(self, obj, request, disabled=False): icon="bin", title=_("Discard"), name="discard", - disabled=disabled, + disabled=not obj.check_discard.as_bool(request.user) or disabled, ) def _get_unlock_link(self, obj, request): @@ -808,12 +808,6 @@ def _get_unlock_link(self, obj, request): if not conf.LOCK_VERSIONS or obj.state != DRAFT or not version_is_locked(obj): return "" - disabled = True - # Check whether the lock can be removed - # Check that the user has unlock permission - if request.user.has_perm("djangocms_versioning.delete_versionlock"): - disabled = False - unlock_url = reverse(f"admin:{obj._meta.app_label}_{self.model._meta.model_name}_unlock", args=(obj.pk,)) return self.admin_action_button( unlock_url, @@ -821,7 +815,7 @@ def _get_unlock_link(self, obj, request): title=_("Unlock"), name="unlock", action="post", - disabled=disabled, + disabled=not obj.check_unlock.as_bool(request.user), ) def get_actions_list(self): @@ -978,7 +972,6 @@ def publish_view(self, request, object_id): # Redirect to published? if conf.ON_PUBLISH_REDIRECT == "published": - redirect_url = None if hasattr(version.content, "get_absolute_url"): redirect_url = version.content.get_absolute_url() or redirect_url @@ -1323,10 +1316,7 @@ def changelist_view(self, request, extra_context=None): # Check if custom breadcrumb template defined, otherwise # fallback on default breadcrumb_templates = [ - "admin/djangocms_versioning/{app_label}/{model_name}/versioning_breadcrumbs.html".format( - app_label=breadcrumb_opts.app_label, - model_name=breadcrumb_opts.model_name, - ), + f"admin/djangocms_versioning/{breadcrumb_opts.app_label}/{breadcrumb_opts.model_name}/versioning_breadcrumbs.html", "admin/djangocms_versioning/versioning_breadcrumbs.html", ] extra_context["breadcrumb_template"] = select_template(breadcrumb_templates) diff --git a/djangocms_versioning/apps.py b/djangocms_versioning/apps.py index c1ebdcfd..a5019d4c 100644 --- a/djangocms_versioning/apps.py +++ b/djangocms_versioning/apps.py @@ -12,15 +12,18 @@ def ready(self): from cms.models import contentmodels, fields from cms.signals import post_obj_operation, post_placeholder_operation + from .conf import LOCK_VERSIONS from .handlers import ( update_modified_date, update_modified_date_for_pagecontent, update_modified_date_for_placeholder_source, ) - from .helpers import is_content_editable + from .helpers import is_content_editable, placeholder_content_is_unlocked_for_user # Add check to PlaceholderRelationField fields.PlaceholderRelationField.default_checks += [is_content_editable] + if LOCK_VERSIONS: + fields.PlaceholderRelationField.default_checks += [placeholder_content_is_unlocked_for_user] # Remove uniqueness constraint from PageContent model to allow for different versions pagecontent_unique_together = tuple( diff --git a/djangocms_versioning/cms_config.py b/djangocms_versioning/cms_config.py index 92c66fe4..e2894084 100644 --- a/djangocms_versioning/cms_config.py +++ b/djangocms_versioning/cms_config.py @@ -25,7 +25,6 @@ from . import indicators, versionables from .admin import VersioningAdminMixin -from .conf import LOCK_VERSIONS from .constants import INDICATOR_DESCRIPTIONS from .datastructures import BaseVersionableItem, VersionableItem from .exceptions import ConditionFailed @@ -33,7 +32,6 @@ get_latest_admin_viewable_content, inject_generic_relation_to_version, is_editable, - placeholder_content_is_unlocked_for_user, register_versionadmin_proxy, replace_admin_for_models, replace_manager, @@ -160,12 +158,6 @@ def handle_admin_field_modifiers(self, cms_config): for key in modifier.keys(): self.add_to_field_extension[key] = modifier[key] - def handle_locking(self): - if LOCK_VERSIONS: - from cms.models import fields - - fields.PlaceholderRelationField.default_checks += [placeholder_content_is_unlocked_for_user] - def configure_app(self, cms_config): if hasattr(cms_config, "extended_admin_field_modifiers"): self.handle_admin_field_modifiers(cms_config) @@ -188,7 +180,6 @@ def configure_app(self, cms_config): self.handle_version_admin(cms_config) self.handle_content_model_generic_relation(cms_config) self.handle_content_model_manager(cms_config) - self.handle_locking() def copy_page_content(original_content): diff --git a/djangocms_versioning/cms_toolbars.py b/djangocms_versioning/cms_toolbars.py index 94337cff..80173f9a 100644 --- a/djangocms_versioning/cms_toolbars.py +++ b/djangocms_versioning/cms_toolbars.py @@ -127,8 +127,8 @@ def _add_unlock_button(self): if LOCK_VERSIONS and self._is_versioned(): item = ButtonList(side=self.toolbar.RIGHT) proxy_model = self._get_proxy_model() - version = Version.objects.get_for_content(self.toolbar.obj) - if version.check_unlock.as_bool(self.request.user): + version = Version.objects.filter_by_content_grouping_values(self.toolbar.obj).filter(state=DRAFT).first() + if version and version.check_unlock.as_bool(self.request.user): unlock_url = reverse( f"admin:{proxy_model._meta.app_label}_{proxy_model.__name__.lower()}_unlock", args=(version.pk,), diff --git a/djangocms_versioning/conditions.py b/djangocms_versioning/conditions.py index c73a8c14..fd76a007 100644 --- a/djangocms_versioning/conditions.py +++ b/djangocms_versioning/conditions.py @@ -76,3 +76,22 @@ def inner(version, user): else: raise ConditionFailed(message) return inner + +def user_can_unlock(message: str) -> callable: + def inner(version, user): + if not user.has_perm("djangocms_versioning.delete_versionlock"): + raise ConditionFailed(message) + return inner + +def user_can_publish(message: str) -> callable: + def inner(version, user): + if not version.has_publish_permission(user): + raise ConditionFailed(message) + return inner + + +def user_can_change(message: str) -> callable: + def inner(version, user): + if not version.has_change_permission(user): + raise ConditionFailed(message) + return inner diff --git a/djangocms_versioning/conf.py b/djangocms_versioning/conf.py index 40030005..1188780e 100644 --- a/djangocms_versioning/conf.py +++ b/djangocms_versioning/conf.py @@ -1,7 +1,8 @@ +from cms import __version__ as CMS_VERSION from django.conf import settings ENABLE_MENU_REGISTRATION = getattr( - settings, "DJANGOCMS_VERSIONING_ENABLE_MENU_REGISTRATION", True + settings, "DJANGOCMS_VERSIONING_ENABLE_MENU_REGISTRATION", CMS_VERSION <= "4.1.0" ) USERNAME_FIELD = getattr( @@ -31,4 +32,4 @@ ON_PUBLISH_REDIRECT = getattr( settings, "DJANGOCMS_VERISONING_ON_PUBLISH_REDIRECT", "published" ) -# Allowed values: "versions", "published", "preview" +#: Allowed values: "versions", "published", "preview" diff --git a/djangocms_versioning/models.py b/djangocms_versioning/models.py index 0a5ef6a2..8bfa1009 100644 --- a/djangocms_versioning/models.py +++ b/djangocms_versioning/models.py @@ -16,6 +16,9 @@ draft_is_not_locked, in_state, is_not_locked, + user_can_change, + user_can_publish, + user_can_unlock, ) from .conf import ALLOW_DELETING_VERSIONS, LOCK_VERSIONS from .operations import send_post_version_operation, send_pre_version_operation @@ -29,7 +32,7 @@ not_draft_error = _("Version is not a draft") lock_error_message = _("Action Denied. The latest version is locked by {user}") lock_draft_error_message = _("Action Denied. The draft version is locked by {user}") - +permission_error_message = _("You do not have permission to perform this action") def allow_deleting_versions(collector, field, sub_objs, using): if ALLOW_DELETING_VERSIONS: @@ -278,7 +281,7 @@ def copy(self, created_by): Allows customization of how the content object will be copied when specified in cms_config.py - This method needs to be ran in a transaction due to the fact that if + This method needs to be run in a transaction due to the fact that if models are partially created in the copy method a version is not attached. It needs to be that if anything goes wrong we should roll back the entire task. We shouldn't leave this to package developers to know to add this feature @@ -296,6 +299,7 @@ def copy(self, created_by): check_archive = Conditions( [ + user_can_change(permission_error_message), in_state([constants.DRAFT], _("Version is not in draft state")), is_not_locked(lock_error_message), ] @@ -345,7 +349,10 @@ def _set_archive(self, user): pass check_publish = Conditions( - [in_state([constants.DRAFT], _("Version is not in draft state"))] + [ + user_can_publish(permission_error_message), + in_state([constants.DRAFT], _("Version is not in draft state")), + ] ) def can_be_published(self): @@ -418,6 +425,7 @@ def is_visible(self): ) check_unpublish = Conditions([ + user_can_publish(permission_error_message), in_state([constants.PUBLISHED], _("Version is not in published state")), draft_is_not_locked(lock_draft_error_message), ]) @@ -468,14 +476,60 @@ def _set_unpublish(self, user): possible to be left with inconsistent data)""" pass + def has_publish_permission(self, user) -> bool: + """ + Check if the given user has permission to publish. + + Args: + user (User): The user to check for permission. + + Returns: + bool: True if the user has publish permission, False otherwise. + """ + return self._has_permission("publish", user) + + def has_change_permission(self, user) -> bool: + """ + Check whether the given user has permission to change the object. + + Parameters: + user (User): The user for which permission needs to be checked. + + Returns: + bool: True if the user has permission to change the object, False otherwise. + """ + return self._has_permission("change", user) + + def _has_permission(self, perm: str, user) -> bool: + """ + Check if the user has the specified permission for the content by + checking the content's has_publish_permission, has_placeholder_change_permission, + or has_change_permission methods. + + Falls back to Djangos change permission for the content object. + """ + if perm == "publish" and hasattr(self.content, "has_publish_permission"): + # First try explicit publish permission + return self.content.has_publish_permission(user) + if hasattr(self.content, "has_change_permission"): + # First fallback: change permissions + return self.content.has_change_permission(user) + if hasattr(self.content, "has_placeholder_change_permission"): + # Second fallback: placeholder change permissions - works for PageContent + return self.content.has_placeholder_change_permission(user) + # final fallback: Django perms + return user.has_perm(f"{self.content_type.app_label}.change_{self.content_type.model}") + check_modify = Conditions( [ in_state([constants.DRAFT], not_draft_error), draft_is_not_locked(lock_draft_error_message), + user_can_unlock(permission_error_message), ] ) check_revert = Conditions( [ + user_can_change(permission_error_message), in_state( [constants.ARCHIVED, constants.UNPUBLISHED], _("Version is not in archived or unpublished state"), @@ -508,6 +562,7 @@ def _set_unpublish(self, user): [ in_state([constants.DRAFT, constants.PUBLISHED], not_draft_error), draft_is_locked(_("Draft version is not locked")) + ] ) diff --git a/djangocms_versioning/static/djangocms_versioning/css/versioning.css b/djangocms_versioning/static/djangocms_versioning/css/versioning.css index f66b94a0..bc19b68b 100644 --- a/djangocms_versioning/static/djangocms_versioning/css/versioning.css +++ b/djangocms_versioning/static/djangocms_versioning/css/versioning.css @@ -207,6 +207,3 @@ ins.cms-diff img { .cms-select::-ms-expand { opacity: 0; } -input.button.revert-button { - margin: 5px; -} diff --git a/djangocms_versioning/static/djangocms_versioning/js/admin/versioning-actions.js b/djangocms_versioning/static/djangocms_versioning/js/admin/versioning-actions.js new file mode 100644 index 00000000..632032fa --- /dev/null +++ b/djangocms_versioning/static/djangocms_versioning/js/admin/versioning-actions.js @@ -0,0 +1,22 @@ +(function () { + "use strict"; + + function closeSideFrame() { + try { + window.top.CMS.API.Sideframe.close(); + } catch (err) {} + } + + document.addEventListener('DOMContentLoaded', function () { + document.querySelectorAll('form.js-close-sideframe').forEach(el => { + el.addEventListener("submit", (ev) => { + ev.preventDefault(); + ev.target.action = ev.target.action; // save action url + closeSideFrame(); + const form = window.top.document.body.appendChild(ev.target); // move to top window + form.style.display = 'none'; + form.submit(); // submit form + }); + }); + }); +})(); diff --git a/djangocms_versioning/static/djangocms_versioning/js/versioning.js b/djangocms_versioning/static/djangocms_versioning/js/versioning.js new file mode 100644 index 00000000..0704f537 --- /dev/null +++ b/djangocms_versioning/static/djangocms_versioning/js/versioning.js @@ -0,0 +1,37 @@ +(function() { + var firstChecked, lastChecked; + + function handleVersionSelection(event) { + if (firstChecked instanceof HTMLInputElement && firstChecked.checked) { + firstChecked.checked = false; + firstChecked.closest('tr').classList.remove('selected'); + firstChecked = lastChecked; + } + if (event.target instanceof HTMLInputElement) { + if (event.target.checked) { + firstChecked = lastChecked; + lastChecked = event.target; + } else if (firstChecked === event.target) { + firstChecked = null; + } else { + lastChecked = null; + } + } + } + + document.addEventListener('DOMContentLoaded', function(){ + var selectedVersions = document.querySelectorAll('#result_list input[type="checkbox"].action-select'); + var selectElement = document.querySelector('#changelist-form select[name="action"]'); + if (selectElement instanceof HTMLSelectElement) { + for (var i = 0; i < selectElement.options.length; i++) { + if (selectElement.options[i].value && selectElement.options[i].value !== 'compare_versions') { + // for future safety: do not restrict on two selected versions, since there might be other actions + return; + } + } + } + selectedVersions.forEach(function(selectedVersion){ + selectedVersion.addEventListener('change', handleVersionSelection); + }); + }); + })(); diff --git a/djangocms_versioning/templates/djangocms_versioning/admin/archive_confirmation.html b/djangocms_versioning/templates/djangocms_versioning/admin/archive_confirmation.html index 40ab5cd3..4a70749c 100644 --- a/djangocms_versioning/templates/djangocms_versioning/admin/archive_confirmation.html +++ b/djangocms_versioning/templates/djangocms_versioning/admin/archive_confirmation.html @@ -6,6 +6,7 @@ {{ block.super }} {{ media }} + {% endblock %} {% block breadcrumbs %}{% endblock %} @@ -15,15 +16,17 @@

{% translate "Are you sure you want to archive the following version?" %}

{{ object_name }}

{% blocktrans %} Version number: {{ version_number }}{% endblocktrans %}

-
+ {% csrf_token %} - - - - +
+ + + + +
{% endblock %} diff --git a/djangocms_versioning/templates/djangocms_versioning/admin/revert_confirmation.html b/djangocms_versioning/templates/djangocms_versioning/admin/revert_confirmation.html index 3de7d687..7bbbb168 100644 --- a/djangocms_versioning/templates/djangocms_versioning/admin/revert_confirmation.html +++ b/djangocms_versioning/templates/djangocms_versioning/admin/revert_confirmation.html @@ -6,6 +6,7 @@ {{ media }} + {% endblock %} {% block breadcrumbs %}{% endblock %} @@ -22,20 +23,20 @@

{% block title %}{% translate "Revert Confirmation" %}{% endblock %}

{{ object_name }}

{% blocktrans %}Version number: {{ version_number }}{% endblocktrans %}

-
+ {% csrf_token %}
{% if draft_version %} - - {% else %} - diff --git a/djangocms_versioning/templates/djangocms_versioning/admin/unpublish_confirmation.html b/djangocms_versioning/templates/djangocms_versioning/admin/unpublish_confirmation.html index 7a87ab53..047dd547 100644 --- a/djangocms_versioning/templates/djangocms_versioning/admin/unpublish_confirmation.html +++ b/djangocms_versioning/templates/djangocms_versioning/admin/unpublish_confirmation.html @@ -5,6 +5,7 @@ {{ block.super }} {{ media }} + {% endblock %} {% block breadcrumbs %}{% endblock %} @@ -20,10 +21,10 @@

{% blocktrans %} Version number: {{ version_number }}{% endblocktrans %}

{{thing}}

{% endfor %}
- + {% csrf_token %}
- diff --git a/djangocms_versioning/test_utils/blogpost/models.py b/djangocms_versioning/test_utils/blogpost/models.py index 282d84c9..7634e5ad 100644 --- a/djangocms_versioning/test_utils/blogpost/models.py +++ b/djangocms_versioning/test_utils/blogpost/models.py @@ -14,6 +14,18 @@ class BlogContent(models.Model): language = models.TextField() text = models.TextField() + def has_publish_permission(self, user): + if user.is_superuser: + return True + # Fake a simple object-dependent permission + return user.username in self.text + + def has_change_permission(self, user): + if user.is_superuser: + return True + # Fake a simple object-dependent permission + return f"<{user.username}>" in self.text + def __str__(self): return self.text diff --git a/docs/index.rst b/docs/index.rst index b6f65499..d09c98f9 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -7,6 +7,7 @@ Welcome to "djangocms-versioning"'s documentation! basic_concepts versioning_integration + permissions version_locking .. toctree:: diff --git a/docs/permissions.rst b/docs/permissions.rst new file mode 100644 index 00000000..ab404720 --- /dev/null +++ b/docs/permissions.rst @@ -0,0 +1,94 @@ +##################################### + Permissions in djangocms-versioning +##################################### + +This documentation covers the permissions system introduced for +publishing and unpublishing content in djangocms-versioning. This system +allows for fine-grained control over who can publish and unpublish or otherwise +manage versions of content. + +*************************** + Understanding Permissions +*************************** + +Permissions are set at the content object level, allowing for detailed +access control based on the user's roles and permissions. The system +checks for specific methods within the **content object**, e.g. +``PageContent`` to determine if a user has the necessary permissions. + +- **Specific publish permission** (only for publish/unpublish action): + To check if a user has the + permission to publish content, the system looks for a method named + ``has_publish_permission`` on the content object. If this method is + present, it will be called to determine whether the user is allowed + to publish the content. + + Example: + + .. code:: python + + def has_publish_permission(self, user): + if user.is_superuser: + # Superusers typically have permission to publish + return True + # Custom logic to determine if the user can publish + return user_has_permission + +- **Change Permission** (and first fallback for ``has_publish_permission``): + If the content object has a + method named ``has_change_permission``, this method will be called to + assess if a user has the permission to change the content. This is a + general permission check that is not specific to publishing or + unpublishing actions. + + Example: + + .. code:: python + + def has_change_permission(self, user): + if user.is_superuser: + # Superusers typically have permission to publish + return True + # Custom logic to determine if the user can change the content + return user_has_permission + +- **First Fallback Placeholder Change Permission**: For content + objects that involve placeholders, such as PageContent objects, a + method named ``has_placeholder_change_permission`` is checked. This + method should determine if the user has the permission to change + placeholders within the content. + + Example: + + .. code:: python + + def has_placeholder_change_permission(self, user): + if user.is_superuser: + # Superusers typically have permission to publish + return True + # Custom logic to determine if the user can change placeholders + return user_has_permission + +- **Last resort Django permissions:** If none of the above methods are + present on the content object, the system falls back to checking if + the user has a generic Django permission to change ``Version`` + objects. This ensures that there is always a permission check in + place, even if specific methods are not implemented for the content + object. By default, the Django permissions are set on a user or group + level and include all instances of the content object. + + .. note:: + + It is highly recommended to implement the specific permission + methods on your content objects for more granular control over + user actions. + +************ + Conclusion +************ + +The permissions system introduced in djangocms-versioning for publishing +and unpublishing content provides a flexible and powerful way to manage +access to content. By defining custom permission logic within your +content objects, you can ensure that only authorized users are able to +perform these actions. diff --git a/docs/settings.rst b/docs/settings.rst index 7f468aef..7747f40a 100644 --- a/docs/settings.rst +++ b/docs/settings.rst @@ -25,10 +25,12 @@ Settings for djangocms Versioning .. py:attribute:: DJANGOCMS_VERSIONING_ENABLE_MENU_REGISTRATION - Defaults to ``True`` + Defaults to ``True`` (for django CMS <= 4.1.0) and ``False`` + (for django CMS > 4.1.0) This settings specifies if djangocms-versioning should register its own - versioned CMS menu. + versioned CMS menu. This is necessary for CMS <= 4.1.0. For CMS > 4.1.0, the + django CMS core comes with a version-ready menu. The versioned CMS menu also shows draft content in edit and preview mode. @@ -37,6 +39,9 @@ Settings for djangocms Versioning Defaults to ``False`` + .. versionadded:: 2.0 + Before version 2.0 version locking was part of a separate package. + This setting controls if draft versions are locked. If they are, only the user who created the draft can change the draft. See :ref:`Locking versions ` for more details. @@ -65,8 +70,7 @@ Settings for djangocms Versioning Defaults to ``"published"`` .. versionadded:: 2.0 - - Before version 2.0 the behavior was always ``"versions"``. + Before version 2.0 the behavior was always ``"versions"``. This setting determines what happens after publication/unpublication of a content object. Three options exist: diff --git a/docs/static/blog-new.jpg b/docs/static/blog-new.jpg new file mode 100644 index 00000000..2df4f311 Binary files /dev/null and b/docs/static/blog-new.jpg differ diff --git a/docs/static/blog-original.jpg b/docs/static/blog-original.jpg new file mode 100644 index 00000000..014a5a3d Binary files /dev/null and b/docs/static/blog-original.jpg differ diff --git a/docs/versioning_integration.rst b/docs/versioning_integration.rst index 45e513e9..21892791 100644 --- a/docs/versioning_integration.rst +++ b/docs/versioning_integration.rst @@ -17,30 +17,13 @@ Change the model structure ---------------------------- Assuming that our `blog` app has one db table: -.. graphviz:: - - digraph ERD1 { - graph [ rankdir = "LR" ]; - ranksep=2; - - "Post" [ label=" Post|id \l |site \l title \l text \l " shape = "record" ]; - - "Post":"PK_GROUPER_ID" [arrowhead = crow]; - } +.. image:: /static/blog-original.jpg + :width: 75px This would have to change to a db structure like this: -.. graphviz:: - - digraph ERD2 { - graph [ rankdir = "LR" ]; - ranksep=2; - - "Post" [ label=" Post|id \l |site \l " shape = "record" ]; - "PostContent" [ label=" PostContent|id \l |post \l |title \l text \l " shape = "record" ]; - - "Post":"PK_GROUPER_ID"->"PostContent":"FK_POST" [arrowhead = crow]; - } +.. image:: /static/blog-new.jpg + :width: 377px Or in python code, `models.py` would need to change from: diff --git a/test_settings.py b/test_settings.py index b7ba9a75..65950588 100644 --- a/test_settings.py +++ b/test_settings.py @@ -44,6 +44,7 @@ "PARLER_ENABLE_CACHING": False, "LANGUAGE_CODE": "en", "DEFAULT_AUTO_FIELD": "django.db.models.AutoField", + "DJANGOCMS_VERSIONING_ENABLE_MENU_REGISTRATION": True, "CMS_CONFIRM_VERSION4": True, } diff --git a/tests/test_admin.py b/tests/test_admin.py index dcad5eec..1f3fb489 100644 --- a/tests/test_admin.py +++ b/tests/test_admin.py @@ -452,12 +452,11 @@ def test_content_link_for_editable_object_with_no_preview_url(self): version = factories.PageVersionFactory(content__title="test5") with patch.object(helpers, "is_editable_model", return_value=True): with override(version.content.language): + url = get_object_preview_url(version.content, language=version.content.language) + label = version.content self.assertEqual( self.site._registry[Version].content_link(version), - '{label}'.format( - url=get_object_preview_url(version.content, language=version.content.language), - label=version.content - ), + f'{label}', ) @@ -516,7 +515,7 @@ def test_revert_action_link_enable_state(self): The revert action is active """ version = factories.PollVersionFactory(state=constants.ARCHIVED) - user = factories.UserFactory() + user = self.get_superuser() request = RequestFactory().get("/admin/polls/pollcontent/") version.created_by = request.user = user actual_enabled_control = self.version_admin._get_revert_link(version, request) @@ -569,7 +568,7 @@ def test_discard_version_through_post_action(self): self.versionable.version_model_proxy, "discard", version.pk ) request = RequestFactory().post(draft_discard_url, {"discard": "1"}) - request.user = factories.UserFactory() + request.user = self.get_superuser() request.session = "session" messages = FallbackStorage(request) @@ -587,7 +586,7 @@ def test_discard_action_link_enabled_state(self): """ version = factories.PollVersionFactory(state=constants.DRAFT) request = RequestFactory().get("/admin/polls/pollcontent/") - request.user = factories.UserFactory() + request.user = self.get_superuser() draft_discard_url = self.get_admin_url( self.versionable.version_model_proxy, "discard", version.pk ) @@ -649,7 +648,7 @@ def test_revert_action_link_for_archive_state(self): The revert url should be null for unpublished state """ version = factories.PollVersionFactory(state=constants.UNPUBLISHED) - user = factories.UserFactory() + user = self.get_superuser() archive_version = version.copy(user) archive_version.archive(user) request = RequestFactory().get("/admin/polls/pollcontent/") @@ -730,7 +729,7 @@ class StateActionsTestCase(CMSTestCase): def test_archive_in_state_actions_for_draft_version(self): version = factories.PollVersionFactory(state=constants.DRAFT) request = RequestFactory().get("/admin/polls/pollcontent/") - request.user = factories.UserFactory() + request.user = self.get_superuser() # Get the version model proxy from the main admin site # Trying to test this on the plain Version model throws exceptions version_model_proxy = [ @@ -806,7 +805,7 @@ def test_archive_not_in_state_actions_for_unpublished_version(self): def test_publish_in_state_actions_for_draft_version(self): version = factories.PollVersionFactory(state=constants.DRAFT) request = RequestFactory().get("/admin/polls/pollcontent/") - request.user = factories.UserFactory() + request.user = self.get_superuser() # Get the version model proxy from the main admin site # Trying to test this on the plain Version model throws exceptions version_model_proxy = [ @@ -882,7 +881,7 @@ def test_publish_not_in_state_actions_for_unpublished_version(self): def test_unpublish_in_state_actions_for_published_version(self): version = factories.PollVersionFactory(state=constants.PUBLISHED) request = RequestFactory().get("/admin/polls/pollcontent/") - request.user = factories.UserFactory() + request.user = self.get_superuser() # Get the version model proxy from the main admin site # Trying to test this on the plain Version model throws exceptions version_model_proxy = [ @@ -962,7 +961,7 @@ def test_unpublish_not_in_state_actions_for_draft_version(self): def test_edit_in_state_actions_for_draft_version(self): version = factories.PollVersionFactory(state=constants.DRAFT) request = RequestFactory().get("/admin/polls/pollcontent/") - request.user = factories.UserFactory() + request.user = self.get_superuser() # Get the version model proxy from the main admin site # Trying to test this on the plain Version model throws exceptions version_model_proxy = [ @@ -1002,7 +1001,7 @@ def test_edit_not_in_state_actions_for_archived_version(self): def test_edit_in_state_actions_for_published_version(self): version = factories.PollVersionFactory(state=constants.PUBLISHED) request = RequestFactory().get("/admin/polls/pollcontent/") - request.user = factories.UserFactory() + request.user = self.get_superuser() # Get the version model proxy from the main admin site # Trying to test this on the plain Version model throws exceptions version_model_proxy = [ @@ -1129,7 +1128,7 @@ def test_archive_view_sets_modified_time(self): url = self.get_admin_url( self.versionable.version_model_proxy, "archive", poll_version.pk ) - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() with freeze_time("2999-01-11 00:00:00", tz_offset=0), self.login_user_context( user ): @@ -1165,7 +1164,7 @@ def test_archive_view_sets_state_and_redirects(self, mocked_messages): url = self.get_admin_url( self.versionable.version_model_proxy, "archive", poll_version.pk ) - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() with self.login_user_context(user): response = self.client.post(url) @@ -1288,7 +1287,7 @@ def test_archive_view_can_be_accessed_by_get_request(self): self.versionable.version_model_proxy, "archive", poll_version.pk ) - with self.login_user_context(self.get_staff_user_with_no_permissions()): + with self.login_user_context(self.get_superuser()): response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -1325,7 +1324,7 @@ def test_publish_view_sets_state_and_redirects(self, mocked_messages): url = self.get_admin_url( self.versionable.version_model_proxy, "publish", poll_version.pk ) - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() with self.login_user_context(user): response = self.client.post(url) @@ -1350,7 +1349,7 @@ def test_publish_view_redirects_according_to_settings(self): from djangocms_versioning import conf original_setting = conf.ON_PUBLISH_REDIRECT - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() conf.ON_PUBLISH_REDIRECT ="published" poll_version = factories.PollVersionFactory(state=constants.DRAFT) @@ -1389,7 +1388,7 @@ def test_published_view_sets_modified_time(self): url = self.get_admin_url( self.versionable.version_model_proxy, "publish", poll_version.pk ) - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() with freeze_time("2999-01-11 00:00:00", tz_offset=0), self.login_user_context( user ): @@ -1549,7 +1548,7 @@ def test_unpublish_view_sets_state_and_redirects(self, mocked_messages): url = self.get_admin_url( self.versionable.version_model_proxy, "unpublish", poll_version.pk ) - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() with self.login_user_context(user): response = self.client.post(url) @@ -1575,7 +1574,7 @@ def test_unpublish_view_sets_modified_time(self): url = self.get_admin_url( self.versionable.version_model_proxy, "unpublish", poll_version.pk ) - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() with freeze_time("2999-01-11 00:00:00", tz_offset=0), self.login_user_context( user ): @@ -1692,7 +1691,7 @@ def test_unpublish_view_can_be_accessed_by_get_request(self): self.versionable.version_model_proxy, "unpublish", poll_version.pk ) - with self.login_user_context(self.get_staff_user_with_no_permissions()): + with self.login_user_context(self.get_superuser()): response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -1729,7 +1728,7 @@ def publish_context(request, version, *args, **kwargs): } with patch.object(versioning_ext, "add_to_context", extra_context_setting): - with self.login_user_context(self.get_staff_user_with_no_permissions()): + with self.login_user_context(self.get_superuser()): response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -1762,7 +1761,7 @@ def test_unpublish_view_doesnt_throw_exception_if_no_app_registered_extra_unpubl versioning_ext = apps.get_app_config("djangocms_versioning").cms_extension with patch.object(versioning_ext, "add_to_context", {}): - with self.login_user_context(self.get_staff_user_with_no_permissions()): + with self.login_user_context(self.get_superuser()): response = self.client.get(url) self.assertEqual(response.status_code, 200) @@ -1815,7 +1814,7 @@ def test_revert_view_sets_modified_time(self): url = self.get_admin_url( self.versionable.version_model_proxy, "revert", poll_version.pk ) - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() with freeze_time("2999-01-11 00:00:00", tz_offset=0), self.login_user_context( user ): @@ -2371,9 +2370,7 @@ def test_changelist_view_displays_correct_breadcrumbs(self): expected = """""" self.assertEqual(str(breadcrumb_html), expected) @@ -2422,12 +2419,11 @@ def test_changelist_view_displays_correct_breadcrumbs_for_extra_grouping_values( breadcrumb_html = soup.find("div", class_="breadcrumbs") # Assert the breadcrumbs - we should have ignored the French one # and put the English one in the breadcrumbs + pk = page_content_en.pk expected = """""" self.assertEqual(str(breadcrumb_html), expected) @@ -2673,10 +2669,10 @@ def test_extended_version_change_list_display_renders_from_provided_list_display self.assertEqual(200, response.status_code) # Check list_display item is rendered - self.assertContains(response, '[TEST]{}'.format( - content.id, - content.text - )) + self.assertContains( + response, + f'[TEST]{content.text}' + ) # Check list_action links are rendered self.assertContains(response, "cms-action-btn") self.assertContains(response, "cms-action-preview") @@ -2901,10 +2897,10 @@ def test_extended_grouper_change_list_display_renders_from_provided_list_display # Check response is valid self.assertEqual(200, response.status_code) # Check list_display item is rendered - self.assertContains(response, '[TEST]{}'.format( - content.poll.id, - content.text - )) + self.assertContains( + response, + f'[TEST]{content.text}', + ) # Check list_action links are rendered self.assertContains(response, "cms-action-btn") self.assertContains(response, "cms-action-view") diff --git a/tests/test_integration_with_core.py b/tests/test_integration_with_core.py index f414e6b8..a4b8a8bd 100644 --- a/tests/test_integration_with_core.py +++ b/tests/test_integration_with_core.py @@ -221,7 +221,7 @@ class WizzardTestCase(CMSTestCase): def test_success_url_for_cms_wizard(self): from cms.cms_wizards import cms_page_wizard, cms_subpage_wizard - from cms.toolbar.utils import get_object_preview_url + from cms.toolbar.utils import get_object_edit_url, get_object_preview_url from djangocms_versioning.test_utils.polls.cms_wizards import ( poll_wizard, @@ -229,21 +229,24 @@ def test_success_url_for_cms_wizard(self): # Test against page creations in different languages. version = PageVersionFactory(content__language="en") - self.assertEqual( + self.assertIn( cms_page_wizard.get_success_url(version.content.page, language="en"), - get_object_preview_url(version.content), + [get_object_preview_url(version.content), get_object_edit_url(version.content)], ) version = PageVersionFactory(content__language="en") - self.assertEqual( + self.assertIn( cms_subpage_wizard.get_success_url(version.content.page, language="en"), - get_object_preview_url(version.content), + [get_object_preview_url(version.content), get_object_edit_url(version.content)], ) version = PageVersionFactory(content__language="de") - self.assertEqual( + self.assertIn( cms_page_wizard.get_success_url(version.content.page, language="de"), - get_object_preview_url(version.content, language="de"), + [ + get_object_preview_url(version.content, language="de"), + get_object_edit_url(version.content, language="de") + ], ) # Test against a model that doesn't have a PlaceholderRelationField diff --git a/tests/test_locking.py b/tests/test_locking.py index 82e61aeb..bbc72d94 100644 --- a/tests/test_locking.py +++ b/tests/test_locking.py @@ -270,11 +270,13 @@ def test_unlock_link_not_present_for_user_with_no_unlock_privileges(self): locked_by=self.user_author) changelist_url = version_list_url(poll_version.content) unlock_url = self.get_admin_url(self.versionable.version_model_proxy, "unlock", poll_version.pk) - + exprected_disabled_button = ( + f'' + ) with self.login_user_context(self.user_has_no_unlock_perms): response = self.client.post(changelist_url) - - self.assertNotContains(response, unlock_url) + self.assertInHTML(exprected_disabled_button, response.content.decode("utf-8")) def test_unlock_link_present_for_user_with_privileges(self): poll_version = factories.PollVersionFactory( @@ -392,11 +394,12 @@ def test_edit_action_link_disabled_state(self): author_request.user = self.user_author otheruser_request = RequestFactory() otheruser_request.user = self.superuser + expected_disabled_state = "inactive" actual_disabled_state = self.version_admin._get_edit_link(version, otheruser_request) self.assertFalse(version.check_edit_redirect.as_bool(self.superuser)) - self.assertEqual("", actual_disabled_state) + self.assertIn(expected_disabled_state, actual_disabled_state) @override_settings(DJANGOCMS_VERSIONING_LOCK_VERSIONS=True) @@ -647,7 +650,7 @@ def test_version_is_unlocked_for_publishing(self): """ A version lock is not present when a content version is in a published or unpublished state """ - user = self.get_staff_user_with_no_permissions() + user = self.get_superuser() poll_version = factories.PollVersionFactory(state=DRAFT, created_by=user, locked_by=user) publish_url = self.get_admin_url(self.versionable.version_model_proxy, "publish", poll_version.pk) unpublish_url = self.get_admin_url(self.versionable.version_model_proxy, "unpublish", poll_version.pk) diff --git a/tests/test_permissions.py b/tests/test_permissions.py new file mode 100644 index 00000000..5dc74a35 --- /dev/null +++ b/tests/test_permissions.py @@ -0,0 +1,259 @@ +from unittest.mock import patch + +from django.core.checks import messages + +from djangocms_versioning import constants +from djangocms_versioning.models import StateTracking, Version +from djangocms_versioning.test_utils import factories +from djangocms_versioning.test_utils.blogpost.cms_config import BlogpostCMSConfig +from djangocms_versioning.test_utils.polls.cms_config import PollsCMSConfig +from tests.test_admin import BaseStateTestCase + + +class PermissionTestCase(BaseStateTestCase): + def setUp(self): + self.versionable = BlogpostCMSConfig.versioning[0] + self.poll_versionable = PollsCMSConfig.versioning[0] + + def get_user(self, username, is_staff=True): + user = factories.UserFactory(username=username, is_staff=is_staff) + user.set_password(username) + user.save() + return user + + @patch("django.contrib.messages.add_message") + def test_publish_view_cannot_be_accessed_without_permission( + self, mocked_messages + ): + post_version = factories.BlogPostVersionFactory(state=constants.DRAFT) + url = self.get_admin_url( + self.versionable.version_model_proxy, "publish", post_version.pk + ) + + with self.login_user_context(self.get_staff_user_with_no_permissions()): + response = self.client.post(url) + + self.assertRedirectsToPreview(response, post_version) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.ERROR) + self.assertEqual(mocked_messages.call_args[0][2], "You do not have permission to perform this action") + + # status hasn't changed + post_version = Version.objects.get(pk=post_version.pk) + self.assertEqual(post_version.state, constants.DRAFT) + # no status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 0) + + @patch("django.contrib.messages.add_message") + def test_unpublish_view_cannot_be_accessed_without_permission( + self, mocked_messages + ): + post_version = factories.BlogPostVersionFactory(state=constants.PUBLISHED) + url = self.get_admin_url( + self.versionable.version_model_proxy, "unpublish", post_version.pk + ) + + with self.login_user_context(self.get_staff_user_with_no_permissions()): + response = self.client.post(url) + + self.assertRedirectsToPreview(response, post_version) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.ERROR) + self.assertEqual(mocked_messages.call_args[0][2], "You do not have permission to perform this action") + + # status hasn't changed + post_version = Version.objects.get(pk=post_version.pk) + self.assertEqual(post_version.state, constants.PUBLISHED) + # no status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 0) + + + @patch("django.contrib.messages.add_message") + def test_publish_view_can_be_accessed_with_low_level_permission( + self, mocked_messages + ): + # alice has no permission to publish bob's post + post_version = factories.BlogPostVersionFactory(state=constants.DRAFT, content__text="bob's post") + url = self.get_admin_url( + self.versionable.version_model_proxy, "publish", post_version.pk + ) + + with self.login_user_context(self.get_user("bob")): + self.client.post(url) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.INFO) + self.assertEqual(mocked_messages.call_args[0][2], "Version published") + + # status has changed + post_version = Version.objects.get(pk=post_version.pk) + self.assertEqual(post_version.state, constants.PUBLISHED) + # status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 1) + + @patch("django.contrib.messages.add_message") + def test_publish_view_cannot_be_accessed_wo_low_level_permission( + self, mocked_messages + ): + # alice has no permission to publish bob's post + post_version = factories.BlogPostVersionFactory(state=constants.DRAFT, content__text="bob's post") + url = self.get_admin_url( + self.versionable.version_model_proxy, "publish", post_version.pk + ) + + with self.login_user_context(self.get_user("alice")): + response = self.client.post(url) + + self.assertRedirectsToPreview(response, post_version) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.ERROR) + self.assertEqual(mocked_messages.call_args[0][2], "You do not have permission to perform this action") + + # status hasn't changed + post_version = Version.objects.get(pk=post_version.pk) + self.assertEqual(post_version.state, constants.DRAFT) + # no status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 0) + + @patch("django.contrib.messages.add_message") + def test_unpublish_view_can_be_accessed_with_low_level_permission( + self, mocked_messages + ): + # bob has permission to unpublish bob's post + post_version = factories.BlogPostVersionFactory(state=constants.PUBLISHED, content__text="bob's post") + url = self.get_admin_url( + self.versionable.version_model_proxy, "unpublish", post_version.pk + ) + + with self.login_user_context(self.get_user("bob")): + self.client.post(url) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.INFO) + self.assertEqual(mocked_messages.call_args[0][2], "Version unpublished") + + # status has changed + post_version = Version.objects.get(pk=post_version.pk) + self.assertEqual(post_version.state, constants.UNPUBLISHED) + # status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 1) + + @patch("django.contrib.messages.add_message") + def test_unpublish_view_cannot_be_accessed_wo_low_level_permission( + self, mocked_messages + ): + # alice has no permission to unpublish bob's post + post_version = factories.BlogPostVersionFactory(state=constants.PUBLISHED, content__text="bob's post") + url = self.get_admin_url( + self.versionable.version_model_proxy, "unpublish", post_version.pk + ) + + with self.login_user_context(self.get_user("alice")): + response = self.client.post(url) + + self.assertRedirectsToPreview(response, post_version) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.ERROR) + self.assertEqual(mocked_messages.call_args[0][2], "You do not have permission to perform this action") + + # status hasn't changed + post_version = Version.objects.get(pk=post_version.pk) + self.assertEqual(post_version.state, constants.PUBLISHED) + # no status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 0) + + @patch("django.contrib.messages.add_message") + def test_archive_view_cannot_be_accessed_without_permission( + self, mocked_messages + ): + post_version = factories.BlogPostVersionFactory(state=constants.DRAFT) + url = self.get_admin_url( + self.versionable.version_model_proxy, "archive", post_version.pk + ) + user = self.get_staff_user_with_no_permissions() + + with self.login_user_context(user): + self.client.post(url) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.ERROR) + self.assertEqual(mocked_messages.call_args[0][2], "You do not have permission to perform this action") + + # status hasn't changed + post_version = Version.objects.get(pk=post_version.pk) + self.assertEqual(post_version.state, constants.DRAFT) + # no status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 0) + + @patch("django.contrib.messages.add_message") + def test_archive_view_can_be_accessed_with_permission( + self, mocked_messages + ): + poll_version = factories.PollVersionFactory(state=constants.DRAFT) + url = self.get_admin_url( + self.poll_versionable.version_model_proxy, "archive", poll_version.pk + ) + user = self.get_staff_user_with_no_permissions() + user.user_permissions.add(self.get_permission("change_pollcontent")) + + with self.login_user_context(user): + self.client.post(url) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.INFO) + self.assertEqual(mocked_messages.call_args[0][2], "Version archived") + + # status has changed + poll_version_ = Version.objects.get(pk=poll_version.pk) + self.assertEqual(poll_version_.state, constants.ARCHIVED) + # status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 1) + + @patch("django.contrib.messages.add_message") + def test_revert_view_cannot_be_accessed_without_permission( + self, mocked_messages + ): + post_version = factories.BlogPostVersionFactory(state=constants.ARCHIVED) + url = self.get_admin_url( + self.versionable.version_model_proxy, "revert", post_version.pk + ) + user = self.get_staff_user_with_no_permissions() + + with self.login_user_context(user): + self.client.post(url) + + self.assertEqual(mocked_messages.call_count, 1) + self.assertEqual(mocked_messages.call_args[0][1], messages.ERROR) + self.assertEqual(mocked_messages.call_args[0][2], "You do not have permission to perform this action") + + # status hasn't changed + poll_version_ = Version.objects.get(pk=post_version.pk) + self.assertEqual(poll_version_.state, constants.ARCHIVED) + # no status change has been tracked + self.assertEqual(StateTracking.objects.all().count(), 0) + + @patch("django.contrib.messages.add_message") + def test_revert_view_can_be_accessed_with_low_level_permission( + self, mocked_messages + ): + post_version = factories.BlogPostVersionFactory(state=constants.ARCHIVED, content__text="post ") + url = self.get_admin_url( + self.versionable.version_model_proxy, "revert", post_version.pk + ) + user = self.get_user("alice", is_staff=True) + with self.login_user_context(user): + self.client.post(url) + + # new draft has been created + post_version_ = Version.objects.filter( + content_type=post_version.content_type, + object_id__gt=post_version.object_id, + pk__gt=post_version.pk + ).first() + self.assertIsNotNone(post_version_) + self.assertEqual(post_version_.state, constants.DRAFT) + self.assertTrue(post_version_.content.has_change_permission(user)) # Content was copied diff --git a/tests/test_toolbars.py b/tests/test_toolbars.py index 665cdd36..deb1f038 100644 --- a/tests/test_toolbars.py +++ b/tests/test_toolbars.py @@ -73,7 +73,7 @@ def test_revert_in_toolbar_in_preview_mode(self): version = PollVersionFactory() version.archive(self.get_superuser()) - toolbar = get_toolbar(version.content, edit_mode=False) + toolbar = get_toolbar(version.content, edit_mode=False, user=self.get_superuser()) toolbar.post_template_populate() publish_button = find_toolbar_buttons("Publish", toolbar.toolbar)