Skip to content

Commit

Permalink
Support objects without permissions in DictRelatedField
Browse files Browse the repository at this point in the history
  • Loading branch information
gregorjerse committed Jan 27, 2025
1 parent f48a15e commit e6db5e4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 19 deletions.
1 change: 1 addition & 0 deletions docs/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Changed
-------
- **BACKWARD INCOMPATIBLE:** Require ``Django 5.1.x`` and bump version of
dependencies
- Support objects without permissions in ``DictRelatedField``

Fixed
-----
Expand Down
41 changes: 22 additions & 19 deletions resolwe/flow/serializers/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from drf_spectacular.utils import extend_schema_field
from rest_framework import exceptions, relations, serializers

from resolwe.permissions.models import Permission
from resolwe.permissions.models import Permission, PermissionInterface


class PrimaryKeyDictRelatedField(serializers.PrimaryKeyRelatedField):
Expand Down Expand Up @@ -88,28 +88,31 @@ def to_internal_value(self, data):

user = getattr(self.context.get("request"), "user")
queryset = self.get_queryset()
has_permissions = issubclass(queryset.model, PermissionInterface)
permission = self.write_permission
try:
return (
queryset.filter(**kwargs)
.filter_for_user(user, permission)
.latest("version")
)
queryset = queryset.filter(**kwargs)
# Filter queryset based on permissions (if model has them).
if has_permissions:
queryset = queryset.filter_for_user(user, permission)
return queryset.latest("version")
except ObjectDoesNotExist:
# Differentiate between "user has no permission" and "object does not exist"
view_permission = Permission.VIEW
if permission != view_permission:
try:
queryset.filter(**kwargs).filter_for_user(
user, view_permission
).latest("version")
raise exceptions.PermissionDenied(
"You do not have {} permission for {}: {}.".format(
self.write_permission, self.model_name, data
if has_permissions:
# Differentiate between "user has no permission" and "object does not exist"
view_permission = Permission.VIEW
if permission != view_permission:
try:
queryset = self.get_queryset()
queryset.filter(**kwargs).filter_for_user(
user, view_permission
).latest("version")
raise exceptions.PermissionDenied(
"You do not have {} permission for {}: {}.".format(
self.write_permission, self.model_name, data
)
)
)
except ObjectDoesNotExist:
pass
except ObjectDoesNotExist:
pass

self.fail(
"does_not_exist", value=smart_str(data), model_name=self.model_name
Expand Down

0 comments on commit e6db5e4

Please sign in to comment.