CakePHP 3 - 关联表的所有权授权

时间:2017-04-06 11:23:38

标签: php mysql cakephp authorization cakephp-3.0

CakePHP 3 Blog Tutorial中,用户有条件授权使用以下代码根据所有权使用编辑和删除等操作:

public function isAuthorized($user)
{
    // All registered users can add articles
    if ($this->request->getParam('action') === 'add') {
        return true;
    }

    // The owner of an article can edit and delete it
    if (in_array($this->request->getParam('action'), ['edit', 'delete'])) {
        $articleId = (int)$this->request->getParam('pass.0');
        if ($this->Articles->isOwnedBy($articleId, $user['id'])) {
            return true;
        }
    }

    return parent::isAuthorized($user);
}

public function isOwnedBy($articleId, $userId)
{
    return $this->exists(['id' => $articleId, 'user_id' => $userId]);
}

我一直在尝试为自己的表实现类似的功能。例如,我有一个Payments表,它通过几个不同的表链接到Users,如下所示:

  • 用户 - >客户 - > Bookings->付款

每个外键:

    Customers表中的
  • user_id = Users->id(User hasOne Customer)
  • 预订表中的
  • customer_id = Customers->id(客户有多个预订)
  • 付款表中的
  • booking_id = Bookings->id(预订有多笔付款)

我的AppController的初始化函数:

public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Auth',[
            'authorize' => 'Controller',
        ]);

        $this->Auth->allow(['display']); //primarily for PagesController, all other actions across the various controllers deny access by default
    }

在我的PaymentsController中,我有以下

public function initialize()
    {
        parent::initialize(); 
    }

public function isAuthorized($user)
    {        
        if (in_array($this->request->action,['view', 'edit', 'index', 'add']
            return (bool)($user['role_id'] === 1); //admin functions
        }

        if (in_array($this->request->action,['cart'])) {
            return (bool)($user['role_id'] === 2) //customer function
        }

        if (in_array($this->request->action, ['cart'])) {
            $bookingId = (int)$this->request->getParam('pass.0');
            if ($this->Payments->isOwnedBy($bookingId, $user['id'])) {
                return true;
            }
        }

        return parent::isAuthorized($user);
    }

    public function isOwnedBy($bookingId, $userId)
    {
        return $this->exists(['id' => $bookingId, 'user_id' => $userId]);
    }

我不确定如何链接不同的表来确定所有权。

  • 目前,如果支付预订#123的客户可以更改网址,以便他们支付预订#111,前提是数据库中存在预订。
  • 此外,预订ID将传递给购物车功能(因为客户正在支付特定预订)。例如:如果客户支付预订#123,则URL = localhost / project / payments / cart / 123。提交购物车后,会创建一个新的付款条目。

此外,关于getParam和isOwnedBy方法,将鼠标悬停在我的编辑器中会显示:

  • Method 'getParam' not found in \Cake\Network\Request
  • Method 'isOwnedBy' not found in App\Model\Table\PaymentsTable

但是,我已经浏览了整个BlogTutorial,并且找不到在模型中使用或设置getParam或isOwnedBy的任何其他地方。

1 个答案:

答案 0 :(得分:0)

在PaymentsController中的IsAuthorized函数中:

{{1}}