如何仅显示属于当前登录用户组的记录?

时间:2016-06-27 09:59:03

标签: php cakephp authorization cakephp-3.0

我确信这是一项微不足道的任务,但我在PHP和CakePHP方面的经验不足。

我有EventsUsersGroups个表,我想在索引视图中向用户显示由他和他的小组成员创建的事件。

我正在尝试处理有关授权的教程中的一段代码,但它仍然无法正常工作。用户可以查看由他创建的事件,但不能查看由他所属的组创建的事件。

请帮助我。我已经花了好几个小时,我无法弄明白。

用户表

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]);
}

1 个答案:

答案 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']
      ];
  }