<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use App\Form\ForgotPasswordForm;
use App\Form\ResetPasswordForm;
use App\Repository\UserRepository;
use App\Entity\UserForgot;
use App\Service\FunctionService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
#[Route('/auth')]
class AuthController extends AbstractController
{
use TargetPathTrait;
#[Route('/', name: 'auth_login')]
public function login(Request $request, AuthenticationUtils $helper): Response
{
$this->saveTargetPath($request->getSession(), 'main', $this->generateUrl('dashboard_index'));
$error = $helper->getLastAuthenticationError();
if($this->getUser()){
if (in_array('ROLE_ADMIN', $this->getUser()->getRoles(), true)
&& $this->getUser()->getIsActive() == 1) {
return $this->redirectToRoute('dashboard_index');
}else{
$error = 'Something went wrong. Please try again later.';
}
}
return $this->render('auth/login.html.twig', [
'last_username' => $helper->getLastUsername(),
'error' => $error,
]);
}
/**
* This is the route the user can use to logout.
*
* But, this will never be executed. Symfony will intercept this first
* and handle the logout automatically. See logout in config/packages/security.yaml
*/
#[Route('/logout', name: 'auth_logout')]
public function logout(): Response
{
// throw new \Exception('This should never be reached!');
return $this->redirectToRoute('auth', [], Response::HTTP_SEE_OTHER);
//return new RedirectResponse($this->urlGenerator->generate('app_homepage'))
}
/* #[Route('/forgot-password', name: 'auth_forgot_password' , methods: ['GET','POST']) ]
public function forgotPassword(Request $request,UserRepository $usersRepository,FunctionService $functionService,EntityManagerInterface $entityManager, AuthenticationUtils $helper): Response
{
// if user is already logged in, don't display the login page again
if ($this->getUser() ) {
throw $this->createNotFoundException('Page not found');
}
$formSubmited = false;
// $userForgot = new UserForgot();
$form = $this->createForm(ForgotPasswordForm::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//echo 'hi';exit;
$email = $form->get('email')->getData();
if(!$usersRepository->loadUserByIdentifier($email)){
$form->get('email')->addError(new \Symfony\Component\Form\FormError('No record found'));
}else {
if ($this->isCsrfTokenValid('forgot-password', $request->request->get('_csrf_token'))) {
// echo 'hi';exit;
$userForgot = new \App\Entity\UserForgot();
$user = $usersRepository->loadUserByIdentifier($email);
// print_r($user);exit;
$resetToken = $functionService->getRandCode(120);
$userForgot->setUserId($user->getUserId());
$userForgot->setCode($resetToken);
$userForgot->setIsExpired(0);
$userForgot->setCreatedAt(new \DateTime());
$entityManager->persist($userForgot);
$entityManager->flush();
$formSubmited = true;
//return $this->render('auth/forgot-password-message.html.twig');
}
}
}
return $this->render('auth/forgot-password.html.twig', [
'form' => $form->createView(),
'formSubmitted' => $formSubmited,
'last_username' => $helper->getLastUsername(),
]);
} */
#[Route('/reset-password/{token}', name: 'auth_reset_password', methods: ['GET','POST'])]
public function resetPassword($token, Request $request,UserRepository $usersRepository,FunctionService $functionService,EntityManagerInterface $entityManager, UserPasswordHasherInterface $passwordHasher): Response
{
// if user is already logged in, don't display the login page again
/* $user = $this->getUser();
if ($this->getUser() ) {
throw $this->createNotFoundException('Page not found');
} */
if ($this->getUser() ) {
throw $this->createNotFoundException('Page not found');
}
//echo 'hi'; exit;
//$token = $request->query->get('token');
//$em = $this->getDoctrine()->getManager();
/* $tokenRepo = $em->getRepository(\App\Entity\UserForgot::class);*/
$userRepo = $entityManager->getRepository(\App\Entity\User::class);
$user = null;
$userforgot=$entityManager->getRepository(\App\Entity\UserForgot::class)->findOneBy(array('code' => $token));
if(!$userforgot) {
return $this->redirect($this->generateUrl('auth_login'));
}
//$authToken = $tokenRepo->findOneBy(['code' => $token]);
if (is_object($userforgot)) {
$user = $userRepo->findOneBy(['userId' => $userforgot->getUserId(), 'isApproved' => true]);
}
if (!is_object($user)) {
throw $this->createNotFoundException('Page not found');
}
// print_r($user);exit;
$formSubmited = false;
//$form = $this->createForm(ResetPasswordForm::class);
$form = $this->createForm(ResetPasswordForm::class);
$form->handleRequest($request);
if ($request->getMethod() == 'POST'){
$data = $form->getData();
if(empty($data)){
$errors = 'Passwords do not match';
return $this->render('auth/reset-password.html.twig',
array('errors' => $errors,
'form' => $form->createView(),
'formSubmitted' => $formSubmited,
'token' => $token,
));
}else{
if ($form->isSubmitted() && $form->isValid()) {
$password = $form->get('password')->getData();
$password = $passwordHasher->hashPassword($user, $password);
$user->setPassword($password);
// save the user
$entityManager->persist($user);
$entityManager->remove($userforgot);
$entityManager->flush();
$formSubmited = true;
}
}
}
//print_r($form);exit;
return $this->render('auth/reset-password.html.twig', [
'form' => $form->createView(),
'formSubmitted' => $formSubmited,
'token' => $token,
'errors' => ''
]);
}
}