2016年3月3日木曜日

cakephp3 のデフォルト機能を利用して認証を行う
-- Perform authentication using cakephp3 default auth --

PHP Ver 5.6.27
CakePHP Ver 3.1.9


Cakephp3のAuth機能を利用して管理画面の認証を作ってみた。
意外と手こずったので書き留める。

made manage function using Auth of Cakephp3.
I was struggling. so write down this blog.


1. DBの設定 [DB setting]


・config/app.phpの編集 [app.php edit]
--------------------------------
'Datasources' => [
    'default' => [
        ~
        'username' => 'db_user',
        'password' => 'db_password',
        'database' => 'database_name',
        ~
--------------------------------

・src/Controller/xxxController.phpの編集 [xxxController.php edit]
--------------------------------
public function initialize()
    {
        parent::initialize();

        // auth config
        $this->loadComponent('Auth', [
                'authenticate' => [
                        'Form' => [ // 認証の種類 Form,Basic,Digestが使える。デフォルトはForm
                                'userModel' => 'xxx', // テーブル名
                                'fields' => [ // ユーザー名とパスワードに使うカラムの指定。省略した場合はusernameとpasswordになる
                                        'username' => 'xxxx',
                                        'password' => 'xxxx'],
                                'scope' => [ // その他の条件
                                        'del_flg' => 0
                                ]
                                ]
                        ],
                'loginRedirect' => [ // ログイン後に遷移するアクションを指定
                        'controller' => 'xxx',
                        'action' => 'index'
                ],
                'logoutRedirect' => [ // ログアウト後に遷移するアクションを指定
                        'controller' => 'xxx',
                        'action' => 'login'
                ],
                'loginAction' => [ // ログインしていない場合のアクションを指定
                        'controller' => 'xxx',
                        'action' => 'login'
                ],
                'storage' => 'Session',
                'authError' => 'Did you really think you are allowed to see that?',
                'unauthorizedRedirect' => $this->referer()
        ]);

        $this->Auth->sessionKey = 'Auth.Admin';
    }

    public function login($id = null)
    {
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);                 $this->Flash->success(__('Admin Login Success'), [
                        'key' => 'auth'
                        ]);
                return $this->redirect($this->Auth->redirectUrl());
            } else {
                $this->Flash->error(__('Username or password is incorrect'), [
                        'key' => 'auth'
                        ]);
            }
        }
    }

    public function logout()
    {
        $this->request->session()->destroy();
        $this->Flash->success(__('Admin Logout Success'));

        return $this->redirect($this->Auth->logout());
    }

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);

        //ログイン無しで表示されるAction
        $this->Auth->allow(['login', 'logout']);
    }
--------------------------------

・src/Template/xxx/login.ctpの作成 [create login.ctp file]
--------------------------------
< ?php
    echo $this->Form->create();
    echo $this->Flash->render('auth');
    echo $this->Form->input('textbox', [
            'label' => 'MailAddress',
            'id' => 'mailaddress',
            'name' => 'mailaddress'
    ]);
    echo $this->Form->input('password', [
            'label' => 'Password',
            'id' => 'password',
            'name' => 'password'
    ]);
    echo $this->Form->button('Login');
    echo $this->form->end();
? >
--------------------------------

※ Entityに_setPasswordというメソッドを作り、以下のように記述すれば
DBに登録する際に暗号化してくれます。

Create a method called _setPassword to Entity.
with encryption when insert to DB.
--------------------------------
use Cake\Auth\DefaultPasswordHasher;

    protected function _setPassword($value) {
        $hasher = new DefaultPasswordHasher();
        return $hasher->hash($value);
    }
--------------------------------

※2 パスワードの長さに気を付けないとLengthが足りなくてもerrorも吐かずに
登録され、ずっと認証されないことになります。
これではまった・・・orz

0 件のコメント:

コメントを投稿