<?php
namespace App\Controller;
use App\Form\PasswordUpdateType;
use App\Model\UserManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="app_login")
*
* @param AuthenticationUtils $authenticationUtils
*
* @return Response
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('home');
}
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'error' => $error,
'last_username' => $lastUsername,
]);
}
/**
* @Route("/user/change-password", name="user_change_password")
*
* @IsGranted("ROLE_CHANGE_PASSWORD")
*
* @param Request $request
* @param UserPasswordEncoderInterface $encoder
* @param UserManager $manager
*
* @return Response
*/
public function changePassword(Request $request, UserPasswordEncoderInterface $encoder, UserManager $manager)
{
$user = $this->getUser();
$form = $this->createForm(PasswordUpdateType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$oldPassword = $form->get('oldPassword')->getData();
$newPassword = $form->get('plainPassword')->getData();
if ($encoder->isPasswordValid($user, $oldPassword) === false) {
$this->addFlash('error', 'Your old password is not correct.');
return $this->redirectToRoute('user_change_password');
}
if ($oldPassword === $newPassword) {
$this->addFlash('error', 'Your new password cannot be the same as your old password.');
return $this->redirectToRoute('user_change_password');
}
$manager->updatePassword($user, $encoder->encodePassword($user, $newPassword));
$this->addFlash('success', 'Password updated successfully');
return $this->redirectToRoute('user_change_password');
}
return $this->render('security/change_password.html.twig', [
'form' => $form->createView(),
'policies' => $this->getParameter('app.password.policies')
]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
return $this->redirectToRoute('app_login');
}
}