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


How to edit only their own data in CakePHP 2?

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

类 用户扩展 AppModel {

public function bindNode($user) {
    return array('model' => 'Group', 'foreign_key' => $user['User']['group_id']);
}

类应用控制器扩展控制器 {

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

应将 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 编写的,但我还没有检查是否有重大差异。