Yii2: authManager should have a method like userHasRole()

(Tailormade) #1

Sometime I just want to know if a user has a certain role or not. Especially for the current authenticated user.

One can use Yii::$app->authManager->getRolesByUser($user_id) to get the roles and then loop through them to find out if the user has got the role. But it could already part of the BaseManager (abstract or base implementation, and finally implemented in PhpManager and DbManager) with a method like userHasRole($user_id, $role) which returns true or false.

Even better would be Yii::$app->user->hasRole($role). Is this possible?

This could result in better performance - e.g. the DbManager could use better queries.

(Alexander Makarov) #2

Yes, it’s just


(Tailormade) #3

Okay, this already exists. Though, in my opionion ‘can’ is a not so obvious method name in context of roles.

(Alexander Makarov) #4

Yeah but checking for role and not specific permission isn’t common either.

(Tailormade) #5

Ah, I see. Thanks for you hint. I’m not that experienced with RBAC. I thought it would be okay, but most likely you’re right.

Is this documented in the Yii Guide or anywhere else? Do you have a link? I think the Yii Guide just says that you can use roles and permissions but does not suggest how to do it or what is best practice.

(Alexander Makarov) #6