<?php
namespace App\Controller\Business;
use App\Entity\PackageOrder;
use App\Entity\User;
use App\Form\ChangePasswordFormType;
use App\Form\ForgottenFormType;
use App\Form\RegistrationFormType;
use App\Repository\PackageRecipeRepository;
use App\Repository\UserRepository;
use App\Security\LoginFormAuthenticator;
use App\Services\Mailer\PingyMailer;
use App\Services\Package\PackageOrderFactory;
use Exception;
use JMS\Serializer\Tests\Fixtures\Order;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use function array_diff;
class RegistrationController extends AbstractController
{
/**
* @Route("/verify/{id}/{hash}", name="app_registration_verify")
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function verify(Request $request,
UserRepository $userRepository,
UserProviderInterface $userProvider,
GuardAuthenticatorHandler $guardHandler,
LoginFormAuthenticator $authenticator,
PingyMailer $pingyMailer,
TokenStorageInterface $tokenStorage,
$id,
$hash)
{
$user = $userRepository->findOneBy([
'validationhash' => $hash,
'id' => (int)$id,
'approved' => User::WAITING_FOR_APPROVING
]);
if(!$user){
return $this->redirectToRoute('shoppingmall_index', []);
}
// Do not get the User's Id or Email Address from the Request object
try {
$userHash = $user->getValidationhash();
if ($userHash === $hash){
$user->setRoles(['ROLE_USER'])
->setApproved(User::IS_APPROVED);
$this->getDoctrine()->getManager()->flush();
$orders = $user->getPackageOrders();
/** @var PackageOrder $order */
foreach ($orders as $order) {
if ($order->getStatus() == PackageOrder::WAITING_FOR_CONFIRM_ACCOUNT) {
//return new RedirectResponse($this->generateUrl('packages_billing_info'));
$request->getSession()->set('_security.main.target_path', $this->generateUrl('packages_billing_info'));
}
}
return $guardHandler->authenticateUserAndHandleSuccess(
$user,
$request,
$authenticator,
'main' // firewall name in security.yaml
);
}else{
throw new Exception('Validation hash error');
}
} catch (\Exception $e) {
$this->addFlash('error', $e->getMessage());
return $this->redirectToRoute('app_register');
}
}
/**
* @Route("/register", name="app_register")
* @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
*/
public function register(
Request $request,
UserPasswordEncoderInterface $passwordEncoder,
GuardAuthenticatorHandler $guardHandler,
LoginFormAuthenticator $authenticator,
PingyMailer $pingyMailer): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
)
);
$hash = md5(rand(0, 10000) . rand(0, 10000));
$user->setValidationhash($hash);
// User is registered, but not allowed like common user
$user->setRoles(['ROLE_REGISTERED']);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$pingyMailer->registered($user->getEmail(), [
'userId' => $user->getId(),
'hash' => $user->getValidationhash()
]);
// do anything else you need here, like send an email
return $guardHandler->authenticateUserAndHandleSuccess(
$user,
$request,
$authenticator,
'main' // firewall name in security.yaml
);
}
return $this->render('admin/registration/register.html.twig', [
'registrationForm' => $form->createView(),
'errors' => $form->getErrors(true),
'error' => false
]);
}
/**
* @Route("/createXYZ", name="app_register_xyz")
* @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
*/
public function registerxyz(
Request $request,
UserPasswordEncoderInterface $passwordEncoder,
GuardAuthenticatorHandler $guardHandler,
LoginFormAuthenticator $authenticator,
PackageOrderFactory $packageOrderFactory,
PackageRecipeRepository $packageRecipeRepository,
UserRepository $userRepository,
PingyMailer $pingyMailer): Response
{
// $user = new User();
// $password = "H4#!?f_34";
// $email = 'lara_mkdad@deichmann.com';
//
// $user->setEmail($email);
//// $form = $this->createForm(RegistrationFormType::class, $user);
//// $form->handleRequest($request);
//
// //if ($form->isSubmitted() && $form->isValid()) {
// // encode the plain password
// $user->setPassword(
// $passwordEncoder->encodePassword(
// $user,
// $password
// )
// );
//
// $hash = md5(rand(0, 10000) . rand(0, 10000));
// $user->setValidationhash($hash);
// // User is registered, but not allowed like common user
// $user->setRoles(['ROLE_USER']);
// $user->setAgree(true);
// $user->setApproved(User::IS_APPROVED);
//
// $entityManager = $this->getDoctrine()->getManager();
// $entityManager->persist($user);
// $entityManager->flush();
$user = $userRepository->findOneBy(['id' => 101]);
$recipeCodes = [
'FreePackage',
'GermanyPackage',
'CzechiaPackage',
'AustriaPackage',
'SlovakiaPackage',
'SwitzerlandPackage',
'OutletsPackage',
'PolandPackage',
'DenmarkPackage',
];
$recipes = $packageRecipeRepository->findBy(['class_name' => $recipeCodes]);
$recipeIds = [];
foreach($recipes as $oneRec){
$recipeIds[] = $oneRec->getId();
}
$packageOrder = $packageOrderFactory->createByPackageIds($recipeIds, null);
$packageOrder->setOrderNumber(time().rand(0, 9999));
$packageOrder->setStatus(PackageOrder::PAID);
$user->addPackageOrder($packageOrder);
$this->getDoctrine()->getManager()->flush();
//$pingyMailer->confirmedOrder($user->getEmail());
// $pingyMailer->registered($user->getEmail(), [
// 'userId' => $user->getId(),
// 'hash' => $user->getValidationhash()
// ]);
// echo $password."<br />";
// echo $email;
exit('');
// do anything else you need here, like send an email
// return $guardHandler->authenticateUserAndHandleSuccess(
// $user,
// $request,
// $authenticator,
// 'main' // firewall name in security.yaml
// );
// //}
//
// return $this->render('admin/registration/register.html.twig', [
// 'registrationForm' => $form->createView(),
// 'errors' => $form->getErrors(true),
// 'error' => false
// ]);
}
/**
* @Route("/change-password", name="app_change_password")
*/
public function changePassword(Request $request, UserPasswordEncoderInterface $passwordEncoder, GuardAuthenticatorHandler $guardHandler, LoginFormAuthenticator $authenticator): Response
{
$form = $this->createForm(ChangePasswordFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $this->getUser();
if(!$user)
return $this->redirectToRoute('app_login');
// encode the plain password
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
)
);
// User is registered, but not allowed like common user
$currRoles = $user->getRoles();
$newRoles = array_diff($currRoles, ['ROLE_RESET_PASSWORD']);
$user->setRoles($newRoles);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
// do anything else you need here, like send an email
return $this->redirectToRoute('app_logout');
}
return $this->render('admin/security/changePassword.html.twig', [
'changePasswordForm' => $form->createView(),
'errors' => $form->getErrors(true),
'error' => false
]);
}
/**
* @Route("/forgotten-password", name="app_forgotten_password")
* @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
*/
public function forgottenPassword(Request $request, PingyMailer $pingyMailer, UserPasswordEncoderInterface $passwordEncoder): Response
{
$form = $this->createForm(ForgottenFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy([
'email' => $data['email']
]);
if(!$user)
throw new Exception('User has not been found');
$randomPassword = substr(sha1(random_bytes(10)), 0, 8);
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$randomPassword
)
);
$roles = $user->getRoles();
$roles[] = 'ROLE_RESET_PASSWORD';
$user->setRoles($roles);
$em = $this->getDoctrine()->getManager();
$em->flush();
// encode the plain password
try {
$pingyMailer->forgottenPassword($user->getEmail(), ['password' => $randomPassword]);
}catch (Exception $e){
}
$this->addFlash('INFO', 'Your password has been reset. Check your email address.');
return $this->redirectToRoute('app_login');
}
return $this->render('admin/security/forgotten.html.twig', [
'forgottenForm' => $form->createView(),
'errors' => $form->getErrors(true),
'error' => false
]);
}
/**
* @Route("/registered", name="app_registered")
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function registered(Request $request, SessionInterface $session, PackageOrderFactory $packageOrderFactory, PingyMailer $pingyMailer){
$roles = $this->getUser()->getRoles();
if(in_array('ROLE_USER', $roles)){
return $this->redirectToRoute('shoppingmall_index');
}
$recipeIds = $session->get(PackagesController::ORDERED_PACKAGES, []);
if(count($recipeIds) > 0){
// bylo objednano balicky - udelam objednavku do statusu waiting - nasledne bude prevedeno po potvrzeni uctu
$recipeIds = $session->get(PackagesController::ORDERED_PACKAGES, []);
$packageOrder = $packageOrderFactory->createByPackageIds($recipeIds);
$packageOrder->setOrderNumber(time().rand(0, 9999));
$packageOrder->setStatus(PackageOrder::WAITING_FOR_CONFIRM_ACCOUNT);
$this->getUser()->addPackageOrder($packageOrder);
$this->getDoctrine()->getManager()->flush();
$session->set(PackagesController::ORDERED_PACKAGES, []);
// $pingyMailer->confirmedOrder($this->getUser()->getEmail());
}
return $this->render('admin/registration/registered.html.twig');
}
}