Question

I have a function in a controller, which needs to check whether the user is logged in (I'm using zfcuser module), and if not, show them the login screen.

It is my understanding that I should be running this:

return $this->forward()->dispatch('zfcuser', array('action' => 'authenticate'));

Unfortunately, this changes the url. I want to show the login screen and allow the user to login without the url changing. By extension this means I will also want to redirect the user back to the same page instead of going to the /user page.

How can I achieve both these things?

Was it helpful?

Solution

I struggled with this myself for the last couple of days. The ZfcUser configuration includes a use_redirect_parameter_if_present setting, but the documentation doesn't give any examples on how one might use this. I don't know if my method is solid, but here's what I did to get this working. Note that this method preserves the URL because it uses forward. I'm not sure of another way to do this without using forward.

In your zfcuser configuration file, go ahead and set that use_redirect_parameter_if_present setting to true. This causes ZfcUser's login action to look for a redirect parameter in the request. It uses this to return the user to the specified location after successful authentication.

Then, in the controller where I want to ensure the user is logged in, I have:

if (!$this->zfcUserAuthentication()->hasIdentity()) {

    // Build the redirect URL using the route to which we want
    // the user returned.
    $redirect = $this->url()->fromRoute('your route', array(
        'optional-route-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'
    ));
}

I hope that helps. If you have issues getting this working, you may need to post some code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top