I have user and agency models
user have an agency model and can access whit $user->agency
now i want check in accessRule when relation is exist show my controller if that relation is null show an alert 'user->agency is null pealse create agency' and then pass the user to agency controller
in user model i have this relation :
public function getAgency(){
return $this->hasOne(Agency::className(),['id'=>'agency_id'])
->viaTable(self::MAP_TABLE,['user_id'=>'id']);
}
and i have this accessRule components :
namespace common\components;
use common\models\User;
class AccessRule extends \yii\filters\AccessRule {
/**
* @inheritdoc
*/
protected function matchRole($user)
{
if (empty($this->roles)) {
return true;
}
foreach ($this->roles as $role) {
if ($role == '?') {
if ($user->getIsGuest()) {
return true;
}
}
elseif (!$user->getIsGuest()) {
$userObj = User::findOne(['id'=>$user->getId()]);
if ($role == User::AGENCY_USER) {
if ( $userObj->agency_perm >= User::AGENCY_USER) {
return true;
}
// Check if the user is logged in, and the roles match
} elseif ($role == User::AGENCY_MODERATOR) {
if ( $userObj->agency_perm >= User::AGENCY_MODERATOR) {
return true;
}
// Check if the user is logged in, and the roles match
} elseif ($role == User::AGENCY_ADMIN) {
if ($userObj->agency_perm >= User::AGENCY_ADMIN) {
return true;
}
// Check if the user is logged in, and the roles match
} elseif ($role == User::SUPER_USER) {
if ($userObj->super_user == User::SUPER_USER) {
return true;
}
// Check if the user is logged in, and the roles match
} elseif (!$user->getIsGuest() && $role == $user->identity->role) {
return true;
}
}
}
return false;
}
}
and use this in my controllers :
'access' => [
'class' => AccessControl::className(),
// We will override the default rule config with the new AccessRule class
'ruleConfig' => [
'class' => AccessRule::className(),
],
'rules' => [
[
'allow' => true,
'roles' => [
User::SUPER_USER,
],
],
],
],
In Yii access control, you can check user access by these approaches:
construct()
methodYou can check your custom access in this level, then choose to grant access or redirect him to another page.
In third way, you can access to your controller/action
name, then decide what happens.