Access Rules matchCallback redirect to login

Hello everybody,

This is my behaviors function in backend/SiteController , i am using User::isUserAdmin($param,$param) function for checking if logged user has admin role or not. Now i got 403 error page, when i try to access the index function with normal user without admin role. How can i set a return url to login page, when this function User::isUserAdmin($param,$param) return false value.




public function behaviors()

{

   return [

       'access' => [

           'class' => AccessControl::className(),

           'only' => ['logout', 'index'],

           'rules' => [

               [

                   'actions' => ['logout'],

                   'allow' => true,

                   'roles' => ['@'],

               ],

               [

                   'actions' => ['index'],

                   'allow' => true,

                   'roles' => ['@'],

                   'matchCallback' => function ($rule, $action) {

                       return User::isUserAdmin(Yii::$app->user->identity->username);

                   },

                    

               ],

           ],

       ],

       'verbs' => [

           'class' => VerbFilter::className(),

           'actions' => [

               'logout' => ['post'],

           ],

       ],

   ];

}



The way I did it in my project was to create a separate helper method for this purpose. I don’t use matchCallback in behaviors for redirecting because it’s only looking for true or false and doesn’t give you any options otherwise. When I looked at modifying access rules for this purpose, it seemed like I was going in the wrong direction.

You can create a helper method that tests access level and redirects, but you will have to put it in the action directly. Or you can just use the isUserAdmin method from the tutorial as a starting point and modify the method to redirect if it returns false. Then you would just put:

[size="2"]





User::isUserAdmin(Yii::$app->user->identity->username);




[size="2"]As the first line in any action you want to apply it. Please keep in mind that this is a variation of super simple RBAC implementation, which is not meant to redirect, so this might get too procedural depending on how you use it.[/size]

Your modified isUserAdmin could look like this:[/size]





public static function isUserAdmin($username)

{

	if (static::findOne(['username' => $username, 'role' => self::ROLE_ADMIN])){


		return true; 


	} else {

       

	return Yii::$app->getResponse()->redirect(Url::to(['yourcontroller/action']));


    }

}




I haven’t tested, so there might be a typo. Also, I don’t think this will work in matchCallback for the reasons stated above, so it you wanted to use matchCallback in certain scenarios, you need to write a second method that is like the original.

Thank you. :rolleyes: