<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Controller;
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\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
/**
* Controller used to manage the application security.
* See https://symfony.com/doc/current/security/form_login_setup.html.
*
* @author Ryan Weaver <weaverryan@gmail.com>
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
class SecurityController extends AbstractController {
use TargetPathTrait;
private $security;
public function __construct(Security $security) {
$this->security = $security;
}
#[Route('/login', name: 'security_login')]
public function login(Request $request, AuthenticationUtils $helper, UserPasswordHasherInterface $passwordHasher, ManagerRegistry $entityManager): Response {
// if user is already logged in, don't display the login page again
if ($this->getUser()) {
// if ($this->security->isGranted('ROLE_ADMIN')) {
return $this->redirectToRoute('dashboard');
// }
}
$users = $entityManager->getRepository(User::class)->findAll();
// create the user and hash its password
// $user = new User();
// $user->setFullName("Visitor");
// $user->setUsername("user");
// $user->setEmail("visitor@evenews.com");
// $user->setRoles(['ROLE_USER']);
// $user->setEnabled('1');
//
// $hashedPassword = $passwordHasher->hashPassword($user, '123456');
// $user->setPassword($hashedPassword);
//
// $entityManager->persist($user);
// $entityManager->flush();
///end create the user
// this statement solves an edge-case: if you change the locale in the login
// page, after a successful login you are redirected to a page in the previous
// locale. This code regenerates the referrer URL whenever the login page is
// browsed, to ensure that its locale is always the current one.
$this->saveTargetPath($request->getSession(), 'main', $this->generateUrl('dashboard'));
return $this->render('security/login.html.twig', [
// last username entered by the user (if any)
'last_username' => $helper->getLastUsername(),
// last authentication error (if any)
'error' => $helper->getLastAuthenticationError(),
'users' => $users,
]);
}
/**
* 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: 'security_logout')]
public function logout(): void {
throw new \Exception('This should never be reached!');
}
#[Route('/pwForgotten', name: 'security_pw_forgotten')]
public function pwForgotten(Request $request): Response {
// if user is already logged in, don't display the login page again
return $this->render('security/pwForgotten.html.twig', [
]);
}
#[Route('/pwForgotten/send', name: 'security_pw_forgotten_send', methods: ['POST'])]
public function pwForgottenSend(Request $request, MailerInterface $mailer, UserRepository $users, EntityManagerInterface $entityManager): Response {
$user = $users->findOneByEmail($request->get('email'));
if ($user) {
$this->addFlash('success', 'An email to reset your password has been sent to your inbox : ' . $request->get('email'));
if ($user->getTokenreset() != null) {
$token = $user->getTokenreset();
} else {
$str = 'A=u_cs3Lmn' . $user->getId();
$token = str_shuffle($str);
// dump($user);die;
$user->setTokenreset($token);
$entityManager->persist($user);
$entityManager->flush();
}
$email = (new TemplatedEmail())
->from('no-reply@evenews.com')
->to($request->get('email'))
->subject('Evenews registration')
// path of the Twig template to render
->htmlTemplate('emails/pwForgotten.html.twig')
// pass variables (name => value) to the template
->context([
'token' => $token,
'user' => $user,
])
;
$mailer->send($email);
} else {
$this->addFlash('warning', 'No account with this email: ' . $request->get('email'));
}
return $this->redirectToRoute('security_pw_forgotten');
}
#[Route('/reset/tk-{token}/password', name: 'security_pw_reset')]
public function resetPassword(Request $request, $token, UserRepository $users): Response {
// if user is already logged in, don't display the login page again
$user = $users->findOneByTokenreset($token);
if ($user) {
} else {
$this->addFlash('warning', 'Request expired, please try again...');
return $this->redirectToRoute('security_pw_forgotten');
}
return $this->render('security/resetPw.html.twig', [
'user' => $user
]);
}
#[Route('/', name: 'security_pw_reset_send', methods: ['POST'])]
public function resetPasswordSend(Request $request, UserRepository $users, UserPasswordHasherInterface $passwordHasher, EntityManagerInterface $entityManager) {
$user = $users->findOneByTokenreset($request->get('_token'));
if ($user) {
$this->addFlash('success', 'Your password has been changed with success.');
$hashedPassword = $passwordHasher->hashPassword($user, $request->get('_password'));
$user->setPassword($hashedPassword);
$user->setTokenreset(null);
$entityManager->persist($user);
$entityManager->flush();
// $message = \Swift_Message::newInstance()
// ->setSubject('Evenews: New Password')
// ->setFrom(['contact@evenews.com' => 'Evenews'])
// ->setTo($user->getEmail())
// ->setBody(
// $this->renderView('emails/pwforgotten.html.twig', array('email' => $request->get('email'), 'token' => $token)
// ), 'text/html'
// );
// $this->get('mailer')->send($message);
} else {
$this->addFlash('warning', 'Request expired, please try again');
}
return $this->redirectToRoute('security_login');
}
#[Route('/email/verification', name: 'security_email_verification')]
public function emailVerification(Request $request, UserRepository $users, EntityManagerInterface $entityManager) {
$user = $this->getUser();
if ($user->getEmailVerification() != "1") {
$str = 'Au_5B3L_mxXbn' . $user->getId();
$token = str_shuffle($str);
$user->setEmailVerification($token);
$entityManager->persist($user);
$entityManager->flush();
// $message = \Swift_Message::newInstance()
// ->setSubject('Email confirmation')
// ->setFrom('contact@evenews.com')
// ->setTo($user->getEmail())
// ->setBody(
// $this->renderView('emails/accountCreated.html.twig', array('user' => $user, 'token' => $token)
// ), 'text/html'
// );
// $this->get('mailer')->send($message);
$this->addFlash('warning', 'An email has been sent to confirm your adress ' . $user->getEmail());
} else {
$this->addFlash('warning', 'Email already verified');
}
if ($this->security->isGranted('ROLE_USER')) {
return $this->redirectToRoute('dashboard');
} else {
return $this->redirectToRoute('security_login');
}
}
#[Route('/email/confirmation/tk/{token}', name: 'security_email_confirmation')]
public function emailConfirmation(Request $request, $token, UserRepository $users, EntityManagerInterface $entityManager) {
$user = $users->findOneByEmailVerification($token);
if ($user->getEmailVerification() != "1") {
$user->setEmailVerification('1');
$entityManager->persist($user);
$entityManager->flush();
// $message = \Swift_Message::newInstance()
// ->setSubject('Email confirmation')
// ->setFrom('contact@evenews.com')
// ->setTo($user->getEmail())
// ->setBody(
// $this->renderView('emails/accountCreated.html.twig', array('user' => $user, 'token' => $token)
// ), 'text/html'
// );
// $this->get('mailer')->send($message);
$this->addFlash('success', 'Email confirmed with success' . $user->getEmail());
} else {
$this->addFlash('info', 'Email already confirmed');
}
return $this->render('security/emailConfirmed.html.twig', [
'user' => $user
]);
}
}