I need to redirect the user after successful registration to their own subdomain (test for this example).
/**
* @Route("/signup", name="app_signup", host="admin.mysymfony.local")
*/
public function signup(
Request $request,
UserPasswordEncoderInterface $passwordEncoder,
LoginFormAuthenticator $authenticator,
GuardAuthenticatorHandler $guardAuthenticatorHandler
): Response
{
$user = new User();
$form = $this->createForm(SignupType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
$user->setPassword($passwordEncoder->encodePassword($user, $user->getPassword()));
$roles = $user->getRoles();
$roles[] = 'ROLE_ADMIN';
$user->setRoles($roles);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->get('session')->set('user_id', $user->getId());
return $guardAuthenticatorHandler->authenticateUserAndHandleSuccess(
$user,
$request,
$authenticator,
'main'
);
}
return $this->render('security/signup.html.twig', [
'form' => $form->createView(),
]);
}
This works fine and the user is redirected to this method after successful authentication:
/**
* @Route("/signup/complete", name="app_signup_complete", host="admin.mysymfony.local")
*/
public function signupComplete(
Request $request,
UserPasswordEncoderInterface $passwordEncoder,
LoginFormAuthenticator $authenticator,
GuardAuthenticatorHandler $guardAuthenticatorHandler
): Response
{
if ($this->getUser() && $this->isGranted('ROLE_ADMIN') ) {
error_log('User authenticated');// this is logged successfully
}
if ( strpos($request->getHost(), 'admin.') == 0 ) {
$host = str_replace('admin.', 'test.', $request->getHost());
$homeUrl = $this->generateUrl('app_home');
$testHomeUrl = $request->getScheme() . '://' . $host. $homeUrl;
return $this->redirect(
$testHomeUrl
);
}
}
This is the method that is called after redirection to the user subdomain:
/**
* @Route("/home", name="app_home")
*/
function index(MessageGenerator $messageGenerator) {
if ( $this->getUser() && $this->isGranted('ROLE_ADMIN')) {
$message = $messageGenerator->getHappyMessage();
$htmlResponse = '<html><body>';
$htmlResponse .= "<p>Lucky message: ".$message. '</p>';
$htmlResponse .= "<p>User id : {$this->getUser()->getId()}."
. '</p>';
$htmlResponse .= "<p>Is granted ROLE_USER : {$this->isGranted('ROLE_USER')}."
. '</p>';
$htmlResponse .= "<p>Is granted ROLE_ADMIN : {$this->isGranted('ROLE_ADMIN')}."
. '</p>';
$htmlResponse .= '</body></html>';
return new Response(
$htmlResponse
);
}
else {
return new Response(var_export($this->get('session')->get('user_id'), true));
}
}
As expected it falls in the else section and the value of user_id passed to the session is not recognized because it is a different subdomain. All suggestions are welcome and please if there is something that needs clarification let me know.