Description
I am trying to check whether a user is logged ir not by using $this->zfcUserAuthentication()->hasIdentity()
which works fine.
Once I verify the user is not logged in, following this suggestion in Stack overflow http://stackoverflow.com/a/14033746, I have this piece of code:
if (!$this->zfcUserAuthentication()->hasIdentity()) {
// Build the redirect URL using the route to which we want
// the user returned.
$redirect = $this->url()->fromRoute('yourRoute', array(
'param' => 1234
));
// Set the redirect URL in the request so that ZfcUser can
// pick it up. This is the key.
$this->getRequest()->getQuery()->set('redirect', $redirect);
// Use ZfcUser's login action rather than its authentication
// action.
return $this->forward()->dispatch('zfcuser', array(
'action' => 'login'
));
}
That will allow you to access redirect url generated in the login form to be used in a hidden variable with name "redirect" and value like this /yourRoute/param/1234/
. Once form is submitted, and you are into the authenticateAction
method in UserController
, the value will be collected as string in the $redirect
variable. See the method :
public function authenticateAction()
{
if ($this->zfcUserAuthentication()->hasIdentity()) {
return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
}
$adapter = $this->zfcUserAuthentication()->getAuthAdapter();
$redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));
$result = $adapter->prepareForAuthentication($this->getRequest());
// Return early if an adapter returned a response
if ($result instanceof Response) {
return $result;
}
$auth = $this->zfcUserAuthentication()->getAuthService()->authenticate($adapter);
if (!$auth->isValid()) {
$this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
$adapter->resetAdapters();
return $this->redirect()->toUrl(
$this->url()->fromRoute(static::ROUTE_LOGIN) .
($redirect ? '?redirect='. rawurlencode($redirect) : '')
);
}
if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
return $this->redirect()->toUrl($redirect);
}
return $this->redirect()->toRoute($this->getOptions()->getLoginRedirectRoute());
}
Even though toRoute accepts params, options, etc. Those are not available at this point. $redirect is a string that is dynamically generated.
if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
return $this->redirect()->toRoute($redirect);
}
Is there any reason this code is using
return $this->redirect()->toRoute($redirect);
Instead of using toURL which works for a dynamic generated and get properly redirected?
return $this->redirect()->toURL($redirect);