php - how to check yii2 relation is exist show controller -
i have user , agency models
user have agency model , can access whit $user->agency
now want check in accessrule when relation is exist show controller if relation null show alert 'user->agency null pealse create agency' , pass user agency controller
in user model have relation :
public function getagency(){ return $this->hasone(agency::classname(),['id'=>'agency_id']) ->viatable(self::map_table,['user_id'=>'id']); }
and have 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 $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 user logged in, , roles match } elseif ($role == user::agency_moderator) { if ( $userobj->agency_perm >= user::agency_moderator) { return true; } // check if user logged in, , roles match } elseif ($role == user::agency_admin) { if ($userobj->agency_perm >= user::agency_admin) { return true; } // check if user logged in, , roles match } elseif ($role == user::super_user) { if ($userobj->super_user == user::super_user) { return true; } // check if user logged in, , roles match } elseif (!$user->getisguest() && $role == $user->identity->role) { return true; } } } return false; } }
and use in controllers :
'access' => [ 'class' => accesscontrol::classname(), // override default rule config new accessrule class 'ruleconfig' => [ 'class' => accessrule::classname(), ], 'rules' => [ [ 'allow' => true, 'roles' => [ user::super_user, ], ], ], ],
in yii access control, can check user access these approaches:
- check in each action (not recommended)
- controller
construct()
method - module/app middle-wares
you can check custom access in level, choose grant access or redirect him page.
in third way, can access controller/action
name, decide happens.
Comments
Post a Comment