yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.24k stars 6.91k forks source link

Regression Yii2 2.0.48: Assigning role to a user with DbManager doesn't clear the cache #19847

Closed michaelarnauts closed 1 year ago

michaelarnauts commented 1 year ago

Since https://github.com/yiisoft/yii2/pull/19727 has been merged, DbManager is now correctly using the cache, but this causes another issue to pop up.

It seems that assign(), revoke() and revokeAll() don't invalidate the cache.

What steps will reproduce the problem?

$user_id = 1;

\Yii::$app->authManager->revokeAll($user_id); // remove all roles
\Yii::$app->cache->flush(); // clear the cache

/* get roles */
$roles = \Yii::$app->authManager->getRolesByUser($user_id);
print_r($roles);
// Array
// (
// )

/* add role */
$assignment = \Yii::$app->authManager->assign(\Yii::$app->authManager->getRole('site-admin'), $user_id);
print_r($assignment);
// yii\rbac\Assignment Object
// (
//    [userId] => 1
//    [roleName] => site-admin
//    [createdAt] => 1684936909
// )

/* get roles */
$roles = \Yii::$app->authManager->getRolesByUser($user_id);
print_r($roles);
// Array
// (
// )

\Yii::$app->cache->flush(); // clear the cache

/* get roles */
$roles = \Yii::$app->authManager->getRolesByUser($user_id);
print_r($roles);
// Array
// (
//    [site-admin] => yii\rbac\Role Object
//        (
//            [type] => 1
//            [name] => site-admin
//            [description] => Site administrator. Has all permissions.
//            [ruleName] =>
//            [data] =>
//            [createdAt] => 1684936058
//            [updatedAt] => 1684936058
//        )
//
// )

What is the expected result?

After the assign(), call I expect the internal cache to be invalidated, so subsequent calls to getRolesByUser() give correct info.

What do you get instead?

The initial call to getRolesByUser() create a cache entry, but that isn't updated when assign() is called, so the subsequent call to getRolesByUser() is giving the old cached data.

Additional info

Q A
Yii version 2.0.48
PHP version 8.2
Operating system Ubuntu 22.04
michaelarnauts commented 1 year ago

@manchenkoff can you check if you also notice this behaviour?