CakePHP3 認証機能拡張Plugin 承認メール、パスワードリマインダ

CakePHP3 認証機能拡張Pluginを作成したのでメモ

よく要件に出る認証関係の機能をPluginにまとめました。

GitHub - Junkins/StandardAuth

機能1 承認メール

サービスのアカウント登録をした際に、登録したメールアドレスに承認メールを送信し、 承認リンクを踏んでもらって初めてアカウントを有効化する機能

機能2 パスワードリマインダ

パスワードを忘れてしまった場合に、該当のメールアドレスを入力し、リセットされたランダムパスワードを送信する機能

Setup

事前の準備はStandardAuthComponentと、StandardAuthBehaviorを対象のコントローラーとTableにセットするだけ。

<?php
namespace App\Controller

use Cake\Controller\Controller;

/**
 * AdminAppController
 */
class AdminAppController extends Controller
{
  /**
   * initialize
   */
  public function initialize()
  {
      parent::initialize();
      $this->loadComponent('StandardAuth.StandardAuth', [
        'authenticate' => [
            'Form' => [
                'userModel' => 'Admins',
                'fields' => [
                    'username' => 'username',
                    'password' => 'password'
                ],
            ]
        ],
      ]);
  }
}
<?php
namespace App\Model\Table;

use Cake\ORM\Table;

/**
 * AdminsTable
 */
class AdminsTable extends Table
{
  /**
   * initialize
   */
  public function initialize(array $config)
  {
      $this->addBehavior('StandardAuth.StandardAuth');
  }
}

使い方

<?php

    /**
     * approval
     */
    public function approval($id, $hash)
    {
        $this->Admins->get($id);
        $result = $this->StandardAuth->approval($id, $hash);
        if ($result) {
            $this->Flash->success(__('The user has been saved.'));
        } else {
            $this->Flash->error(__('Invalid credentials, try again'));
        }
        return $this->redirect(['action' => 'login']);
    }

    /**
    * reset
    * @author ito
    */
    public function reset()
    {
        $this->viewBuilder()->layout('login');
        $this->StandardAuth->resetPassword();
    }
}