Код: Выделить всё
/**
* @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(),
]);
}
Код: Выделить всё
/**
* @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
);
}
}
Код: Выделить всё
/**
* @Route("/home", name="app_home")
*/
function index(MessageGenerator $messageGenerator) {
if ( $this->getUser() && $this->isGranted('ROLE_ADMIN')) {
$message = $messageGenerator->getHappyMessage();
$htmlResponse = '';
$htmlResponse .= "
Lucky message: ".$message. '
';
$htmlResponse .= "
User id : {$this->getUser()->getId()}."
. '
';
$htmlResponse .= "
Is granted ROLE_USER : {$this->isGranted('ROLE_USER')}."
. '
';
$htmlResponse .= "
Is granted ROLE_ADMIN : {$this->isGranted('ROLE_ADMIN')}."
. '
';
$htmlResponse .= '';
return new Response(
$htmlResponse
);
}
else {
return new Response(var_export($this->get('session')->get('user_id'), true));
}
}
Все предложения приветствуются. Если есть что-то, что требует разъяснений, дайте мне знать.
Подробнее здесь: https://stackoverflow.com/questions/619 ... -symfony-5
Мобильная версия