CakePHP 2.x ACL - 所有者级别的控制

CakePHP 2.x ACL - Control at owner level

我能够使用 ACL 控制我的应用程序,一切都完美地完成并且应用程序在 ACLAuth.

下运行顺畅

现在的问题是:

我有两个表,usersposts。没有 RBAC(基于角色的访问控制)。 我正在为每个喜欢关注的用户设置 denyallow

//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');

但是我遇到了一个问题:

user2 正在访问 edit user1posts

示例:

User1 创建了 post1.

现在 User2 已登录,现在他可以编辑 User1 的 post(即 post1- /localhost/myApp/posts/edit/1

问题:这个问题如何设置ACL权限,post的所有者只能编辑post,其他人不能。

我可以在控制器级别实现这一点,只需检查

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
}

但是我需要ACL在这里工作,可以吗?请帮忙

谢谢

这是我的做法

首先告诉 Cake Post 模型是 ACO

 // Post.php model file
 $actsAs = array('Acl' => array('type' => 'controlled'));

这样每次创建新的post蛋糕都会自动在acostable中创建一个项目。

注意:您必须为之前创建的 Post 手动创建节点,这样:

// for every Post in your posts table

$this->Acl->Aco->create(array('alias' => 'Post', 'id' => 123));
$this->Acl->Aco->save();

那么你必须在你的 Post 模型文件中定义一个 parentNode() 函数

// Post.php model file
public function parentNode() {
    return null;
}

现在 ACL 身份验证处理程序仅在操作级别检查表单权限。换句话说,它只是检查您是否被允许访问该操作。然后它要求 isAuthorized() 函数在控制器级别进行其他检查。

所以首先你必须为每个节点设置权限

$this->Acl->allow($user, 'controllers/Posts/edit/123')

然后在你的控制器中你必须做

 // 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);
}

您还可以将 parentNode() 函数实现到 return 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));
}

这种方式不必为每个 post 设置权限,因为 cake 会检查用户是否有权访问 Post 的父节点(谁也是用户) .所以你只需要为每个用户设置权限

$this->Acl->allow($user, $user);

如果您采用此方法,请记得将用户也设置为 ACO

// User.php Model file

$actsAs = array('Acl' => array('type' => 'both'));

我没有测试上面的代码,所以我猜也有很多错别字和错误。如果我有时间我会在接下来的几天做一些测试并改进我的答案