考虑作为两个单独的问题来解决
访问控制
第一个是如何拒绝学生,例如,只是操纵 url 来尝试查看/编辑/删除他们不拥有的东西。对于这种使用isAuthorized,书中有一个示例,适用于问题中的信息:
// 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;
}
限制学生数据
自 2.1 起可用的事件系统是实施上述数据限制的简单方法。书中再次有一个相关示例,适用于问题中的信息,即:
// 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
所有查找添加一个条件,因此索引列表将仅显示他们自己的作业,而对于教师,它将显示所有作业。