Home > Mobile >  Django permissions are present but has_perm() returns False
Django permissions are present but has_perm() returns False

Time:01-29

I'm working on the permissions on a Django 4.1 application. All these permissions are given by groups. First permission first problem:

Permission codename: can_see_all_images appname for the permission: dating group having this permission: X-Gold

As you can see on the screenshot it seems that all the informations are correct: Screenshot

First line: User is in the group Second line, the group has the permission Third line: The permission has the good codename but line4: the user doesn't have the perm.

I restarted the server disconnected the user and reconnected it, nothing changed. Note that if I give the permission directly to the user, it doesn't work. So I guess the problem does not come from the group.

Any idea?

Here is how the permission is created in the model:

permissions = [('can_see_all_images', _('Can see all images'))]

edit: my view code:

@login_required
def public_images(request, slug):
    visited = get_object_or_404(User, slug=slug, is_active=True)
    user = User.objects.get(id=request.user.id)
    if user.has_perm('dating.can_see_all_images'):
        print('ok')
    else:
        print('KO')
    return render(request, 'dating/public_images.html', locals())

Thanks in advance

CodePudding user response:

try using the example given below

    user_id =  request.data.get('user_id') #any existing user id
    user = User.objects.get(id=user_id) # get the user object first
    if user.has_perm('dating.can_see_all_images'):
       pass
    else:
        res = {
                 "message": f"You are not authorized to access API"
            }
        pass

if still stuck after this, then please add your code.

CodePudding user response:

I found the problem, so I post it here in case someone meet the same.

I am using a custom authentication backend. This backend inherits from BasicBackend. In this case you have to redefine the has_perm() method because in the BaseBackend the original method return an empty tuple.

If you don't want to redefine it you need to inherit from ModelBackend and not BaseBackend.

  • Related