我正在使用CakePHP 3.0,我正在尝试让Auth组件使用电子邮件/密码来代替用户名/密码。在2.x中,我认为控制器需要某种类型的代码,并且必须在数据库中存在用户名和电子邮件。无论如何,这是我的相关代码,我不太确定我在这里做错了什么。这是我用3.0写的第一个应用程序,所以我仍然从2.x过渡。谢谢!
/ * AppController.php * /
public $components = [
'Flash',
'Auth' => [
'loginRedirect' => [
'controller' => 'dashboard',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
],
'authorize' => ['controller'],
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email']
]
]
]
];
public function isAuthorized($user) {
// Admin can access every action
if (isset($user['group_id']) && $user['group_id'] == 1) {
return true;
}
// Default deny
return false;
}
public function beforeFilter(Event $event) {
$this->Auth->allow(['index', 'view']);
$this->Auth->config('authenticate', ['Form']);
}
/ * UsersController * /
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow(['add', 'logout']);
}
public function login() {
$this->layout = 'basic';
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 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' => 'add']);
}
$this->Flash->error(__('Unable to add the user.'));
}
$this->set('user', $user);
}
/* login.ctp */
<div class="login">
<h1>Rising Tide Team Login</h1>
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<?= $this->Form->input('username', ['label' => 'Username/Email']) ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end('authenticate') ?>
</div>
答案 0 :(得分:2)
我并没有真正得到你遇到的任何问题或错误,但我在你的代码中注意到了一些事情。
controller
的{{1}}大写,否则您将收到内部错误。'authorize' => ['controller'],
传递给'username'
,而应传递$this->Form->input
,因为您要通过电子邮件和密码对用户进行身份验证。