因此,我創建了權限和角色,而不是註冊,每個用戶都獲得「用戶」角色。 當用戶嘗試更新他人發佈的帖子時,他不能這樣做。問題是他甚至不能更新他的帖子。無法弄清楚。Yii2 rbac用戶無法更新自己的帖子
public function up()
{
$auth = Yii::$app->authManager;
//creating post
$createPost = $auth->createPermission('createPost');
$createPost->description = 'Create Post';
$auth->add($createPost);
//deleting post
$deletePost = $auth->createPermission('deletePost');
$deletePost->description = 'Delete Post';
$auth->add($deletePost);
//update post
$updatePost = $auth->createPermission('updatePost');
$updatePost->description = 'Update Post';
$auth->add($updatePost);
//delete user
$deleteUser = $auth->createPermission('deleteUser');
$deleteUser->description = 'Delete User';
$auth->add($deleteUser);
//create role 'user' and add permissions
$user = $auth->createRole('user');
$user->description = 'User';
$auth->add($user);
$auth->addChild($user, $createPost);
$auth->addChild($user, $deletePost);
$auth->addChild($user, $updatePost);
//create role 'admin' and add permissions
$admin = $auth->createRole('admin');
$admin->description = 'Administrator';
$auth->add($admin);
$auth->addChild($admin, $user);
$auth->addChild($admin, $deleteUser);
}
public function down()
{
Yii::$app->authManager->removeAll();
}
AuthorAccessRule(當我更換控制器 「用戶」 與 「@」,這一切工作正確)(發現它計算器):
class AuthorAccessRule extends AccessRule
{
public $allow = true;
public $roles = ['@'];
public function allows($action, $user, $request)
{
$parentRules = parent::allows($action, $user, $request);
// $parentRes can be `null`, `false` or `true`.
// True means the parent rule matched and allows access.
if($parentRules != true)
{
return $parentRules;
}
return ($this->getProjectAuthorId($request) == $user->id);
}
private function getProjectAuthorId($request)
{
// Fill in code to receive the right project.
// assuming the project id is given à la `project/update?id=1
$postId = $request->get('id');
$post = Post::findOne($postId);
return isset($post) ? $post->user_id : null;
}
}
和控制器:
'access' => [
'class' => AccessControl::className(),
'only' => ['update', 'delete'],
'rules' => [
[
'allow' => true,
'actions' => ['delete', 'update'],
'roles' => ['user'],
'class' => 'app\filters\AuthorAccessRule'
],
[
'allow' => true,
'actions' => ['delete', 'update'],
'roles' => ['admin'],
],
您是否正確地將「用戶」角色分配給具體的用戶ID?嘗試調試你的函數getProjectAuthorId是否返回適當的ID .. –
它不能通過父:: allow方法。將嘗試弄清楚。 –