CakePHP3での認証
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
検索
|
最終更新
|
ヘルプ
]
開始行:
[[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', // 認証条件の追加 Us...
'fields' => [
'username' => 'email', // 認証に使用...
'password' => 'password'// 認証に使...
]
]
]);
$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->redi...
}
$this->Flash->error(__('Invalid username or ...
}
}
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;
}
終了行:
[[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', // 認証条件の追加 Us...
'fields' => [
'username' => 'email', // 認証に使用...
'password' => 'password'// 認証に使...
]
]
]);
$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->redi...
}
$this->Flash->error(__('Invalid username or ...
}
}
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;
}
ページ名: