<?php
namespace EADPlataforma\Services;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use EADPlataforma\Entity\Session;
use EADPlataforma\Enum\ServicesEnum;
/**
* GeneralService
*/
class GeneralService
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var RequestStack
*/
protected $requestStack;
/**
* @var UrlGeneratorInterface
*/
protected $router;
/**
* @var Array
*/
protected $eadToken;
/**
* @var Object
*/
protected $dataTokens;
/**
* @var Array
*/
protected $services = [];
/**
* @var SessionInterface
*/
protected $sessionSym;
/**
* Constructor
*
* @param ContainerInterface $container
*/
public function __construct(
ContainerInterface $container,
RequestStack $requestStack,
UrlGeneratorInterface $router,
SessionInterface $sessionSym
)
{
$this->container = $container;
$this->requestStack = $requestStack;
$this->router = $router;
$this->sessionSym = $sessionSym;
$this->eadToken = $this->container->getParameter('ead-token');
$this->dataTokens = json_decode($this->container->getParameter('ead-services'));
}
public function isSandbox()
{
return ($this->eadToken['sandbox'] == ServicesEnum::YES);
}
public function isDev()
{
return $this->container->getParameter('kernel.environment') == "dev";
}
public function getSessionSym()
{
return $this->sessionSym;
}
public function getTokenCron()
{
return $this->container->getParameter('ead-cron');
}
public function getServiceAccess(int $serviceType, ?int $sandbox = ServicesEnum::NO)
{
$keyService = "{$serviceType}{$sandbox}";
if(!empty($this->services[$keyService])){
return $this->services[$keyService];
}
if($this->isSandbox()){
$sandbox = ServicesEnum::YES;
}
$mainServices = [
ServicesEnum::IP_API,
ServicesEnum::RDSTATION,
ServicesEnum::LOGIN,
ServicesEnum::BLING,
];
if($serviceType == ServicesEnum::AWS_SECRET){
$this->services[$keyService] = json_decode(
$this->container->getParameter('ead-sget')
);
return $this->services[$keyService];
}
if($sandbox != ServicesEnum::YES || $serviceType == ServicesEnum::MEET){
if($serviceType == ServicesEnum::AWS_DYNAMODB_GET){
$this->services[$keyService] = json_decode(
$this->container->getParameter('ead-dget')
);
return $this->services[$keyService];
}
if(!in_array($serviceType, $mainServices)){
$serviceSecretId = ServicesEnum::SERVICES_NAME[$serviceType];
$serviceSecretId = "{$serviceSecretId}/production";
$awsSecretsManager = $this->getService("Aws\\AwsSecretsManager");
$info = $awsSecretsManager->getServiceInfo($serviceSecretId);
if(!empty($info)){
$this->services[$keyService] = $info;
return $this->services[$keyService];
}
}
}
if(!empty($this->dataTokens)){
if(isset($this->dataTokens->{$serviceType})){
return $this->dataTokens->{$serviceType};
}
}
throw new \Exception("Token not found for service: {$serviceType}");
return;
}
public function getUserFromEADAdmin(
string $email,
string $password,
string $clientId,
string $ip,
string $userAgent,
string $host,
?bool $json = false
)
{
$info = $this->getServiceAccess(ServicesEnum::LOGIN);
$data = [
"action" => "user",
"email" => $email,
"password" => $password,
"cliente_id" => $clientId,
"userAgent" => $userAgent,
"host" => $host,
"ip" => $ip,
];
$data = http_build_query($data);
$url = "https://eadmin.eadplataforma.com/modulos/api/?{$data}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Token token="' . $info->token . '"'
]);
$response = curl_exec($ch);
curl_close($ch);
if (!$json){
$response = json_decode($response, true);
if($this->isDev()){
$discordService = $this->getService('DiscordService');
$discordService->setChannel('debug-login');
$discordService->setMessage(json_encode($data));
$discordService->sendDiscord();
if(isset($response['usuario_id'])){
$discordService->setMessage($response['usuario_id']);
$discordService->sendDiscord();
}else if(isset($response['message'])){
$discordService->setMessage($response['message']);
$discordService->sendDiscord();
}
}
}
return $response;
}
public function getUserFromEADAdminByID(
string $userId,
string $clientId,
string $ip,
string $userAgent,
string $host,
?bool $json = false
)
{
$info = $this->getServiceAccess(ServicesEnum::LOGIN);
$data = [
"action" => "userById",
"userId" => $userId,
"cliente_id" => $clientId,
"userAgent" => $userAgent,
"host" => $host,
"ip" => $ip,
];
$data = http_build_query($data);
$url = "https://eadmin.eadplataforma.com/modulos/api/?{$data}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Token token="' . $info->token . '"'
]);
$response = curl_exec($ch);
curl_close($ch);
if (!$json){
$response = json_decode($response, true);
if($this->isDev()){
$discordService = $this->getService('DiscordService');
$discordService->setChannel('debug-login');
$discordService->setMessage(json_encode($data));
$discordService->sendDiscord();
if(isset($response['usuario_id'])){
$discordService->setMessage($response['usuario_id']);
$discordService->sendDiscord();
}else if(isset($response['message'])){
$discordService->setMessage($response['message']);
$discordService->sendDiscord();
}
}
}
return $response;
}
public function getContainer()
{
return $this->container;
}
public function getRequest()
{
return $this->requestStack->getCurrentRequest();
}
public function getClientIp()
{
$request = $this->getRequest();
if($request){
return $request->getClientIp();
}
return;
}
public function getHost()
{
$request = $this->getRequest();
if($request){
return $request->getHost();
}
return;
}
public function getRouter()
{
return $this->router;
}
public function getPath()
{
return $this->container->getParameter('kernel.project_dir');
}
public function getPublicPath()
{
return "{$this->getPath()}/public/";
}
public function getAssetsPath()
{
return "{$this->getPath()}/assets/";
}
public function getService(string $serviceName)
{
$service = $this->container->get("EADPlataforma\Services\\{$serviceName}");
return $service;
}
public function getUtil(string $utilName)
{
$util = $this->container->get("EADPlataforma\Util\\{$utilName}");
return $util;
}
public function getSignatureHash(string $value)
{
return hash_hmac('sha256', $value, $this->getTokenCron());
}
public function signData(string $value)
{
$signature = $this->getSignatureHash($value);
return "{$value}.ead.{$signature}";
}
public function signDataWithExpiration(string $value, int $expirationTime = 30)
{
$expires = time() + $expirationTime;
$signature = $this->getSignatureHash("{$value}.ead.{$expires}");
return "{$value}.ead.{$expires}.ead.{$signature}";
}
public function verifySignedDataExpire(string $hash)
{
try{
list($value, $expires, $signature) = explode('.ead.', $hash, 3);
if(time() >= $expires){
return false;
}
$valid = hash_equals($this->getSignatureHash("{$value}.ead.{$expires}"), $signature);
return $valid ? $value : false;
}catch(\Exception $e){
}
return false;
}
public function verifySignedData(string $hash)
{
try{
list($value, $signature) = explode('.ead.', $hash, 2);
return hash_equals($this->getSignatureHash($value), $signature) ? $value : false;
}catch(\Exception $e){
}
return false;
}
public function setCookieSign(string $cookieName, string $value, ?int $time = null)
{
$cookieValue = $this->signData($value);
$cookieName = "edp_{$cookieName}";
$request = $this->requestStack->getCurrentRequest();
$host = $request->headers->get('host');
$options = [
"expires" => $time,
"path" => "/",
"domain" => $host,
"secure" => true,
"httponly" => true,
"samesite" => "Lax",
];
if(in_array($host, ServicesEnum::DOMAIN_DEV)){
setcookie($cookieName, $cookieValue, $time, '/', $host);
return;
}
setcookie(
$cookieName,
$cookieValue,
$options
);
return;
}
function verifySignedCookie(string $cookieName): bool
{
$cookieName = "edp_{$cookieName}";
$request = $this->requestStack->getCurrentRequest();
$cookies = $request->cookies;
if(!$cookies->has($cookieName)){
return false;
}
return $this->verifySignedData($cookies->get($cookieName));
}
public function setCookie($cookieName, $value, $time = null, ?bool $useMd5 = true)
{
if($useMd5){
$cookieName = md5($cookieName);
}
$cookieName = "edp_{$cookieName}";
$request = $this->requestStack->getCurrentRequest();
$host = $request->headers->get('host');
if(empty($time)){
$time = time() + (10 * 365 * 24 * 60 * 60);
}
$options = [
"expires" => $time,
"path" => "/",
"domain" => $host,
"secure" => true,
"httponly" => true,
"samesite" => "Lax",
];
if(in_array($host, ServicesEnum::DOMAIN_DEV)){
setcookie($cookieName, $value, $time, '/', $host);
return;
}
setcookie($cookieName, $value, $options);
return;
}
public function getCookie($cookieName, ?bool $useMd5 = true)
{
if($useMd5){
$cookieName = md5($cookieName);
}
$cookieName = "edp_{$cookieName}";
$request = $this->requestStack->getCurrentRequest();
$cookies = $request->cookies;
if($cookies->has($cookieName)){
return $cookies->get($cookieName);
}
return;
}
public function deleteCookie($cookieName, ?bool $useMd5 = true)
{
if($useMd5){
$cookieName = md5($cookieName);
}
$cookieName = "edp_{$cookieName}";
$request = $this->requestStack->getCurrentRequest();
$host = $request->headers->get('host');
setcookie($cookieName, null, -1, '/', $host);
}
public function getCookieHashIdentify()
{
$cookieName = 'hashcartoff';
$hashIdentify = $this->getCookie($cookieName);
if(empty($hashIdentify)){
$hashIdentify = md5(rand() . strtotime(date('Y-m-d H:i:s')));
$hashIdentify .= md5(rand() . password_hash($hashIdentify, PASSWORD_DEFAULT));
$this->setCookie($cookieName, $hashIdentify);
}
return $hashIdentify;
}
public function generateUrl(string $routeName, ?array $params = [])
{
return $this->router->generate($routeName, (!empty($params) ? $params : []));
}
public function logoffWS(Session $session, string $clientId)
{
$url = "https://metrics.eadplataforma.app/api/users/token/invalidate";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, 50);
$headers = [
"Content-Type: application/json",
"Authorization: {$this->getTokenCron()}",
];
$userToken = md5($clientId) . md5($session->getId() . $session->getToken());
$data = [
"token" => $userToken,
];
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
return;
}
}