<?php
namespace App\Controller\Users\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use App\Entity\Users\Adminuser\Parametreadmin;
use App\Service\Servicetext\GeneralServicetext;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Produit\Produit\Produit;
use App\Entity\Users\User\Imgslide;
use App\Entity\Produit\Produit\Souscategorie;
use App\Entity\Projet\Projet\Offrespeciale;
use App\Entity\Produit\Produit\Animationproduit;
use App\Entity\Produit\Produit\Panier;
use App\Entity\Produit\Produit\Coutlivraison;
use App\Entity\Produit\Produit\Marqueproduit;
use App\Entity\Produit\Service\Ville;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use App\Service\Email\Singleemail;
use App\Entity\Users\User\User;
use App\Repository\Users\User\UserRepository;
use App\Service\Users\User\UserService;
use Symfony\Component\Security\Http\Event\LogoutEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class SecurityController extends AbstractController
{
private $params;
private $_servicemail;
private $_userService;
private $_userRepository;
public function __construct(ParameterBagInterface $params, Singleemail $servicemail, UserService $userService, UserRepository $userRepository)
{
$this->params = $params;
$this->_servicemail = $servicemail;
$this->_userService = $userService;
$this->_userRepository = $userRepository;
}
/*
public function login(Request $request)
{
$session = $request->getSession();
$em = $this->getDoctrine()->getManager();
// Si le visiteur est déjà identifié, on le redirige vers l'accueil
if($this->isGranted('IS_AUTHENTICATED_REMEMBERED')){
return $this->redirect($this->generateUrl('users_user_acces_plateforme'));
}
// On vérifie s'il y a des erreurs d'une précédente soumission du formulaire
$paramlogosm = $em->getRepository(Parametreadmin::class)
->findOneBy(array('type'=>'logosm'));
$loginbg = $em->getRepository(Parametreadmin::class)
->findOneBy(array('type'=>'loginbg'));
return $this->render($service->getThemeDirectory().'/Users/User/Security/login.html.twig',
array('paramlogosm'=>$paramlogosm,'loginbg'=>$loginbg));
}*/
public function login(GeneralServicetext $service, Request $request)
{
$em = $this->getDoctrine()->getManager();
// Si le visiteur est déjà identifié, on le redirige vers l'accueil
if($this->getUser() != null){ //IS_AUTHENTICATED_REMEMBERED
return $this->redirect($this->generateUrl('users_user_acces_plateforme'));
}
//connexion sécurisé user.
$error_login = '';
$last_username = null;
if($request->getMethod() == 'POST' and $this->getUser() == null){
if (isset($_POST['_username']) and isset($_POST['_password'])){
$repository = $em->getRepository(User::class);
$user = $repository->findOneBy(array('username'=>$_POST['_username']));
if($user != null)
{
if($_POST['_password'] == $service->decrypt($user->getPassword(),$user->getSalt()))
{
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
$this->get('session')->set('_security_main', serialize($token));
// Verifie si le cookie n existe pas
if((!isset($_COOKIE["PIDSESSREM"]) or $_COOKIE["PIDSESSREM"] == 'delete') and isset($_POST['_remember_me']) and $_POST['_remember_me'] == true)
{
// Stock les infos du cookie
$cookie_info = array(
'name' => 'PIDSESSREM',
'value' => $service->encrypt($user->getUsername(),$this->params->get('saltcookies')),
'time' => time() + (3600 * 24 * 360)
);
// Cree le cookie
setCookie($cookie_info['name'], $cookie_info['value'], $cookie_info['time'],'/');
setCookie('PIDSESSDUR',$cookie_info['time'], $cookie_info['time'],'/');
}
$session = $this->get('session');
$target_link = $session->get('_security.welcome.target_path');
if($target_link != null and strlen($target_link) > 5)
{
return $this->redirect($target_link);
}else{
return $this->redirect($this->generateUrl('users_user_acces_plateforme'));
}
}else{
$error_login = '<span style="color: red;">Echec: Mot de passe ou Email invalide.</span>';
$last_username = $_POST['_username'];
}
}else{
$last_username = $_POST['_username'];
}
}
}
$paramlogosm = $em->getRepository(Parametreadmin::class)
->findOneBy(array('type'=>'logosm'));
$loginbg = $em->getRepository(Parametreadmin::class)
->findOneBy(array('type'=>'loginbg'));
return $this->render($service->getThemeDirectory().'/Users/User/Security/login.html.twig',
array('last_username' => $last_username,'error'=> $error_login, 'paramlogosm'=>$paramlogosm,'loginbg'=>$loginbg));
}
public function accueilsite(GeneralServicetext $service)
{
$em = $this->getDoctrine()->getManager();
$session = $this->get('session');
if($this->isGranted('IS_AUTHENTICATED_REMEMBERED')){ //dès qu'un utilisateur se connecte il est redirigé vers le path / qui exécute directement ce controlleur.
$user = $this->getUser();
$dureelastvisite = round((time() - $user->getDernierevisite())/60);
if($dureelastvisite >= 3) //s'il ya plus de 3 minutes que utilisateur n'a pas actualisé sa sesion
{
$user->setDernierevisite(time());
$em->flush();
}
$idproduit = $session->get('idproduit');
if($idproduit != null and $idproduit > 0)
{
$produit = $em->getRepository(Produit::class)
->find($idproduit);
if($produit != null){
$produit->setUser($user);
$em->flush();
}
return $this->redirect($this->generateUrl('produit_produit_ajouter_denouveaux_produits_courant_binplace',
array('position'=>2,'ide'=>$idproduit)));
}
}
$liste_slide = $em->getRepository(Imgslide::class)
->myFindAll();
$top_produit = $em->getRepository(Produit::class)
->findBestProduit(10);
$produit_recommander = $em->getRepository(Produit::class)
->findProduitRecommander(50);
$produit_recommander = $service->selectEntities($produit_recommander, 10);
$top_scat = $em->getRepository(Souscategorie::class)
->myfindAll();
$liste_offre = $em->getRepository(Offrespeciale::class)
->allspecialesoffres(1, 20);
$two_offert = $service->selectEntities($liste_offre, 2);
$firstoffert = $service->selectEntity($liste_offre);
$tabarray = array();
$liste_enregistrement = new \Doctrine\Common\Collections\ArrayCollection();
if($this->getUser() != null)
{
$enregistrement_user = $em->getRepository(Animationproduit::class)
->findBy(array('user'=>$this->getUser(),'enregistrer'=>1), array('date'=>'desc'),3);
foreach($enregistrement_user as $enreg)
{
$liste_enregistrement[] = $enreg;
array_push($tabarray, $enreg->getId());
}
}
$all_enregistrement = $em->getRepository(Animationproduit::class)
->findEnregistrement(10);
foreach($all_enregistrement as $enreg)
{
if(count($liste_enregistrement) < 10 /*and !in_array($enreg->getId(),$tabarray)*/)
{
if(!in_array($enreg->getId(),$tabarray))
{
$liste_enregistrement[] = $enreg;
}
}else{
break;
}
}
$idcard = 0;
if(isset($_COOKIE["PIDCARD"]) and $_COOKIE["PIDCARD"] != 'empty')
{
$idcard = $_COOKIE["PIDCARD"];
}
$prod_panier = new \Doctrine\Common\Collections\ArrayCollection();
$oldpanier = $em->getRepository(Panier::class)
->findOneBy(array('id'=>$idcard,'sousmis'=>0));
if($oldpanier == null and $this->getUser() != null)
{
$oldpanier = $em->getRepository(Panier::class)
->findOneBy(array('user'=>$this->getUser(),'sousmis'=>0));
}
if($oldpanier != null)
{
$prod_panier = $oldpanier->getProduitpaniers();
}
$liste_offre = $em->getRepository(Offrespeciale::class)
->allspecialesoffres(1, 6);
$points_livraison = $em->getRepository(Coutlivraison::class)
->getAllLivraisonPoints(1,6);
$aproposaccueil = $em->getRepository(Parametreadmin::class)
->findOneBy(array('type'=>'aproposaccueil'));
$liste_marque = $em->getRepository(Marqueproduit::class)
->myFindAll();
$liste_ville = $em->getRepository(Ville::class)
->myFindAll(1, 10);
$new_produit = $em->getRepository(Produit::class)
->findNewProduit(10);
return $this->render($service->getThemeDirectory().'/Users/User/Security/accueilsite.html.twig',
array('liste_slide'=>$liste_slide,'top_produit'=>$top_produit,'top_scat'=>$top_scat,'firstoffert'=>$firstoffert,
'aproposaccueil'=>$aproposaccueil,'two_offert'=>$two_offert,'prod_panier'=>$prod_panier,'new_produit'=>$new_produit,
'produit_recommander'=>$produit_recommander,'oldpanier'=>$oldpanier,'liste_enregistrement'=>$liste_enregistrement,
'liste_offre'=>$liste_offre,'points_livraison'=>$points_livraison,'liste_marque'=>$liste_marque,'liste_ville'=>$liste_ville));
}
public function resetpassword($etape, GeneralServicetext $service)
{
$em = $this->getDoctrine()->getManager();
$session = $this->get('session');
if($etape == 1)
{
if(isset($_POST['username']))
{
$repository = $em->getRepository(User::class);
$user = $repository->findOneBy(array('username'=>$_POST['username']));
if($user != null)
{
$code = $user->getDatebeg();
if($service->email($user->getUsername()))
{
$siteweb = $this->params->get('siteweb');
$sitename = $this->params->get('sitename');
$emailadmin = $this->params->get('emailadmin');
$response = $this->_servicemail->sendNotifEmail(
$user->name(30), //Nom du destinataire
$user->getUsername(), //Email Destinataire
$user->name(30).', Vous avez demandé la réinitialisation du mot de passe de votre compte '.$sitename, //Objet de l'email
$user->name(30).', Vous avez demandé la réinitialisation du mot de passe de votre compte '.$sitename, //Grand Titre de l'email
'Le code est: <strong style="font-size: 25px;">'.$code.'</strong></br></br> Si vous n\'avez pas demandé cette action, Aucune action n\'est requise de votre part.', //Contenu de l'email
$siteweb.'/login' //Lien à suivre
);
$type = 1;
}else{
$type = 2;
}
return $this->render($service->getThemeDirectory().'/Users/User/Security/resetpassword.html.twig',
array('type' =>$type,'etape'=> $etape,'user'=>$user));
}else{
echo 0;
exit;
}
}else{
echo 0;
exit;
}
}else if($etape == 2)
{
if(isset($_POST['code']) and isset($_POST['id']))
{
$repository = $em->getRepository(User::class);
$user = $repository->find($_POST['id']);
if($user != null and $user->getDatebeg() == trim($_POST['code']))
{
$session->set('reset_password', 1);
return $this->render($service->getThemeDirectory().'/Users/User/Security/resetpassword.html.twig',
array('etape'=> $etape,'user'=>$user));
}else{
echo 0;
exit;
}
}else{
echo 0;
exit;
}
}else if($etape == 3)
{
if(isset($_POST['password']) and isset($_POST['id']))
{
$repository = $em->getRepository(User::class);
$user = $repository->find($_POST['id']);
$reset_password = $session->get('reset_password');
if($user != null and $reset_password == 1)
{
//sécurisation du mot de passe utilisateur
$passuser = $_POST['password'];
/*
$salt = substr(crypt($passuser,''), 0, 16);
$user->setSalt($salt);
$newpassword = $service->encrypt($passuser,$salt);
*/
$user->setPassword($passuser);
$em->flush();
return $this->render($service->getThemeDirectory().'/Users/User/Security/resetpassword.html.twig',
array('etape'=> $etape,'user'=>$user));
}else{
echo 0;
exit;
}
}else{
echo 0;
exit;
}
}
echo 0;
exit;
}
public function clearsession(Request $request, GeneralServicetext $service, TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher)
{
$logoutEvent = new LogoutEvent($request, $tokenStorage->getToken());
$eventDispatcher->dispatch($logoutEvent);
$tokenStorage->setToken(null);
$response = new Response();
$response->headers->clearCookie('REMEMBERME');
$response->headers->clearCookie('PIDSESSREM');
$response->headers->clearCookie('PIDSESSDUR');
$response->send();
/*if(isset($_COOKIE["PIDSESSREM"]) and isset($_COOKIE["PIDSESSDUR"]))
{
// Stock les infos du cookie
$cookie_info = array(
'name' => "PIDSESSREM",
'value' => "delete",
'time' => $_COOKIE["PIDSESSDUR"]
);
setCookie($cookie_info['name'], $cookie_info['value'], $cookie_info['time'],'/');
}
$this->get('security.token_storage')->setToken(null);
$request->getSession()->invalidate();*/
return $this->redirect($this->generateUrl('users_user_acces_plateforme'));
}
public function opensession(Request $request, GeneralServicetext $generalServicetext)
{
$parameters = json_decode($request->getContent(), true);
if(count($parameters) == 2)
{
if($generalServicetext->array_keys_exists(array("user", "authcode"), $parameters))
{
$iduser = $parameters['user']['id'];
$olduser = $this->_userRepository->findOneBy(array('puui'=>$iduser), array('datebeg'=>'desc'), 1);
if($olduser == null){
$email = $parameters['user']['email'];
$phone = $parameters['user']['phone'];
if($email != null)
{
$username = $email;
$olduser = $this->_userRepository->findOneBy(array('email'=>$email));
}else{
$username = $phone;
$olduser = $this->_userRepository->findOneBy(array('tel'=>$phone));
}
if($olduser == null)
{
$olduser = $this->_userRepository->findOneBy(array('username'=>$username));
if($olduser == null){
//create User and log it
$data = $this->_userService->loginUser($request, null, $parameters['user']['token'], $parameters['user']['tokenkey'], $parameters['user']['firstName'], $parameters['user']['lastName'], $parameters['user']['email'], $parameters['user']['phone'], $parameters['user']['imgprofil'], $parameters['user']['id']);
}else{
//log user
$data = $this->_userService->loginUser($request, $olduser, $parameters['user']['token'], $parameters['user']['tokenkey']);
}
}else{
//log user
$data = $this->_userService->loginUser($request, $olduser, $parameters['user']['token'], $parameters['user']['tokenkey']);
}
}else{
//log user
$data = $this->_userService->loginUser($request, $olduser, $parameters['user']['token'], $parameters['user']['tokenkey']);
}
return $data;
}
}
$data = $generalServicetext->badRequest();
return $data;
}
public function initlocallang()
{
$acceptLang = ['en', 'fr', 'de'];
if(isset($_GET['lang']) and in_array($_GET['lang'], $acceptLang))
{
$selectlang = $_GET['lang'];
}else{
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$selectlang = in_array($lang, $acceptLang) ? $lang : 'en';
}
return $this->redirect($this->generateUrl('users_user_acces_plateforme', array('_locale'=>$selectlang)));
}
}