bigmac-jp blog

web開発関連のメモ

centos7.2 + Apache2.4 + php7 + cakephp3 + mysql5.6 で管理画面を作ります。 その5

centos7.2 + Apache2.4 + php7 + cakephp3 + mysql5.6 で管理画面を作ります。 その5


シンプルな認証機能を作る。メモとして書きます。
基本的はcakephpのAuthComponentを使うとほとんどやることをないです。
公式ドキュメントを参考にします。
シンプルな認証と認可のアプリケーション - 3.6



まずはMysqlにusersのTabelを作成します。
usersテーブルのにはログイン時のusernameとパスワードを保持させます。

CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50),
    password VARCHAR(255),
    role VARCHAR(20),
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);

usersテーブルができたら、次はプログラムを作成します。
基本ベースはbakeコマンドでuserテーブルを指定して作成されたプログラムを修正していくイメージです。
bakeコマンドでとりあえずAllで全部ありで作ります。

bin/cake bake All Users
---------------------------------------------------------------
Baking table class for Users...

Bake All complete. 成功!!!!

次はAuthComponentを適用するためにsrc/Controller/AppController.phpに下記に修正します。
今回はログイン後のリダイレクト先コントローラーとアクションの指定と
ログアウト後のリダイレクト先の指定となります。
ログイン認証時に利用するカラム名がデフォルトのusernameとpasswordの場合は、記述の省略が可能です。ログインアカウント登録画面は認証が不要なので、beforeFilterで'add'を認証除外にしています。

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler', ['enableBeforeRedirect' => false]);
        $this->loadComponent('Flash');
        // AuthComponentようの設定
        $this->loadComponent('Auth', [
            'loginRedirect' => [
                'controller' => 'Index',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'login',
                'home'
            ]
        ]);
    }

    public function beforeFilter(Event $event)
   {
       $this->Auth->allow(['add']);
    }


次にアカウント登録処理を作成します。
先ほどのbakeコマンド実行でコンントローラーのaddアクション処理とテンンプレート(/Template/Users/add.ctp)、モデルのベースは作成済みです。ありがたいーーーーー。


パスワードの登録データは平文ではなく、ハッッシュ化されたものをUsersテーブルに登録するため、修正します。
_setPasswordで入力された平文パスワードをハッシュ化します。
/Model/Entity/User.php

//追加
use Cake\Auth\DefaultPasswordHasher;

class User extends Entity
{

 //追加
    protected function _setPassword($password)
    {
        if (strlen($password) > 0) {
            return (new DefaultPasswordHasher)->hash($password);
        }
    }
}

次はログイン画面を作ります。
bakeコマンドではログイン関連は作成されないため、Usersコントローラにloginアクションとlogoutアクションの追加とlogin.ctpテンンプレートを作成します。
/Controller/UsersController.php

   //追加
    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());
    }

/Template/Users/login.ctp

<!-- File: src/Template/Users/login.ctp -->

<div class="users form">
<?= $this->Flash->render() ?>
<?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Please enter your username and password') ?></legend>
        <?= $this->Form->control('username') ?>
        <?= $this->Form->control('password') ?>
    </fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>

/users/addにブラウザでアクセスするとアカウント追加画面が表示される。
usernameとパスワードと権限)(1)を入力して登録するとusersテーブルにデータが登録される。
login画面でusernameとパスワードを入力すればログインができる。