lonnieezell / myth-auth

One-stop Auth package for CodeIgniter 4
MIT License
637 stars 208 forks source link

Bug: Group Permissions and User cache #533

Open MGatner opened 2 years ago

MGatner commented 2 years ago

User permissions cache is not updated when Group permissions are altered, creating a potential lag time between adding/removing a group permission and the update to the user.

rivaldysaputraagus commented 2 years ago

I also encountered a problem like this, how to fix it? Any references to problems like this ?

manageruz commented 2 years ago

I also encountered a problem like this, how to fix it? Any references to problems like this ?

There are three methods in GroupModel.php file which alter group permissions. They are addPermissionToGroup(), removePermissionFromGroup() and removePermissionFromAllGroups(). So after group permissions altered you should retrieve users which belong to that group and delete there user permisssions cache files.

manageruz commented 2 years ago

Next time when there will be a call to get user's permissions, new data will be retrieved from database and saved to cache.

GagaPoloJr commented 1 year ago

I faced this issue while using has_permission() from Helper Functions which refers to this function getPermissionsForUser() which contains cache()->save("{$userId}_permissions", $found, 300);

Then I checked the model between permissionModel & groupModel and see the difference. You can see function addPermissionToGroup in groupModel doesn't delete cache {$userId}_permissions.

It means that when the has_permission() code runs every time, it caches the current_user permissions {$userId}_permissions.

PermissionModel.php

{
...
},

public function addPermissionToUser(int $permissionId, int $userId)
    {
        cache()->delete("{$userId}_permissions"); //these line
        return $this->db->table('auth_users_permissions')->insert([
            'user_id'       => $userId,
            'permission_id' => $permissionId,
        ]);
    }

GroupModel.php

{
...
},

 public function addPermissionToGroup(int $permissionId, int $groupId)
    {

        $data = [
            'permission_id' => $permissionId,
            'group_id'      => $groupId,
        ];

        return $this->db->table('auth_groups_permissions')->insert($data);
    }

alternative way can add this cache()->delete("{$userId}_permissions") on function addPermissionToGroup() to update the cache. Then can follow the code flow for fix errors related to the function.