Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove user's permissions (django)

I have an issue with removing permissions to users in view or even in the shell. Let me explain my problem:

I did those tests in the shell:

org = Organisateur.objects.get(user__username__contains="ghj") 
content_type = ContentType.objects.get_for_model(Tournoi)

Tournoi is the name of a model

permission_ecriture = 'ecriture_Palaiseau'
permission = Permission.objects.get(content_type=content_type, codename=permission_ecriture)
org.user.user_permissions.remove(permission)`

but when I write:

org.user.has_perm('inscription.ecriture_Palaiseau')` 

it returns True

but when I rewrite:

org = Organisateur.objects.get(user__username__contains="ghj")
org.user.has_perm('inscription.ecriture_Palaiseau')`

it returns False

It is really weird. Why does it works like this?

In my views, it seems that the permissions are not removed even if I do write:

org = Organisateur.objects.get(user__username__contains="ghj")

(after removing the permission, the user still has it)

What I want to do is to remove a permission from an user and add another permission to the same user immediately after. But each time I do that, the user still has the "removed permission"......

Thank you very much

I look forward to hearing from you all soon.

like image 288
karna Avatar asked Feb 09 '23 07:02

karna


1 Answers

This behavior is expected because permissions are cached. From the Django docs:

Permission caching

The ModelBackend caches permissions on the User object after the first time they need to be fetched for a permissions check. This is typically fine for the request-response cycle since permissions are not typically checked immediately after they are added (in the admin, for example). If you are adding permissions and checking them immediately afterward, in a test or view for example, the easiest solution is to re-fetch the User from the database.

like image 56
Daniel Hepper Avatar answered Feb 11 '23 23:02

Daniel Hepper