<?php
namespace App\Controller;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\BFUser;
use App\Entity\BFChallenge;
use App\Entity\BFChallengeEdition;
use App\Entity\BFFestival;
use App\Entity\BFEdition;
use App\Entity\BFPaymentIntentEdition;
use App\Entity\BFPaymentIntentAdmin;
use App\Entity\BFResetPassword;
use App\Entity\BFAdminLicences;
use App\Form\Type\BFUserType;
use App\Form\Type\ResetPassword1Type;
use App\Form\Type\ResetPassword2Type;
use App\Form\Type\BFPaymentIntentAdminType;
use App\Utilities\Secure;
use Symfony\Component\Form\FormError;
use App\Utilities\Mail;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Form\Type\BFAdminLicenceType;
use App\Form\Type\FindPaymentByStripeIdType;
use App\Object\Statistic;
use Stripe\Stripe;
use Stripe\StripeClient;
use Stripe\PaymentIntent;
use Stripe\PaymentMethod;
use Stripe\Event;
class SecurityController extends AbstractController
{
/**
* @Route("/security/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): 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("/security/logout", name="app_logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
/**
* @Route("/security/resetpassword" , name="app_resetpassword")
*/
public function ResetPassword(Request $request)
{
$formreset = $this->createForm(ResetPassword1Type::class);
$formreset->handleRequest($request);
if($formreset->isSubmitted() && $formreset->isValid()){
$email=$formreset->getData()['email'];
//get the user
$user=$this->getDoctrine()->getRepository(BFUser::class)->findOneBy(array('email'=>$email));
if($user==null)
{
$formreset->get('email')->addError(new FormError('Email inconnu'));
}
else
{
$this->ClearUserResetPassword($user);
$datetime = new \DateTime();
$datetime->add(new \DateInterval("P1D")); //add 1day
$bfresetpassword = new BFResetPassword();
$bfresetpassword->setUser($user);
$bfresetpassword->setToken($this->GetUniqueToken());
$bfresetpassword->setValiditydate($datetime);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($bfresetpassword);
$entityManager->flush($bfresetpassword);
//Send mail
$link = $this->generateUrl('app_resetpassword_token', ['token'=>$bfresetpassword->getToken()], UrlGeneratorInterface::ABSOLUTE_URL);
$txtmessage = "Pour reinitialier votre mot de passe rendez vous sur: ".$link;
$subject = "Reinitialiser le mot de passe";
$htmlmessage = $this->render('mail/resetpasswordmail.html.twig', [
'subject' => $subject,
'link' => $link,
]);
$return = Mail::SendMailToMail($email, $subject, $htmlmessage, $txtmessage);
if($return ==false)
{
$this->addFlash('danger', 'Erreur lors de l\'envoi du mail');
}
return $this->render('security/resetpasswordconfirmation.html.twig', [
'passwordchanged' => false,
]);
}
}
if($formreset->isSubmitted() && !$formreset->isValid())
{
foreach($formreset->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
return $this->render('security/resetpassword.html.twig', [
'formreset' => $formreset->createView(),
]);
}
/**
* @Route("/security/resetpassword/{token}", name="app_resetpassword_token")
*/
public function ResetPasswordWithToken($token, Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$bfresetpassword = $this->getDoctrine()->getRepository(BFResetPassword::class)->findOneBy(array('token'=>$token));
$entityManager = $this->getDoctrine()->getManager();
if($bfresetpassword->getValiditydate()< new \DateTime())
{
$entityManager->remove($bfresetpassword);
$entityManager->flush();
$bfresetpassword=null;
}
if($bfresetpassword==null)
{
return $this->redirectToRoute("app_resetpassword");
}
$formreset = $this->createForm(ResetPassword2Type::class);
$formreset->handleRequest($request);
if($formreset->isSubmitted() && $formreset->isValid()){
$email=$formreset->getData()['email'];
$user=$bfresetpassword->getUser();
//check email with bfresetpassworduser email
if($email != $bfresetpassword->getUser()->getEmail())
{
$formreset->get('email')->addError(new FormError('Email inconnu'));
}
else
{
$password = $passwordEncoder->encodePassword($user, $formreset->getData()['plainPassword']);
$user->setPassword($password);
// 4) save the User!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
//remove the resetpasswordrequest
$entityManager->remove($bfresetpassword);
$entityManager->flush();
return $this->render('security/resetpasswordconfirmation.html.twig', [
'passwordchanged' => true,
]);
}
}
if($formreset->isSubmitted() && !$formreset->isValid())
{
foreach($formreset->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
return $this->render('security/resetpassword.html.twig', [
'formreset' => $formreset->createView(),
]);
}
/**
* @Route ("/security/account/superadmin/setdefault", name="app_superadmin_setdefault")
*/
public function SetDefaultSuperAdmin(Request $request)
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
//Check if there is an role_super_admin in the database
$userrepository =$this->getDoctrine()->getRepository(BFUser::class);
$superadmins = $userrepository->findByRole('ROLE_SUPER_ADMIN');
if(count($superadmins)<=1)
{
//set the first user
$firstuser = $userrepository->findFirst();
$firstuser->setRoles(array('ROLE_SUPER_ADMIN'));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($firstuser);
$entityManager->flush();
$this->addFlash('primary', 'Super admin role add default');
}
return $this->redirectToRoute('home_route',[
'routename' => 'account',
]);
}
/**
* @Route ("/security/account/superadmin/add/{email}", name="app_superadmin_add")
*/
public function AddSuperAdmin($email, Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
//Check if there is an role_super_admin in the database
$user =$this->getDoctrine()->getRepository(BFUser::class)->findOneBy(['email'=>$email]);
if($user!=null)
{
//set the first user
$user->setRoles(array('ROLE_SUPER_ADMIN'));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('primary', 'Super admin role add');
}
return $this->redirectToRoute('home_route',[
'routename' => 'account',
]);
}
/**
* @Route ("/security/account/superadmin/remove/{email}", name="app_superadmin_remove")
*/
public function RemoveSuperAdmin($email, Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
//Check if there is an role_super_admin in the database
$user =$this->getDoctrine()->getRepository(BFUser::class)->findOneBy(['email'=>$email]);
if($user!=null)
{
//set the first user
$user->setRoles(array(''));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('primary', 'Super admin role remove');
}
return $this->redirectToRoute('home_route',[
'routename' => 'account',
]);
}
/**
* @Route ("/admin/superadmin", name="admin_superadmin_view")
*/
public function ShowSuperAdminView(Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
$user = $this->getUser();
$adminlicences=new BFAdminLicences();
//form add option or offer
$formaddoption=$this->createForm(BFAdminLicenceType::class, $adminlicences);
$formaddoption->handleRequest($request);
if($formaddoption->isSubmitted() && $formaddoption->isValid())
{
$adminlicences=$formaddoption->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($adminlicences);
$em->flush() ;
$this->addFlash('primary', 'L\'option a été ajoutée');
return $this->redirect($request->getUri());
}
if($formaddoption->isSubmitted() && !$formaddoption->isValid())
{
foreach($formaddoption->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
//form find payment by stripeid
$formfindpayment = $this->createForm(FindPaymentByStripeIdType::class);
$formfindpayment->handleRequest($request);
if($formfindpayment->isSubmitted() && $formfindpayment->isValid())
{
$stripeid=$formfindpayment['stripeid']->getData();
$paymentintent=$this->getDoctrine()->getRepository(BFPaymentIntentEdition::class)->findOneBy(['stripeid' => $stripeid]);
if($paymentintent!=null)
{
return $this->redirectToRoute('payment_admin_details',[
'idpayment' => $paymentintent->getId(),
]);
}
else
{
$this->addFlash('danger', 'None payment found');
return $this->redirect($request->getUri());
}
}
if($formaddoption->isSubmitted() && !$formaddoption->isValid())
{
foreach($formaddoption->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
//admin payments
$adminpayments = $this->getDoctrine()->getRepository(BFPaymentIntentAdmin::class)->findAll();
//admin licences list
$adminlicences = $this->getDoctrine()->getRepository(BFAdminLicences::class)->findAllValid();
//admin statistics
$statistics = array();
$userstat = new Statistic();
$userstotal = $this->getDoctrine()->getRepository(BFUser::class)->findAll();
$userlastmonth = $this->getDoctrine()->getRepository(BFUser::class)->findAllLastMonth();
$userstat->setName('User');
$userstat->setLastmonth(count($userlastmonth));
$userstat->setTotal(count($userstotal));
array_push($statistics,$userstat);
$festivalstat= new Statistic();
$festivaltotal = $this->getDoctrine()->getRepository(BFFestival::class)->findAll();
$festivallastmonth = $this->getDoctrine()->getRepository(BFFestival::class)->findAllLastMonth();
$festivalstat->setName('Festival');
$festivalstat->setLastmonth(count($festivallastmonth));
$festivalstat->setTotal(count($festivaltotal));
array_push($statistics,$festivalstat);
$challengestat= new Statistic();
$challengetotal = $this->getDoctrine()->getRepository(BFChallenge::class)->findAll();
$challengelastmonth = $this->getDoctrine()->getRepository(BFChallenge::class)->findAllLastMonth();
$challengestat->setName('Challenge');
$challengestat->setLastmonth(count($challengelastmonth));
$challengestat->setTotal(count($challengetotal));
array_push($statistics,$challengestat);
$stateditions = new Statistic();
$activeeditions = $this->getDoctrine()->getRepository(BFEdition::class)->findBy(['isactive'=>true]);
$stateditions->setName('Editions actives');
$stateditions->setTotal(count($activeeditions));
array_push($statistics, $stateditions);
$stateditionschallenge = new Statistic();
$activeeditionschallenge = $this->getDoctrine()->getRepository(BFChallengeEdition::class)->findBy(['isactive'=>true]);
$stateditionschallenge->setName('Editions Challenge actives');
$stateditionschallenge->setTotal(count($activeeditionschallenge));
array_push($statistics, $stateditionschallenge);
return $this->render('adminsuperadmin.html.twig', [
'userdescription' => $user->getDescription(),
'formaddoption' => $formaddoption->createView(),
'formfindpayment' => $formfindpayment->createView(),
'bfadminlicences' => $adminlicences,
'statistics' => $statistics,
'bfpaymentintentadmins' => $adminpayments,
'activesuperadmin' => 1,
]);
}
/**
* @Route ("/admin/superadmin/all", name="admin_superadmin_all")
*/
public function ShowSuperAdminAllView(SessionInterface $session, PaginatorInterface $paginator, Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
$user = $this->getUser();
$festivals = $this->getDoctrine()->getRepository(BFFestival::class)->findAll();
$challenges = $this->getDoctrine()->getRepository(BFChallenge::class)->findAll();
$session->set('allfestivals', $festivals);
$session->set('allchallenges', $challenges);
$paginationfestivals = $paginator->paginate(
$session->get('allfestivals'), /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
10 /*limit per page*/
);
$paginationchallenges = $paginator->paginate(
$session->get('allchallenges'), /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
10 /*limit per page*/
);
return $this->render('adminsuperadminall.html.twig', [
'userdescription' => $user->getDescription(),
'paginationfestivals' => $paginationfestivals,
'paginationchallenges' => $paginationchallenges,
'activesuperadmin' => 2,
]);
}
/**
* @Route("/admin/superadmin/paymentadmin/create", name="admin_superadmin_paymentadmin_create")
*/
public function CreatePaymentIntentAdmin(Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
$user = $this->getUser();
$bfpaymentintentbfadmin = new BFPaymentIntentAdmin();
//form add option or offer
$formbfpaymentintentbfadmin=$this->createForm(BFPaymentIntentAdminType::class, $bfpaymentintentbfadmin, ['submit_label'=>'Créer']);
$formbfpaymentintentbfadmin->handleRequest($request);
if($formbfpaymentintentbfadmin->isSubmitted() && $formbfpaymentintentbfadmin->isValid())
{
$bfpaymentintentbfadmin=$formbfpaymentintentbfadmin->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($bfpaymentintentbfadmin);
$em->flush() ;
$this->addFlash('primary', 'Le paiement admin a été créé');
return $this->redirectToRoute('admin_superadmin_paymentadmin_edit', ['idpaymentintentadmin' => $bfpaymentintentbfadmin->getId() ]);
}
if($formbfpaymentintentbfadmin->isSubmitted() && !$formbfpaymentintentbfadmin->isValid())
{
foreach($formbfpaymentintentbfadmin->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
return $this->render('payments/superadminpaymentadmin.html.twig', [
'userdescription' => $user->getDescription(),
'formbfpaymentintentbfadmin' => $formbfpaymentintentbfadmin->createView(),
'activesuperadmin' => 1,
]);
}
/**
* @Route("/admin/superadmin/paymentadmin/edit/{idpaymentintentadmin}", name="admin_superadmin_paymentadmin_edit")
*/
public function EditPaymentIntentAdmin(int $idpaymentintentadmin, Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
$user = $this->getUser();
$bfpaymentintentbfadmin = $this->getDoctrine()->getRepository(BFPaymentIntentAdmin::class)->find($idpaymentintentadmin);
if($bfpaymentintentbfadmin==null)
throw $this->createNotFoundException();
//form add option or offer
$formbfpaymentintentbfadmin=$this->createForm(BFPaymentIntentAdminType::class, $bfpaymentintentbfadmin);
$formbfpaymentintentbfadmin->handleRequest($request);
if($formbfpaymentintentbfadmin->isSubmitted() && $formbfpaymentintentbfadmin->isValid())
{
$bfpaymentintentbfadmin=$formbfpaymentintentbfadmin->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($bfpaymentintentbfadmin);
$em->flush() ;
$this->addFlash('primary', 'Le paiement admin a été édité');
return $this->redirect($request->getUri());
}
if($formbfpaymentintentbfadmin->isSubmitted() && !$formbfpaymentintentbfadmin->isValid())
{
foreach($formbfpaymentintentbfadmin->getErrors(true) as $error)
$this->addFlash('danger', "(".$error->getOrigin()->getName().") ".$error->getMessage());
return $this->redirect($request->getUri());
}
return $this->render('payments/superadminpaymentadmin.html.twig', [
'userdescription' => $user->getDescription(),
'formbfpaymentintentbfadmin' => $formbfpaymentintentbfadmin->createView(),
'bfpaymentintentadmin' => $bfpaymentintentbfadmin,
'activesuperadmin' => 1,
'isedit' => 1,
]);
}
/**
* @Route("/admin/superadmin/paymentadmin/delete/{idpaymentintentadmin}", name="admin_superadmin_paymentadmin_delete")
*/
public function DeletePaymentIntentAdmin(int $idpaymentintentadmin, Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
$bfpaymentintentbfadmin = $this->getDoctrine()->getRepository(BFPaymentIntentAdmin::class)->find($idpaymentintentadmin);
if($bfpaymentintentbfadmin==null)
throw $this->createNotFoundException();
$em = $this->getDoctrine()->getManager();
$em->remove($bfpaymentintentbfadmin);
$em->flush() ;
$this->addFlash('primary', 'Le paiement admin a été supprimé');
return $this->redirectToRoute('admin_superadmin_view');
}
/**
* @Route("/admin/superadmin/paymentadmin/send/{idpaymentintentadmin}", name="admin_superadmin_paymentadmin_send")
*/
public function SendPaymentIntentAdmin(int $idpaymentintentadmin, Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
$bfpaymentintentbfadmin = $this->getDoctrine()->getRepository(BFPaymentIntentAdmin::class)->find($idpaymentintentadmin);
if($bfpaymentintentbfadmin==null)
throw $this->createNotFoundException();
$subject = 'Proposition de procéder au paiement';
$txtmessage="Pas de message texte disponible, seulement la version html est possible";
$htmlmessage = $this->renderView('mail/adminbfpaymentintentadminmail.html.twig', [
'subject' => $subject,
'bfpaymentintentadmin' => $bfpaymentintentbfadmin,
]);
$sent=Mail::SendMailToMail($bfpaymentintentbfadmin->getEmail(), $subject, $htmlmessage, $txtmessage);
if($sent)
{
$this->addFlash('primary', 'Le paiement admin a été envoyé');
}
else
{
$this->addFlash('danger', 'Erreur dans l\'envoie');
}
return $this->redirectToRoute('admin_superadmin_view');
}
/**
* @Route("/paymentadmin/pay/{idpaymentintentadmin}", name="paymentadmin_pay")
*/
public function ProceedPaymentIntentAdmin(int $idpaymentintentadmin, Request $request)
{
$bfpaymentintentbfadmin = $this->getDoctrine()->getRepository(BFPaymentIntentAdmin::class)->find($idpaymentintentadmin);
if($bfpaymentintentbfadmin==null)
throw $this->createNotFoundException();
if($bfpaymentintentbfadmin->getSuccessdate()!=null)
return $this->redirectToRoute('paymentadmin_pay_success',['idpaymentintentadmin'=> $idpaymentintentadmin]);
Stripe::setApiKey($this->getParameter('stripe_secret_key'));
//Create Stripe payment intent and fill data
$intent = PaymentIntent::create([
'amount'=>$bfpaymentintentbfadmin->getPrice(),
'currency' => 'eur',
'description' => $bfpaymentintentbfadmin->getDescription(),
'receipt_email' => $bfpaymentintentbfadmin->getEmail(),
'payment_method_types' => ['card'],
['metadata' => ['bfpaymentintentadmin_id' => $bfpaymentintentbfadmin->getId()]]
]);
$bfpaymentintentbfadmin->setStripeid($intent->id);
$em = $this->getDoctrine()->getManager();
$em->persist($bfpaymentintentbfadmin);
$em->flush();
$succesurl = $this->generateUrl('paymentadmin_pay_success', [
'idpaymentintentadmin' => $idpaymentintentadmin,
]);
//we can show the payment page
return $this->render('homepaymentadmin.html.twig',[
'bfpaymentadmin' => $bfpaymentintentbfadmin,
'intentsecret' => $intent->client_secret,
'stripe_public_key' => $this->getParameter('stripe_public_key'),
'success_url' => $succesurl,
]
);
}
/**
* @Route("/paymentadmin/success/{idpaymentintentadmin}", name="paymentadmin_pay_success")
*/
public function SuccessPaymentIntentAdmin(int $idpaymentintentadmin, Request $request)
{
$bfpaymentintentbfadmin = $this->getDoctrine()->getRepository(BFPaymentIntentAdmin::class)->find($idpaymentintentadmin);
if($bfpaymentintentbfadmin==null)
throw $this->createNotFoundException();
return $this->render('homepaymentadminsuccess.html.twig');
}
/**
* @Route ("/admin/superadmin/adminlicence/delete/{id}", name="admin_superadmin_deletelicence")
*/
public function DeleteAdminLicence(int $id, Request $request)
{
$this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
$bfadminlicence = $this->getDoctrine()->getRepository(BFAdminLicences::class)->find($id);
if($bfadminlicence!=null)
{
$em = $this->getDoctrine()->getManager();
$em->remove($bfadminlicence);
$em->flush();
$this->addFlash('primary', 'L\'option a été supprimée');
}
else
{
$this->addFlash('danger', 'Erreur durant l\'opération');
}
return $this->redirectToRoute('admin_superadmin_view');
}
private function ClearUserResetPassword(BFUser $bfuser)
{
//get bfreset from user id
$bfresetpassword = $this->getDoctrine()->getRepository(BFResetPassword::class)->findOneBy(['user'=>$bfuser]);
if($bfresetpassword!=null)
{
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($bfresetpassword);
$entityManager->flush();
}
}
private function GetUniqueToken()
{
$randomstring="";
$unique=false;
$resetrepository = $this->getDoctrine()->getRepository(BFResetPassword::class);
while(!$unique)
{
$randomstring = Secure::GenerateKey(20);
$bfresetpassword = $resetrepository->findOneBy(array('token'=>$randomstring));
$unique=($bfresetpassword==null);
}
return $randomstring;
}
}