Created
July 16, 2018 08:25
-
-
Save epitre/56b60c870698fd2310888a3088639fe3 to your computer and use it in GitHub Desktop.
SF register + login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Controller; | |
use App\Entity\User; | |
use App\Form\RegisterType; | |
use Doctrine\ORM\EntityManagerInterface; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\HttpFoundation\Session\SessionInterface; | |
use Symfony\Component\Routing\Annotation\Route; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; | |
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; | |
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; | |
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; | |
/** | |
* Class RegisterController | |
* @package App\Controller | |
* | |
* @Route("/register", name="register_") | |
*/ | |
class RegisterController extends Controller | |
{ | |
/** | |
* @Route("/", name="connect") | |
*/ | |
public function connect( | |
Request $request, | |
EntityManagerInterface $entityManager, | |
UserPasswordEncoderInterface $passwordEncoder, | |
TokenStorageInterface $tokenStorage, | |
SessionInterface $session | |
) { | |
$user = new User(); | |
$form = $this->createForm(RegisterType::class, $user); | |
$form->handleRequest($request); | |
if ($form->isSubmitted() && $form->isValid()) { | |
$password = $passwordEncoder->encodePassword($user, $user->getPassword()); | |
$user->setPassword($password); | |
$entityManager->persist($user); | |
$entityManager->flush(); | |
// START | |
// On connecte l'utilisateur dans la foulée | |
$token = new UsernamePasswordToken( | |
$user, | |
$password, | |
'main', | |
$user->getRoles() | |
); | |
$tokenStorage->setToken($token); | |
$session->set('_security_login', serialize($token)); | |
// END | |
$this->addFlash('success', 'Bienvenue '.$user->getUsername()); | |
return $this->redirectToRoute('idea_list'); | |
} | |
return $this->render( | |
'register/connect.html.twig', | |
[ | |
'form' => $form->createView(), | |
] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment