UsersController.php
use Cake\Auth\DefaultPasswordHasher;
use Cake\Event\Event;
public function initialize(){
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
]
],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'logout',
],
'authError' => 'ログインしてください。',
]);
}
function login(){
if($this->request->isPost()){
$user = $this->Auth->identify();
if(!empty($user)){
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('ユーザ名かパスワードが間違っています。');
}
}
public function logout(){
$this->request->session()->destroy();
return $this->redirect($this->Auth->logout());
}
public function beforeFilter(Event $event){
parent::beforeFilter($event);
$this->Auth->allow(['login', 'index', 'add']);
}
public function isAuthorized($user = null){
if($user['role'] === 'admin'){
return true;
}
if($user['role'] === 'user'){
return false;
}
return false;
}
authorize, authenticate, loginRedirect, logoutRedirect, authError
$this->request->session()->destroy();
### login.ctpを作成
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend>アカウント名とパスワードを入力して下さい。</legend>
<?= $this->Form->input('username') ?>
<?= $this->Form->input('password') ?>
<fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
AuctionBaseController.phpを作成し、継承させる
なるほどー