kmmbvnr / django-guardian-ng

Per object permissions for Django
https://django-guardian.readthedocs.io/
Other
1 stars 0 forks source link

Provide a shortcut function for "reassigning" user permissions. #8

Open kmmbvnr opened 5 months ago

kmmbvnr commented 5 months ago

Original issue: https://github.com/django-guardian/django-guardian/issues/810

kmmbvnr commented 5 months ago

Possible solution: https://stackoverflow.com/questions/77431461/reassign-all-guardian-user-object-permissions-from-one-django-user-to-another-dj

from django.db.models import Exists, OuterRef
from guardian.models.models import UserObjectPermissionBase

def change_perm_for_klass(klass, old_user, new_user):
    klass.objects.filter(
        ~Exists(
            klass.objects.filter(
                user=new_user,
                content_object=OuterRef('content_object'),
                permission=OuterRef('permission'),
            )
        ),
        user=old_user,
    ).update(user=new_user)
    klass.objects.filter(user=old_user).delete()

def update_permissions_for_user(old_user, new_user):
    subclasses = set()
    new_gen = {UserObjectPermissionBase}
    while new_gen:
        subclasses.update(new_gen)
        new_gen = {sc for k in new_gen for sc in k.__subclasses__()}
    for klass in subclasses:
        if not klass._meta.abstract:
            change_perm_for_klass(klass, old_user, new_user)
kmmbvnr commented 5 months ago