So, here is a quick description of what I have done and the problem I am facing: I made an access control feature using the beforeAction() in my controller to restrict access for certain user types; in this case "only ADMIN can delete" is the rule I am trying to enforce. Everything works okay except for actions that have URL parameters. See the code below:
My Controller Behavior
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'user' => 'staff',
'rules' => [
[
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
//'delete' => ['POST'],
],
],
];
}
This is the beforeAction - it checks the role of the logged in user against a list of restricted actions
public function beforeAction($action)
{
$role = Yii::$app->staff->identity->role;
$restrictedActions = ['delete', 'create'];
$allowedUserTypes = ['admin'];
if(in_array($action->id, $restrictedActions) && !in_array($role, $allowedUserTypes)){
return $this->redirect(['default/restricted']);
}
return parent::beforeAction($action);
}
The beforeAction restriction works for this:
public function actionCreate()
{
$model = new Expense();
$model->created_on = date('Y-m-d H:i:s');
$model->created_by = Yii::$app->staff->getId();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
But then doesnt work for this:
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
Any help will be much appreciated. Thanks.