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\Component\Request\Request;
class RegistrationController extends Controller
{
public function registerAction(Request $request)
{
$form = $this->createForm(new SomeRegistrationForm());
$form->bindRequest($request);
if ($form->isValid()) {
// do something awesome, like saving the User created by your registration form
$user = $form->getData();
// authenticate your user right now
$this->authenticateUser($user);
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);
}
// .. re-render the form on error
}
}