Barolina
12/13/2017 - 8:01 PM

Field permissions mixin for Django Rest Framework

Field permissions mixin for Django Rest Framework

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