开发者

Django signal handler that monitors changes to groups & permissions?

开发者 https://www.devze.com 2023-03-11 19:54 出处:网络
I\'d like to register a signal handler on the User model that looks something like this: def post_save_handler(sender, instance, created, **kwargs):

I'd like to register a signal handler on the User model that looks something like this:

def post_save_handler(sender, instance, created, **kwargs): 
    should_have_profile = instance.has_perm('profile.should_have')

    if should_have_profile: 
        profile, created = Profile.objects.get_or_create(user=instance)
        if crated: 
            profile.save() 
    else: 
        old_profile = Profile.objects.filter(user=instance)
        if old_profile: 
            old_profile.delete() 

But, in the signal handler, the test for "has_perm" on the new permission (that was added or deleted in the view code via changing group membership) isn't coming in correctly. It's as if the new groups haven't been applied yet.

I briefly suspected _group_perm_cache and _perm_cache in contrib.auth.backends.py, but I augmented my signal handler to remove those values from the incoming instance, and the result is the same.开发者_Python百科

All I can surmise is that any changes to the current groups aren't passed through for this user. I also tried registering a m2m_changed listener on the User object for this purpose, but that wasn't called either (likely because User.groups isn't implemented as a ManyToManyField).

Is there any way to properly do what I'm wanting?


m2m_changed includes an argument that tells what side of the relation the change happened on, so that implies that it'll work both ways. Groups are M2M, but the ManyToManyField is on the Group model, not the User model. It's possible that if you're passing a sender in the connect method, that it should actually be Group because that's where the ManyToManyField resides. Not sure about that, but it's the only thing I can think of for why your m2m_changed signal would not have been sent.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号