php - cakephp 中的记录级别访问

标签 php cakephp permissions

我想根据登录查看记录的用户来限制记录。

例如我有以下两个模型:

Assignments
Users

因此,如果学生(用户)正在查看作业摘要,他应该只能看到他的作业,并且只能执行查看/删除/编辑他的作业。

但是,如果教师(用户)正在查看作业摘要,那么他应该看到所有作业,并且可以对所有作业执行添加/编辑/删除操作。

我已经知道我可以通过将组条件放入查找中,然后在查看/编辑/删除操作中适本地添加代码来做到这一点。

我的问题是 - 在 cakephp 中处理此类场景的最佳方法是什么?对我来说,到处设置条件似乎不是好方法。

最佳答案

考虑两个单独的问题来解决

访问控制

第一个是如何拒绝学生,例如只需操纵 url 来尝试查看/编辑/删除他们不拥有的内容。对于 isAuthorized 的使用,有 an example in the book ,根据问题中的信息进行调整:

// app/Controller/AppController.php

public $components = array(
    'Session',
    'Auth' => array(
        'authorize' => array('Controller') // Added this line
    )
);

public function isAuthorized($user) {
    // Teachers can access/do everything - adapt to whatever identifies a teacher
    if ($user['is_teacher'])) {
        return true;
    }

    // Anyone logged in can access the index
    if ($this->action === 'index') { 
        return true;
    } 

    // The owner of a whatever can view, edit and delete it
    $id = $this->request->params['pass'][0];
    $owner = $this->{$this->modelClass}->field('user_id', array('id' => $id));
    if ($owner === $user['id'])) {
        return true;
    }

    // Default deny
    return false;
}

限制学生数据

The event system自 2.1 起可用,是强制执行上述数据限制的简单方法。再次there's a relevant example in the book ,根据问题中的信息进行调整,即:

// app/Controller/AssignmentsController.php

public function beforeFilter() {
    if (!$this->Auth->user('is_teacher')) {
        $currentUser = $this->Auth->user('id');
        $this->Assignment->getEventManager()->attach(
            function(CakeEvent $e) use ($currentUser) {
                $e->data[0]['conditions']['user_id'] = $currentUser;
                return $e->data[0];
            },
            'Model.beforeFind'
        );
    }
}

这将为所有查找结果添加一个 user_id 条件,因此索引列表将仅显示他们自己的作业,而对于教师来说,它将显示所有作业。

关于php - cakephp 中的记录级别访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17830305/

相关文章:

cakephp - 默认情况下,所有类型的用户/角色都可以访问 CakeDC 管理员,确保其安全

linux - Docker:从 Win10 安装到运行 ubuntu 的容器的目录中不允许进行 git 操作

android - 使用 Gluon 移动环境时如何在运行时请求权限?

php - 在 yii2 中创建扩展线程的自定义类

php - 我的 friend 系统为每个用户更改 session

php - 更新脚本中所需的 ID 未存储(甚至未看到!?)

php - 将 CakePHP FormHelper 与 Bootstrap 表单一起使用

php - CakePHP/MySQL : find with a condition for model itself and an assigned model

android - 检测到屏幕覆盖会阻止 Android 权限

php - 删除删除线的 unicode 文本?