I am currently adding a CakePHP 3 Authentication component to and existing CakePHP application following the documentation listed here:
https://book.cakephp.org/3/en/controllers/components/authentication.html
I am currently handling the display of error messages, following this example:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Username or password is incorrect'));
}
}
}
I am integrating the auth components following the documentation here, where an array of user data is returned if a user is able to be authenticated and false if they are not (as specified in the docs):
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
use Cake\Http\ServerRequest;
use Cake\Http\Response;
class OpenidAuthenticate extends BaseAuthenticate
{
public function authenticate(ServerRequest $request, Response $response)
{
// Do things for OpenID here.
// Return an array of user if they could authenticate the user,
// return false if not.
if($failureCondition) {
return false;
}
return $user;
}
}
However I would like to dynamically determine the error in the auth component:
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
use Cake\Http\ServerRequest;
use Cake\Http\Response;
class OpenidAuthenticate extends BaseAuthenticate
{
public function authenticate(ServerRequest $request, Response $response)
{
if($failureConditionA) {
$this->error = 'Error A';
return false;
}
if($failureConditionB) {
$this->error = 'Error B';
return false;
}
return $user;
}
}
And print the dynamically produced error in the flash message like so:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
// 'Error A' or 'Error B' displayed on failure
$this->Flash->error($this->Auth->error());
}
}
}
What is the correct code to use to do this?
If this violates the intention behind how the AuthComponent is supposed to function, I would be interested to have that explained and / or know any other correct ways to do this?
Thanks in advance!