我能够控制我的应用程序使用ACL,一切都完美完成,应用程序正在ACL和Auth.
现在的问题是:
我有两张桌子,users和posts.没有RBAC(基于角色的访问控制).我正在为每个用户设置deny,allow如下所示.
//allow User1 to do everything
$user->id=1;
$this->ACL->allow($user,'controllers');
//allow User2 to add, edit and view the posts
$user->id=2;
$this->Acl->deny($user, 'controllers');
$this->Acl->allow($user, 'controllers/Posts');
Run Code Online (Sandbox Code Playgroud)
但在这里我遇到了一个问题:
user2是获得访问edit该posts的user1.
例:
User1创造了一个post1.
现在User2登录,他可以编辑User1帖子(即post1- /localhost/myApp/posts/edit/1)
问题:如何为此问题设置ACL权限,帖子的所有者只能编辑帖子而其他人不能.
我可以在控制器级别中简单地检查
if($_SESSION['Auth']['User']['id'] == $Post['Post']['user_id']){
// you're the owner, so u can edit
}else{
//u cant edit, this is not ur post
}
Run Code Online (Sandbox Code Playgroud)
但我需要ACL在这里工作,有可能吗?,请帮助
谢谢
这是我会怎么做
首先,请告诉Cake Post模型是ACO
// Post.php model file
$actsAs = array('Acl' => array('type' => 'controlled'));
Run Code Online (Sandbox Code Playgroud)
这样,每次创建新的发布蛋糕时,都会在acos表中自动创建一个项目。
注意:您必须通过以下方式为先前创建的帖子手动创建节点:
// for every Post in your posts table
$this->Acl->Aco->create(array('alias' => 'Post', 'id' => 123));
$this->Acl->Aco->save();
Run Code Online (Sandbox Code Playgroud)
那么您必须parentNode()在Post Model文件中定义一个函数
// Post.php model file
public function parentNode() {
return null;
}
Run Code Online (Sandbox Code Playgroud)
现在,ACL身份处理程序仅在操作级别检查表单权限。换句话说,它只是检查您是否被允许访问该操作。然后,需要通过该isAuthorized()功能在控制器级别进行其他检查。
所以首先您必须为每个节点设置权限
$this->Acl->allow($user, 'controllers/Posts/edit/123')
Run Code Online (Sandbox Code Playgroud)
然后在您的控制器中,您必须做
// PostsController.php
public function isAuthorized($user = null) {
if ($this->request->action === 'edit') {
$user = // retrieve the user array. i.e. from Session
$post_id = $this->request->$this->request->pass[0];
$post = array('alias' => 'Post', 'id' => $post_id );
return this->Acl->check($user, $post);
}
return parent::isAuthorized($user);
}
Run Code Online (Sandbox Code Playgroud)
您还可以实现parentNode()函数以返回Post的所有者,而不是null
// Post.php model file
// just an hint, the actual code should be
// a bit more complex
public function parentNode() {
$user_id = $this->field('user_id');
return array('User' => array('id' => $user_id));
}
Run Code Online (Sandbox Code Playgroud)
这样,不必为每个帖子都设置权限,因为cake会检查用户是否有权访问帖子的父节点(也是用户)。因此,您只需要为每个用户设置权限
$this->Acl->allow($user, $user);
Run Code Online (Sandbox Code Playgroud)
如果您遵循此方法,请记住也将用户设置为ACO
// User.php Model file
$actsAs = array('Acl' => array('type' => 'both'));
Run Code Online (Sandbox Code Playgroud)
我没有测试上面的代码,所以我想也有很多错别字和错误。如果有时间,我会做一些测试,并在接下来的几天中改善答案