djangodjango-permissions

Django User not inheriting Group permissions


I have a TestCase that i'm testing permissions on. I don't understand how this test is failing where it's failing:

        # Make sure group has permission
        group_permissions = self.my_group.permissions.filter(codename="view_mymodel")
        self.assertEqual(len(group_permissions), 1)

        print("Group Permissions:")
        for permission in group_permissions:
            print(permission)

        # Make sure user is in group
        user_groups = self.user.groups.filter(name="My User Group")
        self.assertEqual(len(user_groups), 1)

        user_permissions = self.user.get_all_permissions()
        print("User Permissions:")
        for permission in user_permissions:
            print(permission)

        # Make sure user has permission
        self.assertTrue(self.user.has_perm("myapp.view_mymodel"))

This is failing at the last assertion. I can see the permission is set for the group but when i call get_all_permissions(), nothing shows up. That makes no sense because get_all_permissions() is suppose to return all permissions on both the User and the group.


Solution

  • Turns out this was a caching issue. If I re-authenticate the user after setting permissions, I see the test passing.

            # Make sure user is in group
            user_groups = self.user.groups.filter(id=self.my_group.id)
            self.assertEqual(len(user_groups), 1)
            
            # Refresh cache on the user
            self.user = get_object_or_404(User, pk=self.user.id)
    
            user_permissions = self.kcs_user.get_all_permissions()
            print("User Permissions:")
            for permission in user_permissions:
                print(permission)
    
            # Make sure user has permission
            self.assertTrue(self.user.has_perm("myapp.view_mymodel"))
    
            # Re-authenticate the client to refresh permissions on the request User
            self.client.force_authenticate(user=self.user)
    

    Problem solved!