<?php
namespace App\Controller\Api;
use App\Entity\Customer;
use App\Entity\CustomerDevice;
use App\Helper\UploadedBase64File;
use App\Services\Api\CustomerManager;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Stripe\Event;
use Stripe\Exception\SignatureVerificationException;
use Stripe\Webhook;
use Psr\Log\LoggerInterface;
use App\Helper\StripeHelper;
\Stripe\Stripe::setApiKey($_ENV['STRIPE_SECRET_KEY_TEST']);
class AuthController extends ApiController
{
/** @var CustomerManager $customerManager */
protected $customerManager;
/**
* @param CustomerManager $customerManager
*/
public function __construct(EntityManagerInterface $em,
ParameterBagInterface $parameterBag,
CustomerManager $customerManager)
{
parent::__construct($em,$parameterBag);
$this->customerManager = $customerManager;
}
/**
* @param Request $request
* @param UserPasswordEncoderInterface $encoder
* @return JsonResponse
*
* @Route("/register", name="api_register", methods={"POST"})
*/
public function register(Request $request, UserPasswordEncoderInterface $encoder)
{
$request = $this->transformJsonBody($request);
$data = [
"name"=>$request->get('name'),
"email"=>$request->get('email'),
"plainPassword"=>$request->get('password'),
"country"=>json_decode($request->get('country'),true),
"teamName"=>$request->get('teamName'),
"teamCategory"=>$request->get('teamCategory', ''),
"season"=>$request->get('season'),
"surname"=>$request->get('surname'),
"typeSoccer"=>$request->get('typeSoccer'),
];
$teamLogo = $request->get('teamLogo');
if(!empty($teamLogo))
$data["teamLogo"] = new UploadedBase64File($teamLogo, $request->get('teamLogoFilename'));
$trainerLogo = $request->get('trainerLogo');
if(!empty($trainerLogo))
$data["trainerLogo"] = new UploadedBase64File($trainerLogo, $request->get('trainerLogoFilename'));
$response = $this->customerManager->register($data, $request);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/auth/facebook", name="api_auth_facebook", methods={"POST"})
*/
public function authFacebook(Request $request)
{
$request = $this->transformJsonBody($request);
$data = [
"email"=>$request->get('email'),
"name"=>$request->get('name'),
"token"=>$request->get('token'),
];
$response = $this->customerManager->authFacebook($data, $request);
if($response)
return $response;
$this->setStatusCode(404);
return $this->response([
"code" => 404,
"message" => "Error al obtener usuario"
]);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/auth/google", name="api_auth_google", methods={"POST"})
*/
public function authGoogle(Request $request)
{
$request = $this->transformJsonBody($request);
$data = [
"email"=>$request->get('email'),
"name"=>$request->get('name'),
"token"=>$request->get('token'),
];
$response = $this->customerManager->authGoogle($data, $request);
if($response)
return $response;
$this->setStatusCode(404);
return $this->response([
"code" => 404,
"message" => "Error al obtener usuario"
]);
}
/**
* @Route("/reset-password", name="reset_password_request", methods={"POST"})
*/
public function request(Request $request, MailerInterface $mailer)
{
$request = $this->transformJsonBody($request);
$data = [
"email" => $request->get('email'),
];
$response = $this->customerManager->request_reset_password($data, $mailer);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @Route("/reset-password/validate/{token}", name="validate_password_reset", methods={"POST"})
*/
public function validate_otp($token, Request $request)
{
$request = $this->transformJsonBody($request);
$data = [
"email" => $request->get('email'),
"verificationCode" => $token,
];
$response = $this->customerManager->validate_otp_reset_password($data);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @Route("/reset-password/{hash_token}", name="reset_password_reset", methods={"POST"})
*/
public function reset($hash_token, Request $request, MailerInterface $mailer)
{
$request = $this->transformJsonBody($request);
$data = [
"email" => $request->get('email'),
"verificationHashCode" => $hash_token,
"password" => $request->get('password'),
"repeat_password" => $request->get('repeat_password'),
];
$response = $this->customerManager->reset_password($data, $mailer);
$this->setStatusCode($response["code"]);
return $this->response($response);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("/auth/login_external", name="api_login_external", methods={"POST"})
*/
public function loginExternal(Request $request)
{
$request = $this->transformJsonBody($request);
$data['email'] = $request->get('email');
$data['password'] = $request->get('password','');
$data['device_id'] = $request->get('device_id');
$data['isFingerPrinter'] = $request->get('isFingerPrinter') ?: 0;
$data['fingerprint'] = $request->get('fingerprint','');
$data['is_web_app'] = $request->get('is_web_app') ?: false;
$response = $this->customerManager->loginExternal($data);
if(is_array($response)){
$this->setStatusCode($response["code"]);
return $this->response($response);
}
return $response;
}
/**
* @Route("/auth/platform_check", name="platform_check")
*/
public function platformCheck(Request $request): JsonResponse
{
$userAgent = $request->headers->get('User-Agent');
if (stripos($userAgent, 'android') !== false) {
$platform = 'Android';
} elseif (stripos($userAgent, 'iphone') !== false || stripos($userAgent, 'ipad') !== false) {
$platform = 'iOS';
} else {
$platform = 'Web';
}
return new JsonResponse(['platform' => $platform]);
}
/**
* @param Request $request
* @return JsonResponse
*
* @Route("auth/remove_account_user", name="api_remove_account_auth", methods={"POST"})
*/
public function removeAccountDefinitely(Request $request)
{
$email = $request->get('email');
$customerRemove = $this->em->getRepository(Customer::class)->findOneBy([
'email' => $email,
'roles' => [Customer::ROLE_CUSTOMER],
]);
$separator = explode('@', $email);
$emailDeleted = $separator[0] . '_deleted_'.time().'@' . $separator[1];
$customerRemove->setEmail($emailDeleted);
$customerRemove->setIsDeleted(1);
$this->em->persist($customerRemove);
$customer_device = $this->em->getRepository(CustomerDevice::class)->findBy([
'customerId' => $customerRemove->getId(),
'status' => true,
]);
foreach ($customer_device as $key => $customerDevice) {
$customerDevice->setStatus(false);
$this->em->persist($customerDevice);
}
$this->em->flush();
return $this->response([
"msgType" => "success",
"message" => "remove user success",
"code" => 200
]);
}
/**
* @Route("/auth/webhook/stripe", name="stripe_webhook", methods={"POST"})
*/
public function handleWebhook(Request $request,LoggerInterface $logger): Response
{
$payload = $request->getContent();
$signature = $request->headers->get('stripe-signature');
$secret = 'whsec_KEM2T2UKlJyGoCrlpjeBck6cXKJtFD4f';
$event = null;
try {
$event = Webhook::constructEvent($payload, $signature, 'whsec_KEM2T2UKlJyGoCrlpjeBck6cXKJtFD4f');
} catch (SignatureVerificationException $e) {
return new Response('Invalid webhook signature', 400);
}
$logger->info('[MESSAGE].', ['data' => $event]);
$logger->info('[TYPE].', ['data' => $event->type]);
// Handle the event
switch ($event->type) {
case 'invoice.payment_succeeded':
$paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
$logger->info('[PAYMENT].', ['data' => $paymentIntent]);
$metadata = $event->data->object->subscription_details->metadata;
$subId = $event->data->object->subscription;
$userId = $metadata['user_id'];
$product_id = $event->data->object->lines->data[0]->description;
$customer = $this->em->getRepository(Customer::class)->findOneBy([
'id' => $userId
]);
$stripe = new StripeHelper();
if($customer !== null){
$data = [
'purchase' => $subId,
'platform' => 'Web',
'product_id'=> $product_id
];
$response = $this->customerManager->updatePurchaseByCustomer($customer,$data);
$logger->info('[PURCHASE_SUCCESS].', ['res' => $response]);
}
// Extract user_id from metadata
$logger->info('[USER_ID].', ['userId' => $userId]);
$logger->info('[SUBSCRIPTION KEY].', ['sub_key' => $userId]);
case 'payment_intent.succeeded':
case 'payment_method.attached':
$paymentIntent = $event->data->object; // contains a \Stripe\PaymentIntent
$logger->info('[PAYMENT].', ['data' => $paymentIntent]);
// Then define and call a method to handle the successful payment intent.
// handlePaymentIntentSucceeded($paymentIntent);
break;
default:
// Unexpected event type
$logger->info('[UNDEFINED EVENT].', ['data' => $event]);
}
return new Response('Webhook event handled');
}
/**
* @Route("/auth/stripe/success", name="app_stripe_payment_success")
*/
public function stripeSuccess(): RedirectResponse
{
// Redirect to the desired URL
$DOMAIN = $_ENV['DOMAIN'];
$PATH= '/settings/membership';
$url = $DOMAIN . $PATH;
return $this->redirect($url); // Replace with your URL
}
}