2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cakePHP4 Authenticationプラグイン ログイン認証と機能・表示切り分け

Posted at

Every Qiita #19
のんびり独学初学者の毎日投稿チャレンジ 19日目
今回は・・・
cakephpでログインユーザ認証の備忘録です。

###ログイン認証の実装
公式チュートリアルでログイン周りを実装します。

UsersController.php
   // ログイン認証不要アクションの設定
    public function beforeFilter(\Cake\Event\EventInterface $event)
    {
        parent::beforeFilter($event);
        $this->Authentication->addUnauthenticatedActions(['login','home', 'add','logout']);
    }
    public function login()
    {
        $this->request->allowMethod(['get', 'post']);
        $result = $this->Authentication->getResult();
        if($result->isValid()){
            $redirect = $this->request->getQuery('redirect',[
                'controller' => 'Users',
                'action' => 'index',
            ]);
            return $this->redirect($redirect);
        }
        if($this->request->is('post') && !$result->isValid()){
            $this->Flash->error(__('メールアドレスかパスワードが違います'));
        }
    }

    public function logout()
    {
        $result = $this->Authentication->getResult();
        if($result->isValid()){
            $this->Authentication->logout();
            return $this->redirect(['controller' => 'Users', 'action' => 'home']);
        }
        return $this->redirect(['controller' => 'Users', 'action' => 'home']);
    }

コントローラーはAuthenticationを継承しますので、ログイン不要アクションはbeforefilterに追加します。
$this->Authentication->getResult();こちらでログイン認証を確認します。

###ログインしているか確認
$this->Authentication->getResult()->getData();
上記でログインユーザか認証してますので、こちらを条件分岐で使用。

 $result = $this->Authentication->getResult();
    if($result->isValid()){
        $current_user = true;
    }else{
        $current_user = false;
    }
  $this->set(compact('current_user'));

$current_userのboolでログイン・非ログイン用でヘッダーの表示を変えていきます。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?