0

I am using native CDbAuthManager to implement RBAC in my webapp. How can I get all the users who has permission to do a role? Suppose I have role named updateprofile. I want to get all the users assigned to that role. I searched the documentation and couldnt find a function.

(I know i can iterate through all user models and do a checkAccess() in a foreach loop, but I prefer a nicer solution )

dInGd0nG
  • 4,162
  • 1
  • 24
  • 37
  • 1
    If you prefer a nicer solution you should use this extension: http://www.yiiframework.com/extension/yii-user-management – adamors Feb 07 '13 at 23:46

3 Answers3

2

The easiest way I've found to do this is to create an AuthAssignment model that maps to your auth_assignment table. Then, you can setup relationships, scopes, etc for it and query using it to retrieve all user models. There isn't anything particularly special about the auth_assignment table (as it is mainly just roles in there).

acorncom
  • 5,975
  • 1
  • 19
  • 31
2

code like

class AuthAssginment extends CActiveRecord{.....
    public function getUsersBaseOnRole($role) {
         return Yii::app()->db->createCommand()
                    ->select('userid')
                    ->from($this->tableName())
                    ->where('itemname=:role', array(
                        ':role' => $role,))
                    ->queryAll() ;


}....
za_al
  • 111
  • 6
1

I think the other replies do not give you the perfect result because roles can be hierarchical and so, you cannot use direct queries or relations. My solution which works well is:

// list all users with 'userManagement' role
if($users = Users::model()->findAll()) {
    foreach($users as $id => $user) {
        if(!$user->checkAccess('userManagement')) {
            unset($users[$id]);
        }
    }
    $users = array_values($users); // to reset indices (optional)
}
MLFR2kx
  • 977
  • 7
  • 16