LoginSignup
1
4

More than 3 years have passed since last update.

CakePHP覚え書き

Last updated at Posted at 2020-07-09

何の記事?

CakePHPのチュートリアルをやっていて分からなくて検索した単語を羅列する
※調べる度に追記していく

【CakePHP公式チュートリアル】
https://book.cakephp.org/3/ja/tutorials-and-examples.html

覚え書き

Component

・コントローラから呼べる共通メソッド
・デフォルトでよく使うやつは用意されている
 ・認証(AuthComponent)
 ・クッキー(CookieComponent)
 ・クロスサイトリクエストフォージェリ(CsrfComponent)
 ・フラッシュ(FlashComponent)
 ・セキュリティ(SecurityComponent)
 ・ページネーション(PaginatorComponent)
 ・リクエストハンドリング(RequestHandlerComponent)
・オリジナルは「src/Controller/Component/」にファイルを作る必要がある
・useで継承する必要がある
・使い方

#①
public $components = ['コンポーネント名'];

#②
$now = $this->Date->today();

#③
$this->loadComponent('コンポーネント名');

【参考】
https://www.sejuku.net/blog/30423

AuthComponent

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

【チュートリアルででてきたところ】
https://book.cakephp.org/3/ja/tutorials-and-examples/bookmarks/part-two.html

AppController.php
        $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'unauthorizedRedirect' => $this->referer() // 未認証時、元のページを返します。
        ]);

        // PagesController が動作し続けるように
        // display アクションを許可
        $this->Auth->allow(['display']);
UsersController.php
public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error('あなたのユーザー名またはパスワードが不正です。');
    }
}

AuthComponent::identify()

identify()メソッドをもちいてリクエスト中の認証情報を使用してユーザーを識別する

 $this->Auth->identify() 

setUser()メソッドをもちいてセッションにユーザー情報を保存する、すなわち、ユーザーをログインする

$this->Auth->setUser()

'authorize'=> 'Controller'

【チュートリアルででてくるところ】
https://book.cakephp.org/3/ja/tutorials-and-examples/bookmarks/part-two.html#id5

ブックマークのアクセスを制限するためになんかいろいろやっている

AppController.php
#initialize()メソッドに設定の追加
'authorize'=> 'Controller',//この行を追加

#isAuthorizedメソッドの追加
public function isAuthorized($user)
{
    return false;
}

BookmarkControllerにもisAuthorized()メソッドの追加

BookmarkController.php
public function isAuthorized($user)
{
    $action = $this->request->getParam('action');

    // add と index アクションは常に許可します。
    if (in_array($action, ['index', 'add', 'tags'])) {
        return true;
    }
    // その他のすべてのアクションは、id を必要とします。
    if (!$this->request->getParam('pass.0')) {
        return false;
    }

    // ブックマークが現在のユーザーに属するかどうかをチェック
    $id = $this->request->getParam('pass.0');
    $bookmark = $this->Bookmarks->get($id);
    if ($bookmark->user_id == $user['id']) {
        return true;
    }
    return parent::isAuthorized($user);
}

AppControllerではisAuthorized()が必ずfalseを返して
BookmarkControllerでは場合によってはtrueにしているよう

ここに書いてあった
https://book.cakephp.org/3/ja/controllers/components/authentication.html#controllerauthorize

isAuthorized()メソッドでtrueになった場合だけ該当ユーザーがリクエスト内で リソースにアクセスすることが許可される、みたい

【参考】
https://qiita.com/kazu56/items/a54596e963d9e2b71f2e
https://www.sejuku.net/blog/30688
https://book.cakephp.org/3/ja/controllers/components/authentication.html
https://book.cakephp.org/3/ja/controllers/components/authentication.html#controllerauthorize

AppController.php

・アプリケーションのすべてのコントローラーの親クラス
・アプリケーションのコントローラー全体で共有されるメソッドを入れるようにする

【参考】
https://book.cakephp.org/3/ja/controllers.html

1
4
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
1
4