Reputation: 495
I'm fairly new and django rest framework and I have some questions regardin permissions.
So I have a user who is a member of organization and member of some group. Lets say we have a model:
class SomeModel:
organization = models.ForeignKey(Organization)
name = models.CharField()
User can only create
/ update
SomeModel
for its own organization and if he's a group of "Coordinators" he can also create
/ update
for any organization.
Currently my approach is to check these conditions in serializer, in .create()
and .update()
methods, since the data is already validated and I'm raising PermissionDenied
errors there. But it feels like that this is not "the right way". I tried making a custom permissions classes, but then the data is not validated, since permissions classes are checked before serializers.
Do you have any suggestions how should I approach this?
Sorry for bad english, it's not my native language. Thanks!
EDIT: Example: Request data is something like:
payload = {'organization': 1, 'name': 'Name'}
So if a user is from organization 1 or he's a coordinator access should be granted and SomeModel
should be created
Upvotes: 4
Views: 4050
Reputation: 47846
You can write a custom permission class HasWritePermissions
which will check whether a user has write/update permissions.
To create a custom permission class, you will need to override BasePermission
class and implement has_permission()
method. This method should return True
if request is to granted access, otherwise False
.
class HasWritePermissions(BasePermission):
def has_permission(self, request, view):
# grant access to non-create/update requests
if request.method not in ['POST', 'PUT', 'PATCH']:
return True
# grant access if user is a member of organization of the object
# to be modified or is a coordinator
if (organization in user.organizations) or (user_is_a_coordinator):
return True
# Otherwise don't grant access
return False
Upvotes: 5