我正在使用cakephp 3,我想在我的应用上创建登录系统。我按照auth的博客教程。当我创建新用户密码时,将其存储为纯文本,而不是哈希。我不知道做错了什么。检查我的代码
我创建表:
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
);
我也创建了UsersTable和实体用户
class UsersTable extends Table
{
/**
* Initialize method
*
* @param array $config
*/
public function initialize(array $config)
{
$this->table('users');
$this->primaryKey('id');
}
}
class User extends Entity
{
protected $_accessible = [
'username' => true,
'password' => true
];
protected function _setPassword($password) {
return (new DefaultPasswordHasher)->hash($password);
}
}
// App\Controller\AppController.php
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
在UsersController中添加:
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('add', 'logout');
}
// Login
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'));
}
}
// Add
public function add() {
$user = $this->Users->newEntity($this->request->data);
if ($this->request->is('post')) {
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add the user.'));
}
$this->set(compact('user'));
}