m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

cakephp3でのauth認証2

alpha1での認証を再度用意

まあ、念のため

準備

とりあえず、改めて作成
mkdir alpha1
cd alpha1/
curl -s https://getcomposer.org/installer | php
php composer.phar create-project -s dev cakephp/app

※composerがうまくいかない場合は一部の

cd app
php ../composer.phar update
起動確認

f:id:m_shige1979:20140630224104p:plain

bakeでpostsを作成しておく
sh app/src/Console/cake bake model Posts
sh app/src/Console/cake bake controller Posts
sh app/src/Console/cake bake view Posts

※なんか適当な画面を別途用意しておく

ログイン

前提

syainsテーブルを新たに作成して

CREATE TABLE syains (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50),
    email VARCHAR(256),
    password VARCHAR(100),
    role VARCHAR(20),
    status INT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);
bake
sh app/src/Console/cake bake model Syains
sh app/src/Console/cake bake controller Users
sh app/src/Console/cake bake view Users
app/src/Controller/UsersController.php
<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Error\NotFoundException;
use Cake\Event\Event;

/**
 * Users Controller
 *
 * @property App\Model\Table\UsersTable $Users
 */
class UsersController extends AppController {

    public function beforeFilter(Event $event){
        // 上位クラスの機能を使用
        parent::beforeFilter($event);
        // ユーザーによるログアウトを許可する
        $this->Auth->allow('logout');

    }

/**
 * ログインアクション
 * @return \Cake\Network\Response|void
 */
    public function login() {
        if ($this->request->is('post')) {

            // 照合
            $user = $this->Auth->identify();
            if ($user) {
                // 認証成功
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());

            } else {
                // 認証失敗
                $this->Flash->error(
                    __('Username or password is incorrect'),
                    'default',
                    [],
                    'auth'
                );
            }
        }

    }

/**
 * ログアウトアクション
 * @return \Cake\Network\Response|void
 */
    public function logout() {
        return $this->redirect($this->Auth->logout());
    }

}

※ログイン、ログアウトのみにして未認証のアクセス許可を与える

app/src/Template/Users/login.ctp
<div class="users form">
<?php echo $this->Form->create('User'); ?>
    <fieldset>
        <legend><?php echo __('Please enter your username and password'); ?></legend>
        <?php echo $this->Form->input('email');
        echo $this->Form->input('password');
    ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')); ?>
<?php echo $this->Form->end(); ?>
</div>

※add.ctpなどは削除してもおk
※usernameではなく、emailとする

app/src/Controller/AppController.php
<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

/**
 * Components this controller uses.
 *
 * Component names should not include the `Component` suffix. Components
 * declared in subclasses will be merged with components declared here.
 *
 * @var array
 */
    public $components = [
        'Session',
        'Flash',
        'Auth' => [
            // ログイン後の画面
            'loginRedirect' => '/users',

            // ログアウト後の画面→ログインページへ遷移
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ],

            // 認証情報
            'authenticate' => [
                'Form' => [
                    // 使用モデル
                    'userModel' => 'Syains',
                    // フィールド
                    'fields' => [
                        'username' => 'email'
                    ],
                    // パスワード認証方法
                    'passwordHasher' => [
                        'className' => 'Default',
                    ]
                ]
            ]
        ]
    ];

    public function beforeFilter(Event $event) {
    }

}

※認証設定などを用意

パスワードを生成してデータを登録

shellを作成
sh app/src/Console/cake bake shell sample1
スクリプト編集
<?php
namespace App\Console\Command;

use Cake\Console\Shell;
use Cake\Auth\DefaultPasswordHasher;

/**
 * Sample1 shell command.
 */
class Sample1Shell extends Shell {

/**
 * main() method.
 *
 * @return bool|int Success or error code.
 */
        public function main() {

            $password = "password";
            echo "Text\n";
            echo $password . "\n";
            echo "\n";

            // デフォルトのパスワードハッシュ
            echo "DefaultPasswordHasher\n";
            $hasher = new DefaultPasswordHasher();
            echo $hasher->hash($password) . "\n";

        }
}
データ登録
insert into syains(
    username, 
    email, 
    password) 
values(
    'test1', 
    'test1@hoge.com', 
    '$2y$10$qpmNFTAxQT7VJvpEJ5qL2OllPBxF8dg2aK7x52Rckf5.fZF5.xn7y'
);

動作確認

f:id:m_shige1979:20140701001006p:plain
f:id:m_shige1979:20140701001016p:plain

まとめ

Authコンポーネントにloginメソッドがなくなっている。(;_;)
認証時に認証方法も指定できるよう。
基本、以前と多少は変わったけど多分大丈夫なはず…