简体   繁体   中英

How to serialize user permissions in Django Rest Framework?

I'm building an application with a Django rest backend and a React frontend and working on authorization and authentication. Authentication works well, but I'm a bit stuck when it comes to telling the frontend what the user is authorized to do in terms of add/edit/view/delete for a model. For example, if a user cannot edit a story, I don't want to display the 'Edit Story' button.

When working through the Django documents, I consider it easiest to send the user's permissions from Django backend to the React frontend. Therefore I want to serialize the user permissions.

This is my View :

class UserAPI(generics.RetrieveAPIView):
  permission_classes = [
    permissions.IsAuthenticated, 
  ]
  serializer_class = UserSerializer

  def get_permissions(request):
    logged_in_user = request.user
    return Response(data=logged_in_user.get_all_permissions())

  def get_object(self):
    return self.request.user

This is my Serializer :

class UserSerializer(serializers.ModelSerializer):
  class Meta:
    model = User
    fields = ('id', 'username', 'user_permissions')

The user Model :

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics/')


    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)

When i call the UserAPI the field user_permissions is empty.

 "user": {
        "id": 35,
        "username": "HII",
        "user_permissions": [
        ]
    }

I wonder how i can not access the user_permission via my API. I'm happy for any hint and clarification.

When i need something like that, i use to SerializerMethodField. You can add SerializerMethodField and you will set all permissions which auth user has.

class UserSerializer(serializers.ModelSerializer):
    user_permissions = serializers.SerializerMethodField()
    class Meta:
        model = User
        fields = ('id', 'username', 'user_permissions')
    def get_user_permissions(self, obj):
        return list(obj.user_permissions.all()) # I'm not sure list type casting is necessary

you can try the following -

user_id = request.user.pk
username = request.user.username
permissions = list(request.user.get_all_permissions())

return HttpResponse(
        json.dumps(CurrentUser(user_id, username, permissions),
                   default=lambda obj: obj.__dict__), content_type='application/json')


class CurrentUser:
    def __init__(self, user_id, username, permissions):
        self.user_id = user_id
        self.username = username
        self.permissions = permissions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM