User.php
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
class User extends Entity{
protected $_accessible = [
'*' => true,
'id' => false
];
public function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
}
Userscontroller.php
<?php
namespace App\Controller;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['adicionar','salvar']);
}
public function adicionar()
{
$userTable = TableRegistry::get('Users');
$user = $userTable->newEntity();
$this->set('user', $user);
}
public function salvar()
{
$userTable = TableRegistry::get('Users');
$user = $userTable->newEntity($this->request->data());
if ($userTable->save($user)) {
$this->Flash->set('Usuário salvo com sucesso');
} else {
$this->Flash->set('Erro ao salvar o usuário');
}
//var_dump($userTable->save($user));exit;
$this->redirect('Users/adicionar');
}
public function login()
{
if ($this->request->is('post')){
$user = $this->Auth->identify();
if ($user){
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}else{
$this->Flash->set('Usuario ou senha invalidos',['element' =>'error']);
}
}
}
}
UsersTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class UsersTable extends Table {
}
Users/login.ctp
<h1>Acesso ao Sistema</h1>
<?php
echo $this->Form->create();
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('Acessar');
echo $this->Form->end();
?>
index.ctp
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Senha</th>
<th>Descrição</th>
</tr>
</thead>
<tbody>
<tr>
<td><?= $user['id']; ?></td>
<td><?= $user['username']; ?></td>
<td><?= $user['password']; ?></td>
<td><?= $user['descricao']; ?></td>
</tr>
</tbody>
</table>
<?php
echo $this->Html->Link('Novo Usuario', ['controller' => 'users', 'action' => 'adicionar']);
?>
adicionar.ctp
<h1>Cadastrar usuário</h1>
<?php
echo $this->Form->create($user,['url' =>['controller' => 'users', 'action' => 'salvar']]);
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->button('Cadastrar');
echo $this->Form->end();
?>