LoginSignup
0
0

More than 3 years have passed since last update.

cakephpユーザー認証機能についてまとめてみた

Posted at

記事説明

自分なりにユーザー機能を実装してみての覚え書き

参考にした記事
http://blog.chatlune.jp/2018/03/02/cakephp-form-authenticate/
https://qiita.com/Natsukii/items/e2b7f265418fc8dce712

1、まずUsersテーブルを作成します。

とりあえず「username」と「password」カラムがあれば大丈夫!

2、Authコンポーネントの読み込むためのコードを書きます。【AuthComponent】

  • ログインやログアウト、ユーザ情報の提供などをしてくれる
  • AppController.phpのinitializeメソッドでその設定および処理が行われている
  • チュートリアルではUsersController.phpでログイン機能を追加した
AppController.php
public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler', [
        'enableBeforeRedirect' => false,
    ]);
    $this->loadComponent('Flash');

    $this->loadComponent('Auth', [
        //送信されたフォームデータのキーとログイン処理の「username」「password」を紐つける設定
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'username',
                    'password' => 'password'
                ]
            ]
        ],
        //ログイン処理を実行する場所設定
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
        //ログイン後のリダイレクト先設定
        'loginRedirect' => [
            'controller' => 'Users',
            'action' => 'index'
        ],
        //ログアウト後のリダイレクト先設定
        'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'index',
        // 未認証時、元のページを返します。
        'unauthorizedRedirect' => $this->referer()
    ]]);
}

3、UsersControllerログインログアウト機能実装

UsersControllerにlogin、logoutのアクションを作成します。

UsersController.php
public function login()
{
    if ($this->request->is('post')) {
        // identify()メソッドをもちいてリクエスト中の認証情報を使用してユーザーを識別する
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            //$this->request->session()->delete('Auth.redirect'); // 固定ページに移動させたい場合
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error('ユーザー名またはパスワードが不正です。');
    }
}

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

4、viewの作成

login.ctp
<div class="users form large-9 medium-8 columns content">
    <?= $this->Flash->render() ?>

    <?= $this->Form->create() ?>
    <fieldset>
        <legend>Login</legend>
        <?= $this->Form->control('username', ['required' => true]) ?>
        <?= $this->Form->control('password', ['required' => true]) ?>
    </fieldset>
    <?= $this->Form->button('ログイン') ?>
    <?= $this->Form->end() ?>

    <?= $this->Html->link("新規登録はこちら", ['action' => 'add']) ?>
</div>

完成

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0