PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 1, 2022

[FIXED] How to Check if user is logged in cakephp 4 application using CakeDC users plugin?

 November 01, 2022     cakedc, cakephp-4.x     No comments   

Issue

How to Check if user is logged in cakephp 4 application using CakeDC users plugin ? I need to change the theme when the user is logged in

In Application.php

public function bootstrap(): void
{
    $this->addPlugin('BootstrapUI');

    // Call parent to load bootstrap from files.
    parent::bootstrap();
    $this->addPlugin('CakeDC/Users', ['routes' => true, 'bootstrap' => true]);
    //$this->addPlugin(\CakeDC\Users\Plugin::class);
    Configure::write('Users.config', ['users']);
}

In AppController.php

public function beforeFilter(EventInterface  $event)
    {
        parent::beforeFilter($event);
           $user = $this->Authentication->identify();
        if ($user) {    
              $this->viewBuilder()->setlayout( 'CakeLte.default' );

        }
}

This error enter image description here


Solution

Assuming you have correctly configured the authentication component in your app, you can check if an user is connected like below :

if($this->Authentication->getIdentity()) {
  // user logged
} else {
  // user not logged
}

Just in case, this is some useful code sample for you.

In your controller :

$this->Authentication->getIdentity();
// Access to a field
$this->Authentication->getIdentity()->username;
// Access to a method of the entity
$this->Authentication->getIdentity()->isAdmin();

In your view :

$this->request->getAttribute('identity')
// Access to a field
$this->request->getAttribute('identity')->username;
// Access to a method of the entity
$this->request->getAttribute('identity')->getOriginalData()->isAdmin();

I admit this is pretty hard to find it, the documentation looks like abandonned about some features.



Answered By - Arthur .B
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing