0

It's my first time creating a project with Django in the backend and React frontend. I have a custom user model with boolean fields as is_moderator & is_admin & is_poster. In the frontend, there's a certain button that should only be visible to admins and moderators. So my question is how to make that button only visible to them, I made Django custom permission like that

class IsModerator(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user.is_authenticated:
            return True

    def has_object_permission(self, request, view, obj):
        if request.user.is_moderator:
            return True 
        if request.user.is_admin:
            return True 
        return False

and add it to the view. In that case, it is available to all kinds of users so when normal users other than moderators and admin click the button it will display an error in the console, to avoid that error I made a condition in the react component checking if the user is logged in and is admin or moderator then display the button, otherwise don't display it, but by that condition, there's no point of the custom permission.

Is there a better way to achieve it?

Menna Magdy
  • 355
  • 1
  • 2
  • 14

1 Answers1

0

I'd say you have to check in both the frontend and backend. If you don't do the permission check in the backend and just hide the button, then a user could still send a manual request to that endpoint and get data they're not supposed to have access to.

So, I think you have done it in a good way.

PS. With your current Permission class IsModerator users that are NOT mods or admin will still have access to actions within your view that are not object level, i.e list, create.

Felix Eklöf
  • 3,253
  • 2
  • 10
  • 27
  • Thank you, Felix, but in that case, if I used the conditions in the frontend and removed the custom permission from the backend, it will also achieve the same thing, that's why I thought there's something missing in my way. for the view it is an API view with patch function only. – Menna Magdy Oct 12 '21 at 10:50
  • I'm not sure I understand completely, but I meant that you should keep your Permission class in backend. This ensures that a user can't access disallowed data. And then you check in the frontend if that user is an admin or mod, then hide button if not. The check in frontend is not secure since someone could just send a request to the endpoint the button is pointing to. – Felix Eklöf Oct 12 '21 at 10:55