src/CmsBundle/EventListener/SecurityListener.php line 52

Open in your IDE?
  1. <?php
  2. namespace App\CmsBundle\EventListener;
  3. use App\CmsBundle\Entity\Ipcheck;
  4. use Symfony\Component\HttpKernel\Kernel;
  5. use Doctrine\ORM\EntityManager;
  6. use Symfony\Component\Security\Core\Authentication\Token\Storage\UsageTrackingTokenStorage;
  7. use Symfony\Component\HttpFoundation\Session\Session;
  8. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  9. use Symfony\Component\HttpFoundation\RequestStack;
  10. use Symfony\Component\DependencyInjection\ContainerInterface;
  11. use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
  12. use App\CmsBundle\Entity\Log;
  13. use GeoIp2\Database\Reader;
  14. class SecurityListener
  15. {
  16.     private $em              null;
  17.     private $security        null;
  18.     private $session         null;
  19.     private $kernel          null;
  20.     private $requestStack    null;
  21.     private $container       null;
  22.     private $translator      null;
  23.     private $GeoIPDB      null;
  24.     
  25.     private $version         null;
  26.     private $git_hash        null;
  27.     private $git_hash_long   null;
  28.     private $date            null;
  29.     private $prev_version    null;
  30.     
  31.     private $cooldown 'U bent tijdelijk geblokkeerd vanwege herhaaldelijk onjuist inloggen. Probeer het later opnieuw.';
  32.     private $blocked 'Je bent geblokkeerd, neem contact op met de applicatieleverancier.';
  33.    public function __construct(EntityManager $entityManagerUsageTrackingTokenStorage $securitySession $session\App\Kernel $kernelRequestStack $requestStackContainerInterface $container$translator)
  34.    {
  35.       $this->em       $entityManager;
  36.       $this->security $security;
  37.       $this->session  $session;
  38.       $this->kernel  $kernel;
  39.       $this->requestStack  $requestStack;
  40.       $this->container  $container;
  41.       $this->translator   $translator;
  42.       $this->GeoIPDB = new Reader('../src/CmsBundle/GeoLite2-City.mmdb');
  43.    }
  44.     public function onAuthenticationFailureAuthenticationFailureEvent $event )
  45.     {
  46.         $request $this->requestStack->getCurrentRequest();
  47.         $authDir $this->kernel->getProjectDir() . '/var/auth/';
  48.         if(!file_exists($authDir)){ mkdir($authDir); }
  49.         $Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy([], ['id' => 'asc']);
  50.         $errorKey $event->getAuthenticationException()->getMessageKey();
  51.         if(file_exists($authDir)){
  52.             $ip $request->getClientIp();
  53.             $_credentials $event->getAuthenticationToken()->getCredentials();
  54.             if (isset($_credentials['username']) && !empty($_credentials['username'])) {
  55.                 $username $_credentials['username'];
  56.             } else {
  57.                 $username 'unknown';
  58.             }
  59.             // Whitelist IP's in .ip file
  60.             $whitelist false;
  61.             $ipFile str_replace('/src/CmsBundle/EventListener''/.ip'__DIR__);
  62.             if(file_exists($ipFile)){
  63.                 $ip_list file($ipFile);
  64.                 foreach($ip_list as $ip_entry){
  65.                     $ip_entry explode(':'trim($ip_entry));
  66.                     $ip_entry trim($ip_entry[0]);
  67.                     if($ip == $ip_entry){
  68.                         $whitelist true;
  69.                         break;
  70.                     }
  71.                 }
  72.             }
  73.             // Whitelist IP's in .whitelist file
  74.             $whitelist false;
  75.             $ipFile str_replace('/src/CmsBundle/EventListener''/.whitelist'__DIR__);
  76.             if(file_exists($ipFile)){
  77.                 $ip_list file($ipFile);
  78.                 foreach($ip_list as $ip_entry){
  79.                     $ip_entry trim($ip_entry);
  80.                     if($ip == $ip_entry){
  81.                         $whitelist true;
  82.                         break;
  83.                     }
  84.                 }
  85.             }
  86.             
  87.             if($whitelist){
  88.                 // IP is whitelisted
  89.                 $Ipcheck $this->em->getRepository(Ipcheck::class)->findOneBy(['user_attempt' => $username'ip' => $ip]);
  90.                 if($Ipcheck){
  91.                     // Remove existing entry
  92.                     $this->em->remove($Ipcheck);
  93.                     $this->em->flush();
  94.                 }
  95.                 $Syslog = new Log();
  96.                 $Syslog->setAction('login');
  97.                 $Syslog->setType('auth');
  98.                 $Syslog->setStatus('failure');
  99.                 $Syslog->setMessage('Foutieve inlog met gebruikersnaam, IP op whitelist.');
  100.                 $Syslog->setSettings($Settings);
  101.                 $this->em->persist($Syslog);
  102.                 if($Settings->getIntegrations()){ $Settings->getIntegrations()->sendTelegram($Settings->getLabel() . ': Foutieve inlog met gebruikersnaam, IP op whitelist. Gebruikersnaam: "' $username '"'); }
  103.                 $this->session->getFlashBag()->add(
  104.                     'error',
  105.                     $this->translator->trans('Gebruikersnaam en/of wachtwoord is onjuist.', [], 'security')
  106.                 );
  107.             }else{
  108.                 $is_admin = (empty($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], '/admin') !== false true false);
  109.                 if($is_admin){
  110.                 // $User = $this->em->getRepository('CmsBundle:User')->findOneByUsername($username);
  111.                 // if($User){
  112.                     $Ipcheck $this->em->getRepository(Ipcheck::class)->findOneBy(['user_attempt' => $username'ip' => $ip]);
  113.                     if(empty($Ipcheck)){
  114.                         $Ipcheck = new Ipcheck();
  115.                         $Ipcheck->setIp($ip);
  116.                         $Ipcheck->setBlocked(false);
  117.                         if($ip != '127.0.0.1'){
  118.                             try{
  119.                                 $client_ip $this->GeoIPDB->city($ip);
  120.                                 $client_country $client_ip->country->isoCode;
  121.                                 $Ipcheck->setCountry($client_country);
  122.                             }catch(\GeoIp2\Exception\AddressNotFoundException $e){}
  123.                         }
  124.                     }
  125.                     try{
  126.                         $datetime1 $Ipcheck->getLoginLastAttempt();
  127.                         if(!empty($datetime1)){
  128.                             $datetime2 = new \DateTime();
  129.                             $interval $datetime1->diff($datetime2);
  130.                             $min $interval->format('%i');
  131.                         }else{
  132.                             $min 0;
  133.                         }
  134.                     }catch(\Exception $e){
  135.                         $min 0;
  136.                     }
  137.                     $Ipcheck->setLoginAttempts($Ipcheck->getLoginAttempts() + 1);
  138.                     // $Ipcheck->setLoginLastAttempt(new \DateTime());
  139.                     if(preg_match('/\w+/'$username)){
  140.                         $Ipcheck->setUserAttempt($username);
  141.                     }else{
  142.                         $Ipcheck->setUserAttempt('unknown: ' $username);
  143.                     }
  144.                     // $User->setIpCheck($Ipcheck);
  145.                     $this->em->persist($Ipcheck);
  146.                     $this->em->flush();
  147.                     // Last invalid login was less then 15 minutes ago, check if it has 5 failed attempts
  148.                     if($Ipcheck->getLoginAttempts() >= 5){
  149.                         if($min >= 15){
  150.                             // Cooldown period is over, restart 5 attempts, with 1 attempt directly used (4 to go before next cooldown)
  151.                             $Ipcheck->setLoginAttempts(1);
  152.                             $Ipcheck->setLoginLastAttempt(new \DateTime());
  153.                             $this->em->persist($Ipcheck);
  154.                             $this->em->flush();
  155.                             $this->session->getFlashBag()->add(
  156.                                 'error',
  157.                                 $this->translator->trans('Gebruikersnaam en/of wachtwoord is onjuist.', [], 'security')
  158.                             );
  159.                         }else{
  160.                             $response = new \Symfony\Component\HttpFoundation\RedirectResponse($this->container->get('router')->generate('admin_login') . '?cooldown=1');
  161.                             $this->security->setToken(null);
  162.                             $this->session->invalidate();
  163.                             // $sec = $interval->format('%s');
  164.                             // $dev = ($this->kernel->getEnvironment() == 'dev');
  165.                             $this->session->getFlashBag()->add(
  166.                                 'error',
  167.                                 ($Ipcheck->getBlocked() ? $this->blocked $this->cooldown)
  168.                             );
  169.                             $Syslog = new Log();
  170.                             $Syslog->setAction('login');
  171.                             $Syslog->setUsername($username);
  172.                             $Syslog->setType('blocked');
  173.                             $Syslog->setPriority(1);
  174.                             $Syslog->setMessage('Meer dan 5 pogingen, vervolg pogingen zijn geblokkeerd.');
  175.                             $Syslog->setSettings($Settings);
  176.                             $this->em->persist($Syslog);
  177.                             $this->em->flush();
  178.                             if($Settings->getIntegrations()){ $Settings->getIntegrations()->sendTelegram($Settings->getLabel() . ': Meer dan 5 pogingen, vervolg pogingen zijn geblokkeerd. Gebruikersnaam: "' $username '"'); }
  179.                             return $response;
  180.                         }
  181.                     }else{
  182.                         $Syslog = new Log();
  183.                         $Syslog->setAction('login');
  184.                         $Syslog->setUsername($username);
  185.                         $Syslog->setType('auth');
  186.                         $Syslog->setStatus('failure');
  187.                         $Syslog->setMessage('Foutieve inlog met gebruikersnaam.');
  188.                         $Syslog->setSettings($Settings);
  189.                         $this->em->persist($Syslog);
  190.                         $this->em->flush();
  191.                         if($Settings->getIntegrations()){ $Settings->getIntegrations()->sendTelegram($Settings->getLabel() . ': Foutieve inlog met gebruikersnaam: "' $username '"'); }
  192.                         $this->session->getFlashBag()->add(
  193.                             'error',
  194.                             $this->translator->trans('Gebruikersnaam en/of wachtwoord is onjuist.', [], 'security')
  195.                         );
  196.                     }
  197.                     // dump($ip);
  198.                     // dump($username);
  199.                 // }
  200.                 }else{
  201.                     $this->session->getFlashBag()->add(
  202.                         'error',
  203.                         $this->translator->trans('Gebruikersnaam en/of wachtwoord is onjuist.', [], 'security')
  204.                     );
  205.                 }
  206.                 $errorLine = [
  207.                     '[' date('Y-m-d H:i:s') . ']',
  208.                     $ip,
  209.                     $username,
  210.                     $errorKey,
  211.                 ];
  212.                 $errorLine implode(' | '$errorLine) . "\n";
  213.                 file_put_contents($authDir $username$errorLineFILE_APPEND);
  214.             }
  215.             /*if(file_exists($authDir . $username)){
  216.                 file_put_contents($errorLine, $authDir . $username, FILE_APPEND);
  217.             }else{
  218.                 echo ( '<pre>' . print_r( '??', 1 ) . '</pre>' );
  219.                 file_put_contents($errorLine, $authDir . $username);
  220.             }*/
  221.             // die( "<pre>" . print_r( $errorLine, 1 ) . "</pre>" );
  222.             // dump($request->getParameter('_username'));die();
  223.         }else{
  224.             $this->session->getFlashBag()->add(
  225.                 'error',
  226.                 $this->translator->trans('Gebruikersnaam en/of wachtwoord is onjuist.', [], 'security')
  227.             );
  228.         }
  229.         // die();
  230.     }
  231.     public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
  232.     {
  233.         $request $request $this->requestStack->getCurrentRequest();
  234.         $Settings $this->em->getRepository('CmsBundle:Settings')->findOneBy([], ['id' => 'asc']);
  235.         $User $this->security->getToken()->getUser();
  236.         $username $event->getAuthenticationToken()->getUsername();
  237.         if(empty($username)){
  238.             $username 'unknown';
  239.         }
  240.         $is_admin = (empty($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], '/admin') !== false true false);
  241.         if(!$is_admin){
  242.             if($User->getUsername() == 'admin'){
  243.                 $response = new \Symfony\Component\HttpFoundation\RedirectResponse($this->container->get('router')->generate('admin_login') . '?cooldown=1');
  244.                 $this->security->setToken(null);
  245.                 $this->session->invalidate();
  246.                 return $response;
  247.             }
  248.         }
  249.         $ip $request->getClientIp();
  250.         $Ipcheck $this->em->getRepository(Ipcheck::class)->findOneBy(['user_attempt' => $username'ip' => $ip]);
  251.         // Whitelist IP's in .ip file
  252.         $whitelist false;
  253.         $ipFile str_replace('/src/CmsBundle/EventListener''/.ip'__DIR__);
  254.         if(file_exists($ipFile)){
  255.             $ip_list file($ipFile);
  256.             foreach($ip_list as $ip_entry){
  257.                 $ip_entry explode(':'trim($ip_entry));
  258.                 $ip_entry trim($ip_entry[0]);
  259.                 if($ip == $ip_entry){
  260.                     $whitelist true;
  261.                     break;
  262.                 }
  263.             }
  264.         }
  265.         // Whitelist IP's in .whitelist file
  266.         $whitelist false;
  267.         $ipFile str_replace('/src/CmsBundle/EventListener''/.whitelist'__DIR__);
  268.         if(file_exists($ipFile)){
  269.             $ip_list file($ipFile);
  270.             foreach($ip_list as $ip_entry){
  271.                 $ip_entry trim($ip_entry);
  272.                 if($ip == $ip_entry){
  273.                     $whitelist true;
  274.                     break;
  275.                 }
  276.             }
  277.         }
  278.         
  279.         if($whitelist){
  280.             // IP is whitelisted
  281.             if($Ipcheck){
  282.                 // Remove existing entry
  283.                 $this->em->remove($Ipcheck);
  284.                 $this->em->flush();
  285.             }
  286.         }else{
  287.             $is_admin = (empty($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], '/admin') !== false true false);
  288.             /**
  289.              COOLDOWN
  290.              */
  291.             if($is_admin && $Ipcheck && $Ipcheck->getLoginAttempts() >= 5){
  292.                 $datetime1 $Ipcheck->getLoginLastAttempt();
  293.                 $datetime2 = new \DateTime();
  294.                 $interval $datetime1->diff($datetime2);
  295.                 $min $interval->format('%i');
  296.                 if((float)$min >= 15){
  297.                     // Cooldown of 15 minutes is gone, reset.
  298.                     $this->em->remove($Ipcheck);
  299.                     $this->em->flush();
  300.                 }else{
  301.                     // Still in cooldown, return error
  302.                     $response = new \Symfony\Component\HttpFoundation\RedirectResponse($this->container->get('router')->generate('admin_login') . '?cooldown=1');
  303.                     $this->security->setToken(null);
  304.                     $this->session->invalidate();
  305.                     $this->session->getFlashBag()->add(
  306.                         'error',
  307.                         ($Ipcheck->getBlocked() ? $this->blocked $this->cooldown)
  308.                     );
  309.                     return $response;
  310.                 }
  311.             }
  312.         }
  313.         /**
  314.          ACCOUNT IS EXPIRED
  315.          */
  316.         if($User->getExpire()){
  317.             $d = new \DateTime();
  318.             if($User->getExpireDate()->format('Ymd') <= $d->format('Ymd')){
  319.                 $response = new \Symfony\Component\HttpFoundation\RedirectResponse($this->container->get('router')->generate('admin_login') . '?expired=1');
  320.                 $this->security->setToken(null);
  321.                 $this->session->invalidate();
  322.                 $this->session->getFlashBag()->add(
  323.                     'warning',
  324.                     'Your account has expired.'
  325.                 );
  326.                 $Syslog = new Log();
  327.                 $Syslog->setAction('login');
  328.                 $Syslog->setUser($User);
  329.                 $Syslog->setUsername($username);
  330.                 $Syslog->setType('auth');
  331.                 $Syslog->setStatus('expired');
  332.                 $Syslog->setMessage('Succesvolle login met verlopen account.');
  333.                 $Syslog->setSettings($Settings);
  334.                 $this->em->persist($Syslog);
  335.                 $this->em->flush();
  336.                 if($Settings->getIntegrations()){ $Settings->getIntegrations()->sendTelegram($Settings->getLabel() . ': Succesvolle login met verlopen account. Gebruikersnaam: "' $username '"'); }
  337.                 return $response;
  338.             }
  339.         }
  340.         /**
  341.          * PASSWORD IS EXPIRED
  342.          */
  343.         if($User->getExpirePasswordEnable()){
  344.             $d = new \DateTime();
  345.             if ($User->getExpirePasswordDate()->format('Ymd') <= $d->format('Ymd')) {
  346.                 $response = new \Symfony\Component\HttpFoundation\RedirectResponse($this->container->get('router')->generate('admin_login') . '?passwordexpired=1');
  347.                 $this->security->setToken(null);
  348.                 $this->session->invalidate();
  349.                 $this->session->getFlashBag()->add(
  350.                     'warning',
  351.                     'Je wachtwoord is verlopen.<br/><a href="/admin/lostpassword?expired=1">Verander wachtwoord</a>'
  352.                 );
  353.                 $Syslog = new Log();
  354.                 $Syslog->setAction('login');
  355.                 $Syslog->setUser($User);
  356.                 $Syslog->setUsername($username);
  357.                 $Syslog->setType('auth');
  358.                 $Syslog->setStatus('expired');
  359.                 $Syslog->setMessage('Wachtwoord is verlopen.');
  360.                 $Syslog->setSettings($Settings);
  361.                 $this->em->persist($Syslog);
  362.                 $this->em->flush();
  363.                 if($Settings->getIntegrations()){ $Settings->getIntegrations()->sendTelegram($Settings->getLabel() . ': Wachtwoord is verlopen. Gebruikersnaam: "' $username '"'); }
  364.                 return $response;
  365.             }
  366.             $expireDate $User->getExpirePasswordDate();
  367.             $expireDate->modify('-1 month');
  368.             if ($User->getExpirePasswordDate()->format('Ymd') <= $d->format('Ymd')) {
  369.                 $this->session->getFlashBag()->add(
  370.                     'warning',
  371.                     'Uw wachtwoord verloopt op: ' $User->getExpirePasswordDate()->format('d-m-Y')
  372.                 );
  373.             }
  374.         }
  375.         /*$validCaptcha = $Settings->validateGoogleRecaptcha($request->request->get('g-recaptcha-response'));
  376.         if(!$validCaptcha){
  377.             $response = new \Symfony\Component\HttpFoundation\RedirectResponse($this->container->get('router')->generate('admin_login') . '?expired=1');
  378.             $this->security->setToken(null);
  379.             $this->session->invalidate();
  380.             $this->session->getFlashBag()->add(
  381.                 'warning',
  382.                 'Ongeldige captcha.'
  383.             );
  384.             return $response;
  385.         }*/
  386.         /**
  387.          RESET LOGIN ATTEMPTS
  388.          */
  389.         if(!empty($Ipcheck)){
  390.             $Ipcheck->setLoginAttempts(0);
  391.             $this->em->persist($Ipcheck);
  392.             $this->em->flush();
  393.         }
  394.         $symfony_version \Symfony\Component\HttpKernel\Kernel::VERSION;
  395.         $target $this->container->getParameter('trinity_cc_server') . '/';
  396.         $target_clean preg_replace('/^http(s)?:\/\//'''$target);
  397.         $authKey $Settings->getCcAuthKey();
  398.         $versionFile $this->kernel->getProjectDir() . '/src/CmsBundle/VERSION';
  399.         if (file_exists($versionFile)) {
  400.             $versionEntries file($versionFile);
  401.             $this->version         trim($versionEntries[0]);
  402.             $this->git_hash        trim($versionEntries[1]);
  403.             $this->git_hash_long   trim($versionEntries[2]);
  404.             $this->date            trim($versionEntries[3]);
  405.             $this->prev_version    trim($versionEntries[4]);
  406.             /*foreach(file($versionFile) as $ln){
  407.                 $ln = trim($ln);
  408.                 dump($ln);
  409.             }*/
  410.         }
  411.         $bundleList = [];
  412.         $bundleDir $this->kernel->getProjectDir() . '/src/Trinity/';
  413.         foreach(scandir($bundleDir) as $d){
  414.             $path $bundleDir $d;
  415.             if(is_dir($path) && !in_array($d, ['.''..'])){
  416.                 $version '';
  417.                 if(file_exists($path '/VERSION')){
  418.                     $versionEntries file($path '/VERSION');
  419.                     if(!empty($versionEntries)){
  420.                         $version = [
  421.                             'version'        => trim($versionEntries[0]),
  422.                             'git_hash'       => trim($versionEntries[1]),
  423.                             'git_hash_long'  => trim($versionEntries[2]),
  424.                             'date'           => trim($versionEntries[3]),
  425.                             'date'           => trim($versionEntries[3]),
  426.                         ];
  427.                     }
  428.                 }
  429.                 $bundleList[$d] = [
  430.                     'path' => $path,
  431.                     'version' => $version,
  432.                 ];
  433.             }
  434.         }
  435.         $Syslog = new Log();
  436.         $Syslog->setAction('login');
  437.         $Syslog->setUser($User);
  438.         $Syslog->setUsername($username);
  439.         $Syslog->setType('auth');
  440.         $Syslog->setStatus('success');
  441.         $Syslog->setMessage('Succesvol ingelogd.');
  442.         $Syslog->setSettings($Settings);
  443.         $this->em->persist($Syslog);
  444.         $this->em->flush();
  445.         if($Settings->getIntegrations()){ 
  446.             $Settings->getIntegrations()->sendTelegram($Settings->getLabel() . ': Succesvol ingelogd. Gebruikersnaam: "' $username '"'); 
  447.         }
  448.         $installed $this->container->getParameter('kernel.bundles');
  449.         if(array_key_exists('TrinityWebshopBundle',  $installed) && $User){
  450.             $WebshopUser $this->em->getRepository('TrinityWebshopBundle:User')->findOneByUser($User);
  451.             $cartId $request->getSession()->get('cart');
  452.             if($WebshopUser && $WebshopUser->getType() == && $WebshopUser->getIsApproved() && !empty($cartId)){
  453.                 $Cart $this->em->getRepository('TrinityWebshopBundle:Cart')->findOneBy(['id' => $cartId]);
  454.                 if(!empty($Cart)){
  455.                     foreach($Cart->getProducts() as $product){
  456.                         $this->em->remove($product);
  457.                     }
  458.                     $this->em->flush();
  459.                 }
  460.             }
  461.         }
  462.         if($User && $request->getHost() != $target_clean){
  463.             $domain $request->getHost();
  464.             $client_data = [
  465.                 'domain'          => $domain,
  466.                 'uri'             => $request->get('uri') ?? '/',
  467.                 'hostname'        => '',
  468.                 'serverip'        => $_SERVER['SERVER_ADDR'],
  469.                 'datetime'        => date('Y-m-d H:i:s'),
  470.                 'version'         => $this->version,
  471.                 'symfony_version' => $symfony_version,
  472.                 'username'        => $User->getUsername(),
  473.                 'title'           => $Settings->getLabel(),
  474.                 'matomo_url'      => $Settings->getPiwikUrl(),
  475.                 'matomo_hash'     => $Settings->getPiwikApiHash(),
  476.                 'userip'          => $_SERVER['REMOTE_ADDR'],
  477.                 'bundleList'      => $bundleList,
  478.             ];
  479.             if(empty($Settings->getCcAuthKey())){
  480.                 // No key yet, request key from server using /connect endpoint
  481.                 $curl curl_init();
  482.                 curl_setopt_array($curl, [
  483.                     CURLOPT_URL => $target 'api/connect?domain=' urlencode($domain) . '&version=' urlencode($this->version),
  484.                     CURLOPT_RETURNTRANSFER => true,
  485.                     CURLOPT_FOLLOWLOCATION => true,
  486.                     CURLOPT_CUSTOMREQUEST => 'GET',
  487.                 ]);
  488.                 $response curl_exec($curl);
  489.                 if(!empty($response) && $response json_decode($responsetrue)){
  490.                     if(!empty($response['token'])){
  491.                         $Settings->setCcAuthKey($response['token']);
  492.                         $this->em->persist($Settings);
  493.                         $this->em->flush();
  494.                     }
  495.                 }
  496.                 
  497.                 curl_close($curl);
  498.             }
  499.             if(!empty($Settings->getCcAuthKey())){
  500.                 // Send data to server
  501.                 $curl curl_init();
  502.                 curl_setopt_array($curl, [
  503.                     CURLOPT_URL => $target 'api/inbound',
  504.                     CURLOPT_RETURNTRANSFER => true,
  505.                     CURLOPT_FOLLOWLOCATION => true,
  506.                     CURLOPT_CUSTOMREQUEST => 'POST',
  507.                     CURLOPT_POSTFIELDS => json_encode($client_data),
  508.                     CURLOPT_HTTPHEADER => [
  509.                         'Content-Type: application/json',
  510.                         'Authorization: Bearer ' $Settings->getCcAuthKey(),
  511.                     ],
  512.                 ]);
  513.                 $response curl_exec($curl);
  514.                 curl_close($curl);
  515.             }
  516.             /* $id      = '1_71cb7h9hd4m3k23ghpadk67ed8b663l8jcmb83hhhdk45';
  517.             if($Settings->getCcExpires()){
  518.                 $expiresIn = $Settings->getCcExpires()->getTimestamp() - time();
  519.                 $expiresInHours = (($expiresIn / 60) / 60);
  520.                 if($expiresInHours < 4){
  521.                     // Force expire in 4 hours
  522.                     $authKey = null;
  523.                 }
  524.             }
  525.             $key     = 'mp3mkk7lhh79cp4domebj8jgkeilk9nlef2dpi53p61hgf';
  526.             $payload = 'grant_type=client_credentials&client_id=' . $id . '&client_secret=' . $key;
  527.             $ch = curl_init();
  528.             curl_setopt($ch, CURLOPT_URL,$target . 'oauth/v2/token');
  529.             curl_setopt($ch, CURLOPT_POST, 1);
  530.             curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
  531.             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  532.             $server_response = json_decode(curl_exec ($ch), true);
  533.             curl_close ($ch);
  534.             if($server_response){
  535.                 if(!empty($server_response['access_token'])){
  536.                     $Settings->setCcExpires(new \DateTime(date('Y-m-d H:i:s', strtotime('+' . $server_response['expires_in'] . ' seconds'))));
  537.                     $Settings->setCcAuthKey($server_response['access_token']);
  538.                     if($Settings->hasLogo()){
  539.                         $this->em->persist($Settings);
  540.                         $this->em->flush();
  541.                     }
  542.                 }
  543.             } */
  544.             /* if($this->container->getParameter('kernel.environment') != 'dev'){
  545.                 $host = $this->requestStack->getCurrentRequest()->getHost();
  546.                 $isLocal = false;
  547.                 if(preg_match('/\.local/', $host)){
  548.                     $isLocal = true;
  549.                 }
  550.                 if($Settings->getCcAuthKey() && !$isLocal){
  551.                     $encrypt_method = "AES-256-CBC";
  552.                     $secret_key = '0XBD7DsyTqGQJJ';
  553.                     $secret_iv = 'sDRFpXBBy3q5rc';
  554.                     // hash
  555.                     $key = hash('sha256', $secret_key);
  556.                     // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
  557.                     $iv = substr(hash('sha256', $secret_iv), 0, 16);
  558.                     $TRC_client = $this->em->getRepository('TrinityApiBundle:Client')->findOneByLabel('TRC');
  559.                     if(empty($TRC_client)){
  560.                         $hash1 = substr(md5(openssl_random_pseudo_bytes(20)),-25) . substr(md5(openssl_random_pseudo_bytes(20)),-25);
  561.                         $hash2 = substr(md5(openssl_random_pseudo_bytes(20)),-25) . substr(md5(openssl_random_pseudo_bytes(20)),-25);
  562.                         $TRC_client = new \App\Trinity\ApiBundle\Entity\Client();
  563.                         $TRC_client->setLabel('TRC');
  564.                         $TRC_client->setRandomId($hash1);
  565.                         $TRC_client->setSecret($hash2);
  566.                         $grant_types = array(
  567.                             'authorization_code',
  568.                             'token',
  569.                             'client_credentials',
  570.                         );
  571.                         $TRC_client->setAllowedGrantTypes($grant_types);
  572.                         $this->em->persist($TRC_client);
  573.                         $this->em->flush();
  574.                     }
  575.                     $api_token = base64_encode(openssl_encrypt($TRC_client->getId() . '_' . $TRC_client->getRandomId(), $encrypt_method, $key, 0, $iv));
  576.                     $api_secret = base64_encode(openssl_encrypt($TRC_client->getSecret(), $encrypt_method, $key, 0, $iv));
  577.                     $client_data['api_token'] = $api_token;
  578.                     $client_data['api_secret'] = $api_secret;
  579.                     $ch = curl_init();
  580.                     curl_setopt($ch, CURLOPT_URL,$target . 'api/authorize');
  581.                     $headers = array(
  582.                         'Content-Type:application/x-www-form-urlencoded',
  583.                         'Authorization:Bearer ' . $Settings->getCcAuthKey()
  584.                     );
  585.                     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  586.                     curl_setopt($ch, CURLOPT_POST, 1);
  587.                     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($client_data));
  588.                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  589.                     $server_response_raw = curl_exec ($ch);
  590.                     $server_response = json_decode($server_response_raw);
  591.                     curl_close ($ch);
  592.                 }
  593.             } */
  594.         }
  595.     }
  596. }