<?php
namespace App\Controller;
use App\Entity\User;
use App\Repository\ShopRepository;
use App\Repository\UserRepository;
use App\Security\EmailVerifier;
use App\Service\UserService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
/**
* @Route("/{_locale<%app.supported_locales%>}/")
*/
class SecurityController extends AbstractController
{
use ResetPasswordControllerTrait;
private $resetPasswordHelper;
private $entityManager;
private $translator;
private $mailer;
private $mailer_sender;
private EmailVerifier $emailVerifier;
public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, ParameterBagInterface $params, TranslatorInterface $translator, MailerInterface $mailer, EmailVerifier $emailVerifier)
{
$this->translator=$translator;
$this->mailer=$mailer;
$this->resetPasswordHelper = $resetPasswordHelper;
$this->emailVerifier = $emailVerifier;
//$this->entityManager = $entityManager;
$this->mailer_sender = $params->get('app.mailer_sender');
}
/**
* @Route("login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
{
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("activation", name="app_activation")
*/
public function activation(AuthenticationUtils $authenticationUtils, Request $request): Response
{
return $this->render('security/activation.html.twig');
}
/**
* @Route("logout", name="app_logout")
*/
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
/**
* @Route("login/activation", name="app_login_with_token")
*/
public function loginWithToken(
AuthenticationUtils $authenticationUtils,
ShopRepository $shopRepository,
UserRepository $userRepository,
UserPasswordHasherInterface $userPasswordHasher,
Request $request,
UserService $userService
): Response
{
if($token = $request->request->get('token') ) {
if($shop=$shopRepository->findOneByLoginHash($token)) {
//echo $shop->getName();
$email=$request->request->get('email');
if(!$user=$userRepository->findOneByEmail($email)) {
$random= time()."_".$rand = substr(uniqid('', true), -5);;
$temp_user=new User();
//$temp_user->setFirstname($shop->getName()."_".$random);
//$temp_user->setLastname($shop->getName()."_".$random);
$temp_user->setEmail($email);
$temp_user->setShop($shop);
$temp_user->addShop($shop);
$temp_user->setRoles(array('ROLE_USER'));
$temp_user->setPassword(
$userPasswordHasher->hashPassword(
$temp_user,
$random
)
);
$userRepository->add($temp_user);
//$this->processSendingPasswordResetEmail($temp_user);
$userService->authenticate($temp_user, $request);
$resetToken = $this->resetPasswordHelper->generateResetToken($temp_user);
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $temp_user,
(new TemplatedEmail())
->from(new Address('support@bak2.com', 'Bak2'))
->to($temp_user->getEmail())
->subject('Please Confirm your Email')
->htmlTemplate('registration/confirmation_email.html.twig')
->context([
'resetToken' => $resetToken,
])
);
return $this->redirectToRoute('app_stock_index');
}
else {
$this->addFlash('error', $this->translator->trans("Vous avez déja activé votre compte"));
return $this->redirectToRoute('app_login');
//user exists
}
}
else {
//unknown token
$this->addFlash('error', $this->translator->trans("Code d'activation inconnu"));
return $this->redirectToRoute('app_login');
}
}
else {
$this->addFlash('error', $this->translator->trans("Code d'activation inconnu"));
return $this->redirectToRoute('app_login');
// no token
//throw new CustomUserMessageAuthenticationException('Unknown token');
}
return $this->redirectToRoute('app_login');
}
/**
* @Route("login/{shopName}/{hash}", name="app_login_auto")
*/
public function autoLogin($shopName, $hash, ShopRepository $shopRepository, UserRepository $userRepository, UserPasswordHasherInterface $userPasswordHasher, Request $request, UserService $userService): Response
{
if($shop=$shopRepository->findOneByName($shopName)) {
if($shop->getLoginHash() && $shop->getLoginHash()==$hash) {
$random= time()."_".$rand = substr(uniqid('', true), -5);;
$temp_user=new User();
$temp_user->setFirstname($shop->getName()."_".$random);
$temp_user->setLastname($shop->getName()."_".$random);
$temp_user->setEmail($shop->getMachineName().".".$random."@bak2.com");
$temp_user->setShop($shop);
$temp_user->addShop($shop);
$temp_user->setRoles(array('ROLE_USER'));
$temp_user->setPassword(
$userPasswordHasher->hashPassword(
$temp_user,
$random
)
);
$userRepository->add($temp_user);
$userService->authenticate($temp_user, $request);
/*
$request->request->set('email',$temp_user->getEmail());
$request->request->set('password',$random);
$loginFormAuthenticator->authenticate(
$request
);
*/
//$loginService->login($temp_user, $request);
//Security::login();
}
}
//die();
return $this->redirectToRoute('app_stock_index');
}
private function processSendingPasswordResetEmail(User $user)
{
// Do not reveal whether a user account was found or not.
if (!$user) {
return $this->redirectToRoute('app_login');
}
try {
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
} catch (ResetPasswordExceptionInterface $e) {
// If you want to tell the user why a reset email was not sent, uncomment
// the lines below and change the redirect to 'app_forgot_password_request'.
// Caution: This may reveal if a user is registered or not.
//
$this->addFlash('reset_password_error', sprintf(
'%s - %s',
$this->translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
$this->translator->trans($e->getReason(), [], 'ResetPasswordBundle')
));
return $this->redirectToRoute('app_check_email');
}
$email = (new TemplatedEmail())
->from(new Address($this->mailer_sender, 'Bak2'))
->to($user->getEmail())
->subject('Account created, please change your password')
->htmlTemplate('reset_password/email.html.twig')
->context([
'resetToken' => $resetToken,
])
;
try {
$this->mailer->send($email);
} catch (TransportExceptionInterface $e) {
var_dump($e);
// some error prevented the email sending; display an
// error message or try to resend the message
}
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession($resetToken);
//return $this->redirectToRoute('app_check_email');
}
}