如何在CakePHP 2中仅编辑自己的数据?

时间:2012-04-10 06:34:12

标签: php cakephp

如何使注册用户只能编辑他们的数据而不能编辑其他人。当它设置ACL(aro和aco)时。 我的设置:

类用户扩展AppModel {

public function bindNode($user) {

    return array('model' => 'Group', 'foreign_key' => $user['User']['group_id']);

}

class AppController扩展Controller {

public $components = array(
    'Acl',
    'Auth' => array(
        'authorize' => array(
            'Actions' => array('actionPath' => 'controllers')
        )
    ),
    'Session'
);

1 个答案:

答案 0 :(得分:1)

您应该将isAuthorized方法添加到控制器中。在此方法中,您将检查用户是否有权使用他们尝试对其传递的参数执行的操作。你可以使用这样的代码:

switch ($this->action) {
    case 'delete':
    case 'edit':
        // id of what they are trying to edit
        $this->Topic->id = $this->params['pass'][0];
        // id of the owner of what they are trying to edit
        $ownerId = $this->Topic->field('user_id');

        $userId = $this->Auth->user('id');
        if ($ownerId == $userId) {
            // allow users to edit or delete their own topics
            return TRUE;
        } else {
            // allow admin group to edit any topic
            return $this->Auth->user('group') == 'admin';
        }
}

如果您想使用Cake的ACL系统来检查权限而不是像“用户是管理员组成员”这样的硬编码检查,请参阅此处的教程:http://jonisalonen.com/2010/role-based-acl-in-cakephp/ 它是为Cake 1.3编写的,我还没有检查是否存在重大差异。