Blog Tutorial - Authentication and Authorization

I’m following this guide to log in Authentication and Authorization --> https://book.cakephp.org/3/en/tutorials-and-examples/blog-auth-example/auth.html

I copied the following files:

CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50),
    password VARCHAR(255),
    role VARCHAR(20),
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);

// src/Model/Table/UsersTable.php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class UsersTable extends Table
{
    public function validationDefault(Validator $validator)
    {
        return $validator
            ->notEmpty('username', 'A username is required')
            ->notEmpty('password', 'A password is required')
            ->notEmpty('role', 'A role is required')
            ->add('role', 'inList', [
                'rule' => ['inList', ['admin', 'author']],
                'message' => 'Please enter a valid role'
            ]);
    }

}

// src/Controller/UsersController.php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(‘add’);
}

public function index()
{
    $this->set('users', $this->Users->find('all'));
}

public function view($id)
{
    $user = $this->Users->get($id);
    $this->set(compact('user'));
}

public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is(‘post’)) {
// Prior to 3.4.0 $this->request->data() was used.
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success((‘The user has been saved.’));
return $this->redirect([‘action’ => ‘add’]);
}
$this->Flash->error(
(‘Unable to add the user.’));
}
$this->set(‘user’, $user);
}
}

<div class="users form">
<?= $this->Form->create($user) ?>
    <fieldset>
        <legend><?= __('Add User') ?></legend>
        <?= $this->Form->control('username') ?>
        <?= $this->Form->control('password') ?>
        <?= $this->Form->control('role', [
            'options' => ['admin' => 'Admin', 'author' => 'Author']
        ]) ?>
   </fieldset>
<?= $this->Form->button(__('Submit')); ?>
<?= $this->Form->end() ?>
</div>

it gives me an error: Call to a member function allow() on booleanError in: ROOT\src\Controller\UsersController.php, line 14

I’m not seeing the part where you show that you have loaded the Auth component.

1 Like

I was going crazy thanks a lot. Now works