- 追加された行はこの色です。
- 削除された行はこの色です。
[[CakePHP3めも]]
*UserController.php [#a9287d29]
usersテーブルに username と password の名前でフィールドを作っておけばそれらを使って認証してくれます。
public function initialize()
{
parent::initialize();
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Pages',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
]
]);
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->config('authenticate', [
'Form' => [
'userModel' => 'Users', // 認証に使用するテーブル
'finder' => 'auth' // 認証条件の追加 UsersTable.php の findAuth() へ
]
]);
$this->Auth->allow(['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'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
ログイン後のユーザーのデータは以下で取得できます。
$user = $this->Auth->user();
idだけを取得したい場合は以下のように指定します。
$id = $this->Auth->user('id');
*UsersTable.php [#s2c9cbe6]
username, password に加えて enabled が 1 であることを認証条件に加える場合は以下のように書きます。
public function findAuth(Query $query)
{
$query->where([
'Users.enabled' => 1
]);
return $query;
}