CakePHP4で、cakeDC/usersを使ってログイン機能を追加する

1 Mins read

今回は、最新のCakePHP4.0.8を使ってログイン機能を実装したいと思います。
まずは、インストール完了した画面です。データベースの設定も済ませています。

ここで、コンソールから以下のようにインストールします

$ composer require cakedc/users
$ composer require league/oauth2-google:@stable

src/Application.php のファイルのbootstrap()メソッドに追記します

//src/Application.php file
    /**
     * {@inheritdoc}
     */
    public function bootstrap()
    {
        parent::bootstrap();

        $this->addPlugin(\CakeDC\Users\Plugin::class);
        // Uncomment the line below to load your custom users.php config file
        //Configure::write('Users.config', ['users']);
    }

データベース接続が完了している前提で、ログイン情報を格納するテーブル作成をします。以下を行うことで3つのテーブルが作成されます

$ bin/cake migrations migrate -p CakeDC/Users

ここまで出来たらWEBページにアクセスしてみます。どのページにアクセスしてもリダイレクト処理が行われて、以下のように表示されたらOKです。

まだユーザーを作成していないので、ログインはできません。そこで管理者権限のユーザーを追加します

$ bin/cake users addSuperuser --email=example@example.com --password=examle

Superuser added:
Id: 12345678-1234-1234-1234-1234567890ab
Username: superadmin
Email: example@example.com
Role: superuser
Password: 123456789012345678901234567890ab

こちらのusername とパスワードでログインできることをまずは確認します。これで最低限のログイン機能は完成です。
なお、ログアウトは、http://example.com/logout となります