所以,我创建了权限和角色,而不是在注册时每个用户获得"用户"角色。当用户尝试更新其他人的帖子时,他不能,这没关系。问题是他甚至无法更新他的帖子。想不通。(当我在控制器中将"用户"替换为"@"时,所有这些都可以正常工作(
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(在stackoverflow上找到它(:
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' => 'appfiltersAuthorAccessRule'
],
[
'allow' => true,
'actions' => ['delete', 'update'],
'roles' => ['admin'],
],
尝试调试在哪种条件下父::允许不通过。 Yo可以通过以下方式做到这一点:
public function allows($action, $user, $request)
{
$a = $this->matchAction($action);
$b = $this->matchRole($user);
$c = $this->matchIP($request->getUserIP());
$d = $this->matchVerb($request->getMethod());
$e = $this->matchController($action->controller);
$f = $this->matchCustom($action);
$g = $this->allow;
throw new Exception("$a, $b, $c, $d, $e, $f, $g");
$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);
}
签入女巫案例在异常消息中为 0?