<?php
namespace App\Controller\Admin;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\HttpFoundation\Request;
#[Route('/admin', name: 'hs_training_center_admin_')]
class SecurityAdminController extends AbstractController
{
#[Route("/login", name:"login")]
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser() && $this->getUser()->isPublished()) {
return $this->redirectToRoute('hs_training_center_dashboard');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('Admin/Security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
#[Route("/logout", name:"logout")]
public function logout(): never
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route('/change-password', name: 'change_password')]
public function changePassword(Request $request, UserRepository $userRepository, UserPasswordHasherInterface $passwordEncoder): Response
{
$user = $this->getUser();
$error = null;
if (!$user) {
return $this->redirectToRoute('hs_training_center_admin_login');
}
if ($request->isMethod('POST')) {
$currentPassword = $request->request->get('current_password');
$newPassword = $request->request->get('new_password');
if ($passwordEncoder->isPasswordValid($user, $currentPassword)) {
$encodedPassword = $passwordEncoder->hashPassword($user, $newPassword);
$user->setPassword($encodedPassword);
$userRepository->save($user, true);
// Redirection vers une page ou un message de succès
$this->addFlash('success', 'Votre mot de passe a bien été mis à jour.');
return $this->redirectToRoute('hs_training_center_dashboard');
} else {
$this->addFlash('warning', 'Le mot de passe actuel est incorrect.');
}
}
return $this->render('Admin/Security/change_password.html.twig');
}
}