我正在使用访问控制过滤器进行访问管理,但无法完成一件事 - 例如,我如何才能只允许项目经理更新项目并禁止其他人更新项目?我通过 matchCallback 尝试过,但在这种情况下,所有项目经理都可以更新任何项目,因为返回了 TRUE。
类似的更经常需要的规则 - 如何允许用户使用 ACF 更新/删除他作为作者的帖子?
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create', 'update', 'delete'],
'rules' => [
[
'actions' => ['update'],
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
return Yii::$app->user->identity->getProjectParticipants()
->one()->isManager(Yii::$app->user->identity->id);
}
],
],
],
最佳答案
可以这样实现:
use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
class MyController extends Controller
{
...
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['update', 'delete'],
'rules' => [
[
'actions' => ['update', 'delete'],
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {
if (Yii::$app->user->can('admin') || $this->isUserAuthor()) {
return true;
}
return false;
}
],
],
],
];
}
protected function findModel($id)
{
if (($model = MyModel::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
protected function isUserAuthor()
{
return $this->findModel(Yii::$app->request->get('id'))->author->id == Yii::$app->user->id;
}
...
}
关于php - 只允许作者使用 ACF 在 yii2 中编辑他的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29239735/