How to limit data to users who own it without limiting admin users in CakePHP?

后端 未结 3 972
太阳男子
太阳男子 2020-12-18 09:17

Currently I am writing an application where I have multiple users. They have data that should only be visible to them and not the other authenticated users in the system. I

3条回答
  •  忘掉有多难
    2020-12-18 09:36

    For any one else who comes here this is how I set it up.

    First I set up a basic Role based ACL

    Then I deny access to reports/all for normal users

    $config['rules']['deny'][reports/all'] = 'Role/default' ;
    

    Then in the model that I wanted to protect I added this:

    public function beforeFind($queryData){
        //TODO:make this cleaner
        App::uses('ComponentCollection', 'Controller');
        App::uses('AclComponent', 'Controller/Component');
        $collection = new ComponentCollection();
        $this->Acl = new AclComponent($collection);     
    
        if(!$this->Acl->check(array('User'=>AuthComponent::user()),'/reports/all/')){  // must be a user (not admin)
            $this->bindModel(array('hasOne' => array('ReportsUser')));
            $queryData['conditions']['ReportsUser.user_id'] = AuthComponent::user('id');
            $queryData['recursive'] = 2;
        }
        return $queryData;
    }
    

    On the cases where ACL doesn't allow access to reports/all we add a condition to any find queries so it only shows reports with the correct user_id.

提交回复
热议问题