Skip to content

Instantly share code, notes, and snippets.

@inoryy
Created December 30, 2011 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save inoryy/1540222 to your computer and use it in GitHub Desktop.
Save inoryy/1540222 to your computer and use it in GitHub Desktop.

Redirecting to last visited page after registration.

Imagine this scenario: A new user on your awesome webpage finds an awesome link, but it's only open to registered users, so he's automatically redirected to login form, then he goes to a register page (or fills embedded form right there) and then gets redirected back to a homepage. Somewhat frustrating experience, don't you think?

Well, let's solve this little problem with some help from [symfony2 authentication listener] (https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.php). More specifically, by exploiting [already existing feature] (https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.php#L270) for login form. This feature is actually a simple session parameter that is set the moment you're redirected to login page and purged the moment you login. Thus all you need to do is let symfony do its magic, redirect user to a login page from your private page and if he clicks on register (or fills in embedded form), have this snippet for redirecting URLs:

use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController;

class RegistrationController extends BaseController
{
    public function registerAction()
    {
        // Proccess form here ...
        
        if ($this->container->get('session')->has('_security.target_path')) {
            $url = $this->container->get('session')->get('_security.target_path');
            $this->container->get('session')->remove('_security.target_path');
        } else {
            $url = $this->container->get('router')->generate('knp_university_homepage');
        }

        return new RedirectResponse($url);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment