(sorry for my bad english)
Iḿ using Cake 4.0 with Authentication Plugin.
I want the users to get redirected to the page they had visited before visiting to login form.
I made me a working solution with modifiying the headers of the login-request.
login form:
<h3>Login</h3>
<?= $this->Form->create()?>
<fieldset>
<legend><?= __('Please enter your username and password') ?></legend>
<?= $this->Form->control('email', ['required' => true]) ?>
<?= $this->Form->control('password', ['required' => true]) ?>
<?= $this->Form->hidden('origin', ['value' => $this->request->referer()]) ?>
</fieldset>
<?= $this->Form->submit(__('Login')); ?>
<?= $this->Form->end() ?>
<?= $this->Html->link(__("Register as New User"), ['action' => 'register']) ?>
<?= $this->Html->link(__("Password reset"), ['action' => 'recall']) ?>
my users controller (only login method), users controller also uses use Cake\Routing\Router;
and use Cake\Http\Response;
public function login()
{
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
// regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
//from where did the user come to the login form
$origin=$this->request->getData('origin');
//define where to redirect, if $origin is not valid
$redirect = $this->request->getQuery('redirect', [
'controller' => 'Recipes',
'action' => 'index',
]);
$origin=substr($origin,1);
$origin = Router::url('/',true).$origin;
$this->response = $this->response->withLocation($origin);
//debug($this->redirect($redirect));
//die();
return $this->redirect($redirect);
}
// display error if user submitted and authentication failed
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->error(__('Invalid username or password'));
}
}
Iḿ sure there is a better solution in a more CakePHP way, but i did not find it.
Can someone maybe tell me a better way ?
Greetings
Dirk