gpt4 book ai didi

authentication - Yii 基于角色的访问,管理自己的帖子

转载 作者:行者123 更新时间:2023-12-01 01:17:36 25 4
gpt4 key购买 nike

我在谷歌上搜索、阅读教程、博客并进行了很多实验。所以我能够定义基于角色的对 Controller 操作的访问。
一切正常。
我想问的是。如何编写规则来显示、编辑和删除用户自己的帖子?

默认情况下,它显示所有帖子。但是,我们可以将数据提供者标准放在显示自己的帖子中。但是我怎样才能控制 CRUD 呢?
请帮助我。我的代码如下。

 public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view'),
'users' => array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions' => array('create', 'update'),
'expression' => 'Yii::app()->controller->HaveAccess()',
//'users' => array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions' => array('admin', 'delete'),
'expression' => 'Yii::app()->controller->HaveAccess()',
),
array('deny', // deny all users
'users' => array('*'),
),
);
}

用于帖子展示:
 public function actionIndex() {
$dataProvider = new CActiveDataProvider('Advertisment');
if (!$this->IsAdmin()) {
$dataProvider = new CActiveDataProvider('Advertisment', array(
'criteria' => array(
'condition' => 'added_by='.$this->userId,
'order' => 'id DESC',
),
'pagination' => array(
'pageSize' => 20,
),
));
}
$this->render('index', array(
'dataProvider' => $dataProvider,
));
}

最佳答案

要将更新和删除操作限制为用户自己的帖子,您必须检查 Controller 操作内的权限(这在 Controller 的 accessRules afaik 中是不可能的,因为要检查权限的帖子的 id 不知道accessRules 被评估的时间。)

例子:

public function actionUpdate($id){
$model = $this->loadModel($id);
if($model->added_by === $this->userId){
// your code here
}else
throw new CHttpException(401,'You are not authorized to edit this post.');
}

关于authentication - Yii 基于角色的访问,管理自己的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11157553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com