1

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

  • Looks like you haven't loaded the [authentication component](https://book.cakephp.org/authentication/2/en/authentication-component.html)? And the function you'd want would be `getIdentity`, not `identify`. – Greg Schmidt Sep 20 '21 at 13:34

1 Answers1

2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Arthur .B
  • 51
  • 2
  • After studying more in depth, it is necessary to put in the controller; $authenticationConfig = Configure::read('Auth.AuthenticationComponent'); $this->loadComponent('Authentication.Authentication', $authenticationConfig); – Sanderson Queiroz Sep 21 '21 at 01:11