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' );
}
}
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.