CakePHP3でログイン認証を構築
細かいところは公式マニュアルをチェック
https://book.cakephp.org/3.0/ja/controllers/components/authentication.html
AppController.php – コントローラー全体の認証設定を行う
LoginController.php – ログインフォーム、ログイン処理など
TUsersController.php – ユーザー表示、登録、編集など
■認証設定(AppController.php)
initializeに認証処理を追記します。
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
# 認証
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Login',
'action' => 'index'
],
'loginRedirect' => [
'controller' => 'TUsers',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Login',
'action' => 'index'
],
'authenticate' => [
'Form' => [
'userModel' => 'TUsers',
'fields' => [
'username' => 'account',
'password' => 'password'
]
]
]
]);
}
loginAction – ログイン処理を行うコントローラーとアクションを指定
loginRedirect – ログイン後に移動するコントローラーとアクションを指定
logoutRedirect – ログアウト後に移動するコントローラーとアクションを指定
authenticate – 認証の詳細設定
Form:ユーザーID、パスワードを入力するフォームを作成して認証処理をさせるタイプ。他にはBasicやDigestがあります。
userModel:認証に使用するモデルを指定(デフォルトはUsers)
fields:認証に使用するカラムを指定(デフォルトはusernameとpassword)
■ログインフォーム(index.ctp)、認証処理(LoginController.php)
LoginController.php
public function initialize() {
// AppControllerのAuthを継承
parent::initialize();
}
// ログインフォームとログイン処理
public function index() {
$this->loadModel("TUsers");
$users = $this->TUsers->newEntity();
if($this->request->is('post')) {
$users = $this->TUsers->patchEntity($users, $this->request->data);
$user = $this->Auth->identify();
if($user) {
$this->Auth->setUser($user);
$this->redirect($this->Auth->redirectUrl());
} else {
echo "ログインエラーだよ";
}
}
}
index.ctp
<?= $this->Flash->render() ?>
<?= $this->Form->create('Users') ?>
User<?= $this->Form->text('account') ?>
Password<?= $this->Form->password('password') ?>
<?= $this->Form->button('login') ?>
<?= $this->Form->end() ?>
■ユーザーの表示、追加、編集など
コントローラーに継承用の一文を追記します。
これがないとログイン後でもログインフォームに飛ばされちゃいます。
TUsersController.php
public function initialize(){
// AppControllerのAuthを継承
parent::initialize();
}
ユーザ作成、編集時にパスワードをハッシュ化させる。
Model/Entity/TUser.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;// ハッシャー
class TUser extends Entity
{
protected function _setPassword($password){
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
}
こうやって書くと単純だけど結構苦戦しました。
AppControllerに書きましたけど、コントローラー単位でやる方法は分かりません(w
