cakephpcakephp-3.4role-base-authorization

cakePhp 3.4 Authorization


I'm trying to save the views to count. it only saves the record when an authenticated user access this page. save fails when an Unauthenticated user access to this function.

 use Cake\ORM\TableRegistry;
    use Cake\Event\Event;

      public function beforeFilter(Event $event)
            {
                    $this->Auth->allow(['view']);
            }
       public function view($photoId = null)
        {
            $photoViewsTable = TableRegistry::get('PhotoViews');
            $photoViews = $photoViewsTable->newEntity();
            $photoViews->ip_address = $_SERVER['REMOTE_ADDR'];
            $photoViews->photo_id = $photoId;
            $photoViews->user_id = ($this->request->session()->read('Auth.User.id')) ? $this->request->session()->read('Auth.User.id') : 0;
            $photoViews->ip_address = $_SERVER['REMOTE_ADDR'];
            $photoViewsTable->save($photoViews);
    }

Solution

  • I think it is because of the validation rule in your model PhotoViews. Check if you have validation of user_id exists in table users.

    Change 0 to null in this line

    $photoViews->user_id = ($this->request->session()->read('Auth.User.id')) ? $this->request->session()->read('Auth.User.id') : null;
    

    Be sure to check the validation of allowEmpty in your model and null in the database table.

    You can debug it by getting the validation error like this.

    if(!$photoViewsTable->save($photoViews)){
        debug($photoViewsTable->getErrors());
    }
    

    Check this with login and without login.

    Hope this will help.