<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mime\Email;
use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\Routing\Annotation\Route;
use App\Utils\Ticketing;
use App\Entity\User;
use App\Entity\Item;
use App\Utils\Functions;
class UserController extends AbstractController
{
/**
* @var Ticketing
*/
private $ticketing;
/**
* @var Functions
*/
private $functions;
/**
* @var ManagerRegistry
*/
private $doctrine;
/**
* @param Ticketing $ticketing
* @param Functions $functions
* @param ManagerRegistry $doctrine
*/
public function __construct(Ticketing $ticketing, Functions $functions, ManagerRegistry $doctrine)
{
date_default_timezone_set('UTC');
$this->ticketing = $ticketing;
$this->functions = $functions;
$this->doctrine = $doctrine;
}
/**
* @Route("/access", name="access")
*/
public function access(Request $request, ManagerRegistry $doctrine, MailerInterface $mailer): Response
{
if($request->get("format")){
$format = $request->get("format");
} else {
$format = 1;
}
$session = $request->getSession();
if($request->get("ref")){
$session->set('ref', $request->get("ref"));
}
$entityManager = $doctrine->getManager();
$redirect="";
$statusLogin = "";
$statusPreregister = "";
$emailPreregister = $request->get('email-preregister');
$emailLogin = $request->get('email-login');
$password = $request->get('password');
if($request->get("redirect")){
$redirect=$request->get("redirect");
}
if($emailLogin){
if($request->get('send-form-log')){
$result = $this->ticketing->curl("users/login", "normal", array("userId"=>$emailLogin, "password"=>$password), "POST");
if($result["code"] != 200){
$statusLogin = "error";
} else{
$session = $request->getSession();
$session->set('userId', $result["userId"]);
if($redirect!=""){
return $this->redirect($redirect);
}
return $this->redirectToRoute('home');
}
}
}
if ($emailPreregister) {
if ($request->get('send-form-pre')) {
$result = $this->ticketing->curl("users", "normal", array("userId" => $emailPreregister), "POST");
if ($result["code"] != 201) {
$statusPreregister = "error";
} else {
$email = (new TemplatedEmail())
->from($this->getParameter('mailer_from'))
->to($result["userId"])
->subject('2º Congreso Iberoamericano de DBT - Registro')
->htmlTemplate('mail/register.html.twig')
->context([
'userId' => $result["userId"],
'registerCode' => $result["registerCode"],
]);
try {
$mailer->send($email);
$statusPreregister = "done";
} catch (\Exception $e) {
$statusPreregister = 'sender_error';
}
$user = new User();
$user->setUserId($result["userId"]);
$user->setCreatedAt(new \DateTime());
$entityManager->persist($user);
$entityManager->flush();
}
}
}
return $this->render('user/access.html.twig', [
'statusLogin' => $statusLogin,
'statusPreregister' => $statusPreregister,
'redirect' => $redirect,
'format' => $format
]);
}
/**
* @Route("/register/{userId}/{registerCode}", name="register")
*/
public function register(Request $request, ManagerRegistry $doctrine, $userId, $registerCode): Response
{
$em = $doctrine->getManager();
$status = "";
$user = $this->ticketing->curl("users/".$userId, "normal", array(), "GET");
if($user["code"] == 200){
$status = "error";
} else {
if($request->get('send-form')){
$password = $request->get('password');
$name = !empty($request->get('name')) ? $request->get('name') : '';
$surname = !empty($request->get('surname')) ? $request->get('surname') : '';
$nationallity = !empty($request->get('nationallity')) ? $request->get('nationallity') : '';
$document = !empty($request->get('document')) ? $request->get('document') : '';
$country = !empty($request->get('country')) ? $request->get('country') : '';
$city = !empty($request->get('city')) ? $request->get('city') : '';
if ($request->get('birth_date')) {
$birth_date = $request->get('birth_date');
$datetime = new \DateTime();
$newDate = $datetime->createFromFormat('Y-m-d', $birth_date);
}
$gender = !empty($request->get('gender')) ? $request->get('gender') : '';
$phone = !empty($request->get('phone')) ? $request->get('phone') : '';
$objUser = $em->getRepository(User::class)->findOneBy(['user_id' => $userId]);
$objUser->setName($name);
$objUser->setSurname($surname);
$objUser->setNationallity($nationallity);
$objUser->setDocument($document);
$objUser->setCountry($country);
$objUser->setCity($city);
if (isset($newDate)) $objUser->setBirthDate($newDate);
$objUser->setGender($gender);
$objUser->setPhone($phone);
$em->persist($objUser);
$em->flush();
$result = $this->ticketing->curl("users", "normal", array("userId"=>$userId, "password"=>$password, "name"=>$name, "surname"=>$surname, "registerCode"=>$registerCode), "PATCH");
if($result["code"] != 200){
$status = "error";
} else {
$status = "done";
}
}
}
return $this->render('user/register.html.twig', [
'status' => $status,
'id' => $userId,
'code' => $registerCode
]);
}
/**
* @Route("/logout", name="logout")
*/
public function logout(Request $request): Response
{
$session = $request->getSession();
$session->clear();
return $this->redirectToRoute('home');
}
/**
* @Route("/user-profile", name="userProfile")
*/
public function userProfile(Request $request): Response
{
$session = $request->getSession();
if($request->get("ref")){
$session->set('ref', $request->get("ref"));
}
$em = $this->doctrine->getManager();
$userId=$this->functions->getUserLogged();
if(!$userId){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return $this->redirectToRoute('access',array("redirect" => $this->generateUrl('userProfile')));
}
$tickets = $this->ticketing->curl("tickets?onSaleByUser=false&user=".$userId."&limit=1000", "normal", array(), "GET");
$result = $this->ticketing->curl("users/".$userId, "normal", array(), "GET");
$items_pending = $em->getRepository(Item::class)->search("count",array("web_pending" => TRUE));
$sents = $this->ticketing->curl("tickets/activity?origin=".$userId."&limit=1000&enabled=true", "normal", array(), "GET");
$sells = $this->ticketing->curl("tickets?onSaleByUser=true&user=".$userId."&limit=1000", "normal", array(), "GET");
$userAlias = $em->getRepository(User::class)->findOneBy(['user_id' => $userId])->getName();
return $this->render('user/profile.html.twig', [
'user' => $result,
'tickets' => $tickets["tickets"],
"items_pending" => $items_pending,
"name" => $userAlias,
"sents" => $sents["activity"],
"sells" => $sells["tickets"]
]);
}
/**
* @Route("/extra-content/{ticketId}/{source}", name="extraContent")
*/
public function extraContent(Request $request, $ticketId, $source): Response
{
$session = $request->getSession();
$em = $this->doctrine->getManager();
$userId=$this->functions->getUserLogged();
if(!$userId){
$this->addFlash(
'notice',
'Debe iniciar sesión como usuario'
);
return $this->redirectToRoute('access');
}
$ticket = $this->ticketing->curl("tickets/".$ticketId, "normal", array(), "GET");
if(!$ticket || $ticket["code"]!="200" || $ticket["user"]["userId"]!=$userId || !$ticket["active"]){
$this->addFlash(
'notice',
'No se puede acceder al contenido extra'
);
return $this->redirectToRoute('home');
}
if(!array_key_exists("extraContent", $ticket) || !array_key_exists($source, $ticket["extraContent"])){
$this->addFlash(
'notice',
'No se puede acceder al contenido extra'
);
return $this->redirectToRoute('home');
}
$source = $ticket["extraContent"][$source];
// Path to your private key. Be very careful that this file is not accessible
// from the web!
$private_key_filename = \dirname(__DIR__).'/../var/private_key.pem';
$key_pair_id = 'K3HFP4XM97GS7X';
$expires = time() + 86400; // 1 hour
$canned_policy_stream_name = $this->functions->get_canned_policy_stream_name($source, $private_key_filename, $key_pair_id, $expires);
$client_ip = $_SERVER['REMOTE_ADDR'];
$policy =
'{'.
'"Statement":['.
'{'.
'"Resource":"'. $source . '",'.
'"Condition":{'.
'"IpAddress":{"AWS:SourceIp":"' . $client_ip . '/32"},'.
'"DateLessThan":{"AWS:EpochTime":' . $expires . '}'.
'}'.
'}'.
']' .
'}';
$custom_policy_stream_name = $this->functions->get_custom_policy_stream_name($source, $private_key_filename, $key_pair_id, $policy);
//echo urldecode($canned_policy_stream_name);die();
return $this->redirect(urldecode($custom_policy_stream_name));
return $this->render('user/extra-content.html.twig', [
'source' => $source,
'canned_policy_stream_name' => urldecode($canned_policy_stream_name),
'custom_policy_stream_name' => urldecode($custom_policy_stream_name)
]);
}
/**
* @Route("/recover-password", name="recoverPassword")
*/
public function recoverPassword(Request $request, MailerInterface $mailer): Response
{
$status = "";
$email = $request->get('email');
$result = $this->ticketing->curl("users/".$email."/recover", "normal", array(), "GET");
if($email && $result){
if($result["code"] != 200 || (!array_key_exists('recoverCode', $result) && !array_key_exists('registerCode', $result))){
$status = "error";
} else {
if(array_key_exists('registerCode', $result)){
$mail = (new TemplatedEmail())
->from($this->getParameter('mailer_from'))
->to($email)
->subject('2º Congreso Iberoamericano de DBT - Registro')
->htmlTemplate('mail/register.html.twig')
->context([
'userId' => $email,
'registerCode' => $result["registerCode"],
]);
} else {
$mail = (new TemplatedEmail())
->from($this->getParameter('mailer_from'))
->to($email)
->subject('2º Congreso Iberoamericano de DBT - Recuperar contraseña')
->htmlTemplate('mail/recover-password.html.twig')
->context([
'userId' => $email,
'recoverCode' => $result["recoverCode"],
]);
}
try {
$mailer->send($mail);
$status = "done";
} catch (\Exception $e) {
$status = 'sender_error';
}
}
}
return $this->render('user/recover-password.html.twig', [
'status'=>$status
]);
}
/**
* @Route("/change-password/{userId}/{recoverCode}", name="changePassword")
*/
public function changePassword(Request $request, $userId, $recoverCode): Response
{
$status = "";
$password = $request->get('password');
$check = $this->ticketing->curl("users/".$userId, "normal", array(), "GET");
if($check["code"] != 200 || !array_key_exists('recoverCode', $check) || $check["recoverCode"]!=$recoverCode){
$status = "error2";
}
else{
if($request->get('send-form')){
$result = $this->ticketing->curl("users/change-password", "normal", array("userId"=>$userId, "password"=>$password, "recoverCode"=>$recoverCode), "PATCH");
if($result["code"] != 200){
$status = "error";
} else {
$status = "done";
}
}
}
return $this->render('user/change-password.html.twig', [
'status' => $status,
'id' => $userId,
'code' => $recoverCode
]);
}
}