我确信这是一项微不足道的任务,但我在PHP和CakePHP方面的经验不足。
我有Events
,Users
和Groups
个表,我想在索引视图中向用户显示由他和他的小组成员创建的事件。
我正在尝试处理有关授权的教程中的一段代码,但它仍然无法正常工作。用户可以查看由他创建的事件,但不能查看由他所属的组创建的事件。
请帮助我。我已经花了好几个小时,我无法弄明白。
用户表:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(60) NOT NULL,
password VARCHAR(255) NOT NULL,
group_id INT NOT NULL REFERENCES groups(id)
);
活动表:
CREATE TABLE events (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100),
created DATETIME DEFAULT NOW(),
description VARCHAR(1000) NOT NULL,
ended DATETIME,
working_hours INT,
price DECIMAL,
user_id INT NOT NULL REFERENCES users(id),
status_id INT NOT NULL REFERENCES statuses(id),
employee_id INT REFERENCES REFERENCES employees(id)
);
isAuthorized
中的 AppController
功能:
public function isAuthorized($user)
{
// Admin can access every action
if ($user['group_id'] === 1) {
return true;
}
// Default deny
return false;
}
isAuthorized
中的 EventsController
功能:
public function isAuthorized($user)
{
$action = $this->request->params['action'];
// The index action is always allowed.
//Every user can add a new event
if (in_array($action, ['index','add','przekaz'])) {
return true;
}
// The owner of an event can edit and delete it
if (in_array($this->request->action, ['edit', 'view'])) {
$eventId = (int)$this->request->params['pass'][0];
//This block is a remnant of my attempt to create authorization by group
$event = $this->Events->get($eventId, [
'contain' => []
]);
$authorId = $event->user_id;
$author = $this->Users->get($authorId, [
'contain' => []
]);
$groupId = $author->group_id;
$loggedUserGroupId = $user['group_id'];
//end of remnant
if ($user['group_id'] === 1 || $this->Events->isOwnedBy($eventId, $user['id']) || $groupId === $loggedUserGroupId) {
return true;
}
}
return parent::isAuthorized($user);
}
isOwnedBy
中的 EventsTable
功能:
public function isOwnedBy($eventId, $userId)
{
return $this->exists(['id' => $eventId, 'user_id' => $userId]);
}
答案 0 :(得分:1)
似乎我误解了isAuthorized
究竟是做什么的。我应该在isAuthorized
方法中编辑一行,而不是查看index
方法。我对自己缺乏知识感到羞耻。
解决方案:
public function index()
{
if($this->Auth->user('group_id') != 1) {
$this->paginate = [
'conditions' => [
'Users.group_id' => $this->Auth->user('group_id') // this line was changed
],
'contain' => ['Employees', 'Users', 'Statuses']
];
} else {
$this->paginate = [
'contain' => ['Employees', 'Users', 'Statuses']
];
}