Create Users Table:
CREATE TABLE IF NOT EXISTS `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(50) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `role` varchar(20) DEFAULT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
In Terminal, Cake bake the MVC
bin/cake bake model users && bin/cake bake controller users && bin/cake bake template users && bin/cake bake controller --prefix admin users && bin/cake bake template --prefix admin users
Load Auth component in App Controller Initialize method:
public function initialize() { $this->loadComponent('Flash'); $this->loadComponent('Auth', [ 'loginRedirect' => [ 'controller' => 'Users', 'action' => 'index', 'prefix' => 'admin' ], 'logoutRedirect' => [ 'controller' => 'Pages', 'action' => 'display', 'home' ] ]); }
Set up password hashing to encrypt the password by going to Model->Entity->User.php
Add the PasswordHasher library after the namespace
use Cake\Auth\DefaultPasswordHasher;
Add the password hasher method:
protected function _setPassword($password) { return (new DefaultPasswordHasher)->hash($password); }
Add BeforeFilter, Login and Logout method to App Controller
public function beforeFilter(Event $event) { parent::beforeFilter($event); // Allow users to register and logout. // You should not add the "login" action to allow list. Doing so would // cause problems with normal functioning of AuthComponent. $this->Auth->allow(['logout']); } public function login() { if ($this->request->is('post')) { $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); return $this->redirect($this->Auth->redirectUrl()); } $this->Flash->error(__('Invalid username or password, try again')); } } public function logout() { return $this->redirect($this->Auth->logout()); }
Create the file login.ctp in Template->Users
<section id="content"> <div class="row"> <div class="large-6 large-centered columns text-center"> <?= $this->Flash->render('auth') ?> <?= $this->Form->create() ?> <fieldset> <legend><?= __('Please enter your username and password') ?></legend> <?= $this->Form->input('username') ?> <?= $this->Form->input('password') ?> </fieldset> <?= $this->Form->button(__('Login')); ?> <?= $this->Form->end() ?> </div> </div> </section>
Temporarily allow the add method to function without being logged in by addinf the following in Controller->UsersController.php
public function beforeFilter(Event $event) { parent::beforeFilter($event); $this->Auth->allow('add'); }
Visit myappurl.com/users/add which should show an add user form, fill this in with your details.
Now that we have created a user, remove public access to the add user url in Controller->UsersController.php, remove the line “$this->Auth->allow(‘add’);”.