Created
July 15, 2015 13:01
-
-
Save synotna/79f1e0128fb98394ceb6 to your computer and use it in GitHub Desktop.
Field permissions mixin for Django Rest Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FieldPermissionsMixin(object): | |
""" | |
A Serializer mixin for controlling which fields are included based on user permissions | |
Usage: | |
class MySerializer(FieldPermissionsMixin, serializers.ModelSerializer): | |
class Meta: | |
model = MyModel | |
field_permissions = { | |
'field': ['app.permission'], | |
} | |
""" | |
class Meta: | |
# field name: [list of permissions] | |
field_permissions = {} | |
def get_fields(self): | |
fields = super().get_fields() | |
user_permissions = self.context['request'].user.get_all_permissions() | |
for field, permissions in self.Meta.field_permissions.items(): | |
# if user does not have one of the permissions to view the field, remove it | |
if not any(permission in user_permissions for permission in permissions): | |
fields.pop(field) | |
return fields |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment