Proyectos de Subversion LeadersLinked - Services

Rev

Rev 385 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Nullix\CryptoJsAes\CryptoJsAes;
use GeoIp2\Database\Reader as GeoIp2Reader;

use Laminas\Authentication\AuthenticationService;
use Laminas\Authentication\Result as AuthResult;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\JsonModel;


use LeadersLinked\Form\Auth\SigninForm;
use LeadersLinked\Form\Auth\ResetPasswordForm;
use LeadersLinked\Form\Auth\ForgotPasswordForm;
use LeadersLinked\Form\Auth\SignupForm;

use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Mapper\EmailTemplateMapper;
use LeadersLinked\Mapper\NetworkMapper;
use LeadersLinked\Mapper\UserMapper;

use LeadersLinked\Model\User;
use LeadersLinked\Model\UserType;
use LeadersLinked\Library\QueueEmail;
use LeadersLinked\Library\Functions;
use LeadersLinked\Model\EmailTemplate;
use LeadersLinked\Mapper\UserPasswordMapper;
use LeadersLinked\Model\UserBrowser;
use LeadersLinked\Mapper\UserBrowserMapper;
use LeadersLinked\Mapper\UserIpMapper;
use LeadersLinked\Model\UserIp;
use LeadersLinked\Form\Auth\MoodleForm;
use LeadersLinked\Library\Rsa;
use LeadersLinked\Library\Image;

use LeadersLinked\Authentication\AuthAdapter;
use LeadersLinked\Authentication\AuthEmailAdapter;

use LeadersLinked\Model\UserPassword;

use LeadersLinked\Model\Connection;
use LeadersLinked\Authentication\AuthImpersonateAdapter;
use LeadersLinked\Model\Network;
use LeadersLinked\Model\JwtToken;
use LeadersLinked\Mapper\JwtTokenMapper;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use LeadersLinked\Form\Auth\SigninDebugForm;
use LeadersLinked\Library\ExternalCredentials;
use LeadersLinked\Library\Storage;



class AuthController extends AbstractActionController
{

    
    /**
     *
     * @var \Laminas\Db\Adapter\AdapterInterface
     */
    private $adapter;
    
    /**
     *
     * @var \LeadersLinked\Cache\CacheInterface
     */
    private $cache;
    
    
    /**
     *
     * @var \Laminas\Log\LoggerInterface
     */
    private $logger;
    
    /**
     *
     * @var array
     */
    private $config;
    
    
    /**
     *
     * @var \Laminas\Mvc\I18n\Translator
     */
    private $translator;
    
    
    /**
     *
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
     * @param \LeadersLinked\Cache\CacheInterface $cache
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
     * @param array $config
     * @param \Laminas\Mvc\I18n\Translator $translator
     */
    public function __construct($adapter, $cache, $logger, $config, $translator)
    {
        $this->adapter      = $adapter;
        $this->cache        = $cache;
        $this->logger       = $logger;
        $this->config       = $config;
        $this->translator   = $translator;
    }

    public function signinAction()
    {
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork = $currentNetworkPlugin->getNetwork();

        $request = $this->getRequest();

        if ($request->isPost()) {
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
            $currentNetwork = $currentNetworkPlugin->getNetwork();
            
            $jwtToken = null;
            $headers = getallheaders();
            

            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
                
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
                
                
                if (substr($token, 0, 6 ) == 'Bearer') {
                    
                    $token = trim(substr($token, 7));
                    
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
                        $key = $this->config['leaderslinked.jwt.key'];
                        
                        
                        try {
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
                            
                            
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
                            }
                            
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
                            if(!$jwtToken) {
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
                            }

                        } catch(\Exception $e) {
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
                        }
                    } else {
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
                    }
                } else {
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
                }
            } else {
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
            }



            $form = new  SigninForm($this->config);
            $dataPost = $request->getPost()->toArray();

            if (empty($_SESSION['aes'])) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
                ]);
            }
            
            
            $aes = $_SESSION['aes'];
            unset( $_SESSION['aes'] );
            
            if (!empty($dataPost['email'])) {
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $aes);
            }


            if (!empty($dataPost['password'])) {
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $aes);
            }
            
            
            $form->setData($dataPost);

            if ($form->isValid()) {
                
                $dataPost = (array) $form->getData();
           

                $email      = $dataPost['email'];
                $password   = $dataPost['password'];
        
                
                
    

                $authAdapter = new AuthAdapter($this->adapter, $this->logger);
                $authAdapter->setData($email, $password, $currentNetwork->id);
                $authService = new AuthenticationService();

                $result = $authService->authenticate($authAdapter);

                if ($result->getCode() == AuthResult::SUCCESS) {

                    $identity = $result->getIdentity();
                    

                    $userMapper = UserMapper::getInstance($this->adapter);
                    $user = $userMapper->fetchOne($identity['user_id']);
                    
  
                    if($token) {
                        $jwtToken->user_id = $user->id;
                        $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                        $jwtTokenMapper->update($jwtToken);
                    }
                    

                    $navigator = get_browser(null, true);
                    $device_type    =  isset($navigator['device_type']) ? $navigator['device_type'] : '';
                    $platform       =  isset($navigator['platform']) ? $navigator['platform'] : '';
                    $browser        =  isset($navigator['browser']) ? $navigator['browser'] : '';


                    $istablet = isset($navigator['istablet']) ?  intval($navigator['istablet']) : 0;
                    $ismobiledevice = isset($navigator['ismobiledevice']) ? intval($navigator['ismobiledevice']) : 0;
                    $version = isset($navigator['version']) ? $navigator['version'] : '';


                    $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
                    $userBrowser = $userBrowserMapper->fetch($user->id, $device_type, $platform, $browser);
                    if ($userBrowser) {
                        $userBrowserMapper->update($userBrowser);
                    } else {
                        $userBrowser = new UserBrowser();
                        $userBrowser->user_id           = $user->id;
                        $userBrowser->browser           = $browser;
                        $userBrowser->platform          = $platform;
                        $userBrowser->device_type       = $device_type;
                        $userBrowser->is_tablet         = $istablet;
                        $userBrowser->is_mobile_device  = $ismobiledevice;
                        $userBrowser->version           = $version;

                        $userBrowserMapper->insert($userBrowser);
                    }
                    //

                    $ip = Functions::getUserIP();
                    $ip = $ip == '127.0.0.1' ? '148.240.211.148' : $ip;

                    $userIpMapper = UserIpMapper::getInstance($this->adapter);
                    $userIp = $userIpMapper->fetch($user->id, $ip);
                    if (empty($userIp)) {

                        if ($this->config['leaderslinked.runmode.sandbox']) {
                            $filename = $this->config['leaderslinked.geoip2.production_database'];
                        } else {
                            $filename = $this->config['leaderslinked.geoip2.sandbox_database'];
                        }

                        $reader = new GeoIp2Reader($filename); //GeoIP2-City.mmdb');
                        $record = $reader->city($ip);
                        if ($record) {
                            $userIp = new UserIp();
                            $userIp->user_id = $user->id;
                            $userIp->city = !empty($record->city->name) ? Functions::utf8_decode($record->city->name) : '';
                            $userIp->state_code = !empty($record->mostSpecificSubdivision->isoCode) ? Functions::utf8_decode($record->mostSpecificSubdivision->isoCode) : '';
                            $userIp->state_name = !empty($record->mostSpecificSubdivision->name) ? Functions::utf8_decode($record->mostSpecificSubdivision->name) : '';
                            $userIp->country_code = !empty($record->country->isoCode) ? Functions::utf8_decode($record->country->isoCode) : '';
                            $userIp->country_name = !empty($record->country->name) ? Functions::utf8_decode($record->country->name) : '';
                            $userIp->ip = $ip;
                            $userIp->latitude = !empty($record->location->latitude) ? $record->location->latitude : 0;
                            $userIp->longitude = !empty($record->location->longitude) ? $record->location->longitude : 0;
                            $userIp->postal_code = !empty($record->postal->code) ? $record->postal->code : '';

                            $userIpMapper->insert($userIp);
                        }
                    } else {
                        $userIpMapper->update($userIp);
                    }

                    /*
                    if ($remember) {
                        $expired = time() + 365 * 24 * 60 * 60;

                        $cookieEmail = new SetCookie('email', $email, $expired);
                    } else {
                        $expired = time() - 7200;
                        $cookieEmail = new SetCookie('email', '', $expired);
                    }


                    $response = $this->getResponse();
                    $response->getHeaders()->addHeader($cookieEmail);
                    */
                    
                    



                    $this->logger->info('Ingreso a LeadersLiked', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);

                    $user_share_invitation = $this->cache->getItem('user_share_invitation');

                    $url =  $this->url()->fromRoute('dashboard');
                    
                    if ($user_share_invitation && is_array($user_share_invitation)) {
                        
                        $content_uuid = $user_share_invitation['code'];
                        $content_type = $user_share_invitation['type'];
                        $content_user = $user_share_invitation['user'];
                        
                        
                        
                        $userRedirect = $userMapper->fetchOneByUuid($content_user);
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
                            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);

                            if ($connection) {

                                if ($connection->status != Connection::STATUS_ACCEPTED) {
                                    $connectionMapper->approve($connection);
                                }
                            } else {
                                $connection = new Connection();
                                $connection->request_from = $user->id;
                                $connection->request_to = $userRedirect->id;
                                $connection->status = Connection::STATUS_ACCEPTED;

                                $connectionMapper->insert($connection);
                            }
                        }
                        
                        if($content_type == 'feed') {
                            $url = $this->url()->fromRoute('dashboard', ['feed' => $content_uuid ]);
                            
                        }
                        else if($content_type == 'post') {
                            $url = $this->url()->fromRoute('post', ['id' => $content_uuid ]);
                        }
                        else {
                            $url = $this->url()->fromRoute('dashboard');
                        }
                        
                    }
                    
                    
                    $hostname = empty($_SERVER['HTTP_HOST']) ?  '' : $_SERVER['HTTP_HOST'];
                    
                    $networkMapper = NetworkMapper::getInstance($this->adapter);
                    $network = $networkMapper->fetchOneByHostnameForFrontend($hostname);
                    
                    if(!$network) {
                        $network = $networkMapper->fetchOneByDefault();
                    }
                    
                    $hostname = trim($network->main_hostname);
                    $url = 'https://' . $hostname . $url;

                    
                    $data = [
                        'redirect'  => $url,
                        'uuid'      => $user->uuid,
                    ];

                    
                  
                            
                    if($currentNetwork->xmpp_active) {
                        $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
                        $externalCredentials->getUserBy($user->id);
                        
                        
                        $data['xmpp_domain'] = $currentNetwork->xmpp_domain;
                        $data['xmpp_hostname'] = $currentNetwork->xmpp_hostname;
                        $data['xmpp_port'] = $currentNetwork->xmpp_port;
                        $data['xmpp_username'] = $externalCredentials->getUsernameXmpp();
                        $data['xmpp_pasword'] = $externalCredentials->getPasswordXmpp();
                        $data['inmail_username'] = $externalCredentials->getUsernameInmail();
                        $data['inmail_pasword'] = $externalCredentials->getPasswordInmail();

                                 }
                    
                    $data = [
                        'success'   => true,
                        'data'      => $data
                    ];
                    

                    $this->cache->removeItem('user_share_invitation');
                } else {

                    $message = $result->getMessages()[0];
                    if (!in_array($message, [
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
                        'ERROR_ENTERED_PASS_INCORRECT_1', 'ERROR_USER_REQUEST_ACCESS_IS_PENDING', 'ERROR_USER_REQUEST_ACCESS_IS_REJECTED'


                    ])) {
                    }

                    switch ($message) {
                        case 'ERROR_USER_NOT_FOUND':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
                            break;

                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
                            break;

                        case 'ERROR_USER_IS_BLOCKED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
                            break;

                        case 'ERROR_USER_IS_INACTIVE':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
                            break;


                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
                            break;


                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
                            break;


                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
                            break;


                        case 'ERROR_USER_REQUEST_ACCESS_IS_PENDING':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Falta verificar que pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
                            break;

                        case  'ERROR_USER_REQUEST_ACCESS_IS_REJECTED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Rechazado por no pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
                            break;


                        default:
                            $message = 'ERROR_UNKNOWN';
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
                            break;
                    }




                    $data = [
                        'success'   => false,
                        'data'   => $message
                    ];
                }

                return new JsonModel($data);
            } else {
                $messages = [];



                $form_messages = (array) $form->getMessages();
                foreach ($form_messages  as $fieldname => $field_messages) {

                    $messages[$fieldname] = array_values($field_messages);
                }

                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
            }
        } else if ($request->isGet()) {
            
            $aes = '';
            $jwtToken = null;
            $headers = getallheaders();
            
            
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
                
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
                
                
                if (substr($token, 0, 6 ) == 'Bearer') {
                    
                    $token = trim(substr($token, 7));
                    
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
                        $key = $this->config['leaderslinked.jwt.key'];
                        
                        
                        try {
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
                            
                            
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
                            }
                            
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
                        } catch(\Exception $e) {
                            //Token invalido
                        }
                    }
                }
            }
            
            if(!$jwtToken) {
            
                $aes = Functions::generatePassword(16);
                
                $jwtToken = new JwtToken();
                $jwtToken->aes = $aes;
                
                $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                if($jwtTokenMapper->insert($jwtToken)) {
                    $jwtToken = $jwtTokenMapper->fetchOne($jwtToken->id);
                }
                
                $token = '';
                
                if(!empty($this->config['leaderslinked.jwt.key'])) {
                    $issuedAt   = new \DateTimeImmutable();
                    $expire     = $issuedAt->modify('+365 days')->getTimestamp();
                    $serverName = $_SERVER['HTTP_HOST'];
                    $payload = [
                        'iat'  => $issuedAt->getTimestamp(),
                        'iss'  => $serverName,
                        'nbf'  => $issuedAt->getTimestamp(),
                        'exp'  => $expire,
                        'uuid' => $jwtToken->uuid,
                    ];
                    
   
                    $key = $this->config['leaderslinked.jwt.key'];
                    $token = JWT::encode($payload, $key, 'HS256');

                }
            } else {
                if(!$jwtToken->user_id) {
                    $aes = Functions::generatePassword(16);
                    $jwtToken->aes = $aes;
                    $jwtTokenMapper->update($jwtToken);
                }
            }
            
            
            
            
            


            if ($this->config['leaderslinked.runmode.sandbox']) {
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
            } else {
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
            }


            $access_usign_social_networks = $this->config['leaderslinked.runmode.access_usign_social_networks'];

            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
            if ($sandbox) {
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
            } else {
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
            }
            

            $parts = explode('.', $currentNetwork->main_hostname);
            if($parts[1] === 'com') {
                $replace_main = false;
            } else {
                $replace_main = true;
            }
            

                $storage = Storage::getInstance($this->config, $this->adapter);
                $path = $storage->getPathNetwork();
                
                if($currentNetwork->logo) {
                    $logo_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->logo);
                } else {
                    $logo_url = '';
                }
                
                if($currentNetwork->navbar) {
                    $navbar_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->navbar);
                } else {
                    $navbar_url = '';
                }
                
                if($currentNetwork->favico) {
                    $favico_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->favico);
                } else {
                    $favico_url = '';
                }
           

         

            $data = [
                'google_map_key'                => $google_map_key,
                'email'                         => '',
                'remember'                      => false,
                'site_key'                      => $site_key,
                'theme_id'                      => $currentNetwork->theme_id,
                'aes'                           => $aes,
                'jwt'                           => $token,
                'defaultNetwork'                => $currentNetwork->default,
                'access_usign_social_networks'  => $access_usign_social_networks && $currentNetwork->default == Network::DEFAULT_YES ? 'y' : 'n',
                'logo_url'                      => $logo_url,
                'navbar_url'                    => $navbar_url,
                'favico_url'                    => $favico_url,
                'intro'                         => $currentNetwork->intro ? $currentNetwork->intro : '',
                'is_logged_in'                  => $jwtToken->user_id ? true : false,

            ];
            
            if($currentNetwork->default == Network::DEFAULT_YES) {
                
   
                
                $currentUserPlugin = $this->plugin('currentUserPlugin');
                if ($currentUserPlugin->hasIdentity()) {
                    
                    
                    $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
                    $externalCredentials->getUserBy($currentUserPlugin->getUserId());
                    
       
                    if($currentNetwork->xmpp_active) {
                        $data['xmpp_domain']      = $currentNetwork->xmpp_domain;
                        $data['xmpp_hostname']    = $currentNetwork->xmpp_hostname;
                        $data['xmpp_port']        = $currentNetwork->xmpp_port;
                        $data['xmpp_username']    = $externalCredentials->getUsernameXmpp();
                        $data['xmpp_password']    = $externalCredentials->getPasswordXmpp();
                        $data['inmail_username']    = $externalCredentials->getUsernameInmail();
                        $data['inmail_password']    = $externalCredentials->getPasswordInmail();
                    }
                }
            }
            
            $data = [
                'success' => true,
                'data' =>  $data
            ];
           
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

    public function facebookAction()
    {

        $request = $this->getRequest();
        if ($request->isGet()) {
            /*
          //  try {
                $app_id = $this->config['leaderslinked.facebook.app_id'];
                $app_password = $this->config['leaderslinked.facebook.app_password'];
                $app_graph_version = $this->config['leaderslinked.facebook.app_graph_version'];
                //$app_url_auth = $this->config['leaderslinked.facebook.app_url_auth'];
                //$redirect_url = $this->config['leaderslinked.facebook.app_redirect_url'];
                
                [facebook]
                app_id=343770226993130
                app_password=028ee729090fd591e50a17a786666c12
                app_graph_version=v17
                app_redirect_url=https://leaderslinked.com/oauth/facebook
                
                https://www.facebook.com/v17.0/dialog/oauth?client_id=343770226993130&redirect_uri= https://dev.leaderslinked.com/oauth/facebook&state=AE12345678
                

                $s = 'https://www.facebook.com/v17.0/dialog/oauth' . 
                    '?client_id=' 
                    '&redirect_uri={"https://www.domain.com/login"}
                    '&state={"{st=state123abc,ds=123456789}"}

                $fb = new \Facebook\Facebook([
                    'app_id' => $app_id,
                    'app_secret' => $app_password,
                    'default_graph_version' => $app_graph_version,
                ]);
                
                $app_url_auth =  $this->url()->fromRoute('oauth/facebook', [], ['force_canonical' => true]);
                $helper = $fb->getRedirectLoginHelper();
                $permissions = ['email', 'public_profile']; // Optional permissions
                $facebookUrl = $helper->getLoginUrl($app_url_auth, $permissions);
                
                
                
                return new JsonModel([
                    'success' => false,
                    'data' => $facebookUrl
                ]);
            } catch (\Throwable $e) {
                return new JsonModel([
                    'success' => false,
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_FACEBOOK'
                ]);
            }*/
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function twitterAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {

            try {
                if ($this->config['leaderslinked.runmode.sandbox']) {

                    $twitter_api_key = $this->config['leaderslinked.twitter.sandbox_api_key'];
                    $twitter_api_secret = $this->config['leaderslinked.twitter.sandbox_api_secret'];
                } else {
                    $twitter_api_key = $this->config['leaderslinked.twitter.production_api_key'];
                    $twitter_api_secret = $this->config['leaderslinked.twitter.production_api_secret'];
                }

                /*
                 echo '$twitter_api_key = ' . $twitter_api_key . PHP_EOL;
                 echo '$twitter_api_secret = ' . $twitter_api_secret . PHP_EOL;
                 exit;
                 */

                //Twitter
                //$redirect_url =  $this->url()->fromRoute('oauth/twitter', [], ['force_canonical' => true]);
                $redirect_url = $this->config['leaderslinked.twitter.app_redirect_url'];
                $twitter = new \Abraham\TwitterOAuth\TwitterOAuth($twitter_api_key, $twitter_api_secret);
                $request_token =  $twitter->oauth('oauth/request_token', ['oauth_callback' => $redirect_url]);
                $twitterUrl = $twitter->url('oauth/authorize', ['oauth_token' => $request_token['oauth_token']]);

                $twitterSession = new \Laminas\Session\Container('twitter');
                $twitterSession->oauth_token = $request_token['oauth_token'];
                $twitterSession->oauth_token_secret = $request_token['oauth_token_secret'];

                return new JsonModel([
                    'success' => true,
                    'data' =>  $twitterUrl
                ]);
            } catch (\Throwable $e) {
                return new JsonModel([
                    'success' => false,
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_TWITTER'
                ]);
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function googleAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {

            try {


                //Google
                $google = new \Google_Client();
                $google->setAuthConfig('data/google/auth-leaderslinked/apps.google.com_secreto_cliente.json');
                $google->setAccessType("offline");        // offline access

                $google->setIncludeGrantedScopes(true);   // incremental auth

                $google->addScope('profile');
                $google->addScope('email');

                // $redirect_url =  $this->url()->fromRoute('oauth/google', [], ['force_canonical' => true]);
                $redirect_url = $this->config['leaderslinked.google_auth.app_redirect_url'];

                $google->setRedirectUri($redirect_url);
                $googleUrl = $google->createAuthUrl();

                return new JsonModel([
                    'success' => true,
                    'data' =>  $googleUrl
                ]);
            } catch (\Throwable $e) {
                return new JsonModel([
                    'success' => false,
                    'data' =>  'ERROR_WE_COULD_NOT_CONNECT_TO_GOOGLE'
                ]);
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function signoutAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getRawUser();
        if ($currentUserPlugin->hasImpersonate()) {


            $userMapper = UserMapper::getInstance($this->adapter);
            $userMapper->leaveImpersonate($currentUser->id);

            $networkMapper = NetworkMapper::getInstance($this->adapter);
            $network = $networkMapper->fetchOne($currentUser->network_id);


            if (!$currentUser->one_time_password) {
                $one_time_password = Functions::generatePassword(25);

                $currentUser->one_time_password = $one_time_password;

                $userMapper = UserMapper::getInstance($this->adapter);
                $userMapper->updateOneTimePassword($currentUser, $one_time_password);
            }


            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
            if ($sandbox) {
                $salt = $this->config['leaderslinked.backend.sandbox_salt'];
            } else {
                $salt = $this->config['leaderslinked.backend.production_salt'];
            }

            $rand = 1000 + mt_rand(1, 999);
            $timestamp = time();
            $password = md5($currentUser->one_time_password . '-' . $rand . '-' . $timestamp . '-' . $salt);

            $params = [
                'user_uuid' => $currentUser->uuid,
                'password' => $password,
                'rand' => $rand,
                'time' => $timestamp,
            ];

            $currentUserPlugin->clearIdentity();

            return new JsonModel([
                'success'   => true,
                'data'      => [
                    'message' => 'LABEL_SIGNOUT_SUCCESSFULLY',
                    'url' => 'https://' . $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params)
                ],    
                
            ]);
            
            
           // $url = 'https://' . $network->main_hostname . '/signin/impersonate' . '?' . http_build_query($params);
           // return $this->redirect()->toUrl($url);
        } else {


            if ($currentUserPlugin->hasIdentity()) {

                $this->logger->info('Desconexión de LeadersLinked', ['user_id' => $currentUserPlugin->getUserId(), 'ip' => Functions::getUserIP()]);
            }

            $currentUserPlugin->clearIdentity();

           // return $this->redirect()->toRoute('home');
           
            return new JsonModel([
                'success'   => true,
                'data'      => [
                    'message' => 'LABEL_SIGNOUT_SUCCESSFULLY',
                    'url' => '',
                ],
                
            ]);
        }
    }


    public function resetPasswordAction()
    {
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork  = $currentNetworkPlugin->getNetwork();

        $code =  Functions::sanitizeFilterString($this->params()->fromRoute('code', ''));

        $userMapper = UserMapper::getInstance($this->adapter);
        $user = $userMapper->fetchOneByPasswordResetKeyAndNetworkId($code, $currentNetwork->id);

        if (!$user) {
            $this->logger->err('Restablecer contraseña - Error código no existe', ['ip' => Functions::getUserIP()]);

            return new JsonModel([
                'success'   => false,
                'data'      => 'ERROR_PASSWORD_RECOVER_CODE_IS_INVALID'
            ]);

        }

        $password_generated_on = strtotime($user->password_generated_on);
        $expiry_time = $password_generated_on + $this->config['leaderslinked.security.reset_password_expired'];

        if (time() > $expiry_time) {
            $this->logger->err('Restablecer contraseña - Error código expirado', ['ip' => Functions::getUserIP()]);
            return new JsonModel([
                'success'   => false,
                'data'      => 'ERROR_PASSWORD_RECOVER_CODE_HAS_EXPIRED'
            ]);
        }

        $request = $this->getRequest();

        if ($request->isPost()) {
            $dataPost = $request->getPost()->toArray();

            if (empty($_SESSION['aes'])) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
                ]);   
            }

            if (!empty($dataPost['password'])) {
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
            }

            if (!empty($dataPost['confirmation'])) {
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
            }

            $form = new ResetPasswordForm($this->config);
            $form->setData($dataPost);

            if ($form->isValid()) {
                $data = (array) $form->getData();
                $password = $data['password'];

                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);

                $oldPassword = false;
                foreach ($userPasswords as $userPassword) {
                    if (password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password)) {
                        $oldPassword = true;
                        break;
                    }
                }

                if ($oldPassword) {
                    $this->logger->err('Restablecer contraseña - Error contraseña ya utilizada anteriormente', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);

                    return new JsonModel([
                        'success'   => false,
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'

                    ]);
                } else {
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);


                    $result = $userMapper->updatePassword($user, $password_hash);
                    if ($result) {

                        $userPassword = new UserPassword();
                        $userPassword->user_id = $user->id;
                        $userPassword->password = $password_hash;
                        $userPasswordMapper->insert($userPassword);


                        $this->logger->info('Restablecer contraseña realizado', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);


                        
                        return new JsonModel([
                            'success'   => true,
                            'data'      => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED'

                        ]);
                    } else {
                        $this->logger->err('Restablecer contraseña - Error desconocido', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);

                        return new JsonModel([
                            'success'   => false,
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'

                        ]);
                    }
                }
            } else {
                $form_messages =  $form->getMessages('captcha');
                if (!empty($form_messages)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
                    ]);
                }

                $messages = [];

                $form_messages = (array) $form->getMessages();
                foreach ($form_messages  as $fieldname => $field_messages) {
                    $messages[$fieldname] = array_values($field_messages);
                }

                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
            }
        } else if ($request->isGet()) {

            if (empty($_SESSION['aes'])) {
                $_SESSION['aes'] = Functions::generatePassword(16);
            }

            if ($this->config['leaderslinked.runmode.sandbox']) {
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
            } else {
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
            }


            return new JsonModel([
                'code' => $code,
                'site_key' => $site_key,
                'aes'       => $_SESSION['aes'],
                'defaultNetwork' => $currentNetwork->default,
            ]);

        }



        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }

    public function forgotPasswordAction()
    {
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork  = $currentNetworkPlugin->getNetwork();

        $request = $this->getRequest();

        if ($request->isGet()) {
            if (empty($_SESSION['aes'])) {
                $_SESSION['aes'] = Functions::generatePassword(16);
            }

            $site_key = $this->config['leaderslinked.runmode.sandbox'] 
            ? $this->config['leaderslinked.google_captcha.sandbox_site_key'] 
            : $this->config['leaderslinked.google_captcha.production_site_key'];

            return new JsonModel([
                'site_key'  => $site_key,
                'aes'       => $_SESSION['aes'],
                'defaultNetwork' => $currentNetwork->default,
            ]);
        }

        if ($request->isPost()) {
            $dataPost = $request->getPost()->toArray();

            if (empty($_SESSION['aes'])) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
                ]);
            }

            if (!empty($dataPost['email'])) {
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
            }

            $form = new ForgotPasswordForm($this->config);
            $form->setData($dataPost);

            if (!$form->isValid()){
                $form_messages =  $form->getMessages('captcha');

                if (!empty($form_messages)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
                    ]);
                }

                $messages = [];
                $form_messages = (array) $form->getMessages();
                foreach ($form_messages  as $fieldname => $field_messages) {
                    $messages[$fieldname] = array_values($field_messages);
                }

                return new JsonModel([
                    'success'   => false,
                    'data'      => $messages
                ]);
            }

            $dataPost = (array) $form->getData();
            $email      = $dataPost['email'];

            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);

            if (!$user) {
                $this->logger->err('Olvidó contraseña ' . $email . '- Email no existe ', ['ip' => Functions::getUserIP()]);
                return new JsonModel([
                    'success' => false,
                    'data' =>  'ERROR_EMAIL_IS_NOT_REGISTERED'
                ]);
            }

            
            if ($user->status == User::STATUS_INACTIVE) {
                return new JsonModel([
                    'success' => false,
                    'data' =>  'ERROR_USER_IS_INACTIVE'
                ]);
            } 
            
            if ($user->email_verified == User::EMAIL_VERIFIED_NO) {
                $this->logger->err('Olvidó contraseña - Email no verificado ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_EMAIL_HAS_NOT_BEEN_VERIFIED'
                ]);
            } 
            
            $password_reset_key = md5($user->email . time());
            $userMapper->updatePasswordResetKey((int) $user->id, $password_reset_key);

            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RESET_PASSWORD, $currentNetwork->id);

            if (!$emailTemplate) {
                $this->logger->err('Olvidó contraseña - Email template no existe ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_EMAIL_TEMPLATE_NOT_FOUND'
                ]);
            }

            $arrayCont = [
                'firstname'             => $user->first_name,
                'lastname'              => $user->last_name,
                'other_user_firstname'  => '',
                'other_user_lastname'   => '',
                'company_name'          => '',
                'group_name'            => '',
                'content'               => '',
                'code'                  => '',
                'link'                  => $this->url()->fromRoute('reset-password', ['code' => $password_reset_key], ['force_canonical' => true])
            ];

            $email = new QueueEmail($this->adapter);
            
            if (!$email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name))) {
                $this->logger->err('Olvidó contraseña - Error al enviar email ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_EMAIL_NOT_SENT'
                ]);
            }

            $this->logger->info('Olvidó contraseña - Se envio link de recuperación ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);

            return new JsonModel([
                'success' => true,
                'data' => 'LABEL_RECOVERY_LINK_WAS_SENT_TO_YOUR_EMAIL'
            ]);
        }

        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }

    public function signupAction()
    {
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork  = $currentNetworkPlugin->getNetwork();


        $request = $this->getRequest();
        if ($request->isPost()) {
            $dataPost = $request->getPost()->toArray();

            if (empty($_SESSION['aes'])) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
                ]);
            }

            if (!empty($dataPost['email'])) {
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $_SESSION['aes']);
            }

            if (!empty($dataPost['password'])) {
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $_SESSION['aes']);
            }

            if (!empty($dataPost['confirmation'])) {
                $dataPost['confirmation'] = CryptoJsAes::decrypt($dataPost['confirmation'], $_SESSION['aes']);
            }

            if (empty($dataPost['is_adult'])) {
                $dataPost['is_adult'] = User::IS_ADULT_NO;
            } else {
                $dataPost['is_adult'] = $dataPost['is_adult'] == User::IS_ADULT_YES ? User::IS_ADULT_YES : User::IS_ADULT_NO;
            }



            $form = new SignupForm($this->config);
            $form->setData($dataPost);

            if ($form->isValid()) {
                $dataPost = (array) $form->getData();

                $email = $dataPost['email'];

                $userMapper = UserMapper::getInstance($this->adapter);
                $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
                if ($user) {
                    $this->logger->err('Registro ' . $email . '- Email ya  existe ', ['ip' => Functions::getUserIP()]);



                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_EMAIL_IS_REGISTERED'
                    ]);
                } else {

                    $user_share_invitation = $this->cache->getItem('user_share_invitation');


                    if ($user_share_invitation && is_array($user_share_invitation)) {
                        
                        $content_uuid = $user_share_invitation['code'];
                        $content_type = $user_share_invitation['type'];
                        $content_user = $user_share_invitation['user'];
                        
                        
                        $userRedirect = $userMapper->fetchOneByUuid($content_user);
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE) {
                            $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);

                            $user = new User();
                            $user->network_id           = $currentNetwork->id;
                            $user->email                = $dataPost['email'];
                            $user->first_name           = $dataPost['first_name'];
                            $user->last_name            = $dataPost['last_name'];
                            $user->timezone             = $dataPost['timezone'];
                            $user->usertype_id          = UserType::USER;
                            $user->password             = $password_hash;
                            $user->password_updated_on  = date('Y-m-d H:i:s');
                            $user->status               = User::STATUS_ACTIVE;
                            $user->blocked              = User::BLOCKED_NO;
                            $user->email_verified       = User::EMAIL_VERIFIED_YES;
                            $user->login_attempt        = 0;
                            $user->is_adult             = $dataPost['is_adult'];
                            $user->request_access       = User::REQUEST_ACCESS_APPROVED;





                            if ($userMapper->insert($user)) {

                                $userPassword = new UserPassword();
                                $userPassword->user_id = $user->id;
                                $userPassword->password = $password_hash;

                                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
                                $userPasswordMapper->insert($userPassword);


                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);

                                if ($connection) {

                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
                                        $connectionMapper->approve($connection);
                                    }
                                } else {
                                    $connection = new Connection();
                                    $connection->request_from = $user->id;
                                    $connection->request_to = $userRedirect->id;
                                    $connection->status = Connection::STATUS_ACCEPTED;

                                    $connectionMapper->insert($connection);
                                }


                                $this->cache->removeItem('user_share_invitation');


                         
                                if($content_type == 'feed') {
                                    $url = $this->url()->fromRoute('dashboard', ['feed' => $content_uuid ]);
                                    
                                }
                                else if($content_type == 'post') {
                                    $url = $this->url()->fromRoute('post', ['id' => $content_uuid ]);
                                }
                                else {
                                    $url = $this->url()->fromRoute('dashboard');
                                }
                                
                                $hostname = empty($_SERVER['HTTP_HOST']) ?  '' : $_SERVER['HTTP_HOST'];
                                
                                $networkMapper = NetworkMapper::getInstance($this->adapter);
                                $network = $networkMapper->fetchOneByHostnameForFrontend($hostname);
                                
                                if(!$network) {
                                    $network = $networkMapper->fetchOneByDefault();
                                }
                                
                                $hostname = trim($network->main_hostname);
                                $url = 'https://' . $hostname . $url;
                                

                                $data = [
                                    'success'   => true,
                                    'data'      => $url
                                ];


                                $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);

                                return new JsonModel($data);
                            }
                        }
                    }




                    $timestamp = time();
                    $activation_key = sha1($dataPost['email'] . uniqid() . $timestamp);

                    $password_hash = password_hash($dataPost['password'], PASSWORD_DEFAULT);

                    $user = new User();
                    $user->network_id           = $currentNetwork->id;
                    $user->email                = $dataPost['email'];
                    $user->first_name           = $dataPost['first_name'];
                    $user->last_name            = $dataPost['last_name'];
                    $user->usertype_id          = UserType::USER;
                    $user->password             = $password_hash;
                    $user->password_updated_on  = date('Y-m-d H:i:s');
                    $user->activation_key       = $activation_key;
                    $user->status               = User::STATUS_INACTIVE;
                    $user->blocked              = User::BLOCKED_NO;
                    $user->email_verified       = User::EMAIL_VERIFIED_NO;
                    $user->login_attempt        = 0;

                    if ($currentNetwork->default == Network::DEFAULT_YES) {
                        $user->request_access = User::REQUEST_ACCESS_APPROVED;
                    } else {
                        $user->request_access = User::REQUEST_ACCESS_PENDING;
                    }

                    $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
                    $externalCredentials->completeDataFromNewUser($user);

                    if ($userMapper->insert($user)) {

                        $userPassword = new UserPassword();
                        $userPassword->user_id = $user->id;
                        $userPassword->password = $password_hash;

                        $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
                        $userPasswordMapper->insert($userPassword);

                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_USER_REGISTER, $currentNetwork->id);
                        if ($emailTemplate) {
                            $arrayCont = [
                                'firstname'             => $user->first_name,
                                'lastname'              => $user->last_name,
                                'other_user_firstname'  => '',
                                'other_user_lastname'   => '',
                                'company_name'          => '',
                                'group_name'            => '',
                                'content'               => '',
                                'code'                  => '',
                                'link'                  => $this->url()->fromRoute('activate-account', ['code' => $user->activation_key], ['force_canonical' => true])
                            ];

                            $email = new QueueEmail($this->adapter);
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
                        }

                        $this->logger->info('Registro con Exito ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);

                        return new JsonModel([
                            'success' => true,
                            'data' => 'LABEL_REGISTRATION_DONE'
                        ]);
                    } else {
                        $this->logger->err('Registro ' . $email . '- Ha ocurrido un error ', ['ip' => Functions::getUserIP()]);

                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }
                }
            } else {

                $form_messages =  $form->getMessages('captcha');
                if (!empty($form_messages)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'      => 'ERROR_RECAPTCHA_EMPTY'
                    ]);
                }

                $messages = [];

                $form_messages = (array) $form->getMessages();
                foreach ($form_messages  as $fieldname => $field_messages) {
                    $messages[$fieldname] = array_values($field_messages);
                }

                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
            }
        } else if ($request->isGet()) {

            if (empty($_SESSION['aes'])) {
                $_SESSION['aes'] = Functions::generatePassword(16);
            }

            if ($this->config['leaderslinked.runmode.sandbox']) {
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
            } else {
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
            }

            $email      = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';

            return new JsonModel([
                'site_key'  => $site_key,
                'aes'       => $_SESSION['aes'],
                'defaultNetwork' => $currentNetwork->default,
            ]);
        }

        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }

    public function activateAccountAction()
    {

        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork  = $currentNetworkPlugin->getNetwork();



        $request = $this->getRequest();
        if ($request->isGet()) {
            $code   =  Functions::sanitizeFilterString($this->params()->fromRoute('code'));
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByActivationKeyAndNetworkId($code, $currentNetwork->id);



            if ($user) {
                if (User::EMAIL_VERIFIED_YES == $user->email_verified) {
                    
                    $this->logger->err('Verificación email - El código ya habia sido verificao ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
                    
                    $response = [
                        'success' => false,
                        'data' => 'ERROR_EMAIL_HAS_BEEN_PREVIOUSLY_VERIFIED'
                    ];
            
                    return new JsonModel($response);
                } else {

                    if ($userMapper->activateAccount((int) $user->id)) {

                        $this->logger->info('Verificación email realizada ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);



                        $user_share_invitation = $this->cache->getItem('user_share_invitation');

                        if ($user_share_invitation) {
                            $userRedirect = $userMapper->fetchOneByUuid($user_share_invitation);
                            if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
                                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);

                                if ($connection) {

                                    if ($connection->status != Connection::STATUS_ACCEPTED) {
                                        $connectionMapper->approve($connection);
                                    }
                                } else {
                                    $connection = new Connection();
                                    $connection->request_from = $user->id;
                                    $connection->request_to = $userRedirect->id;
                                    $connection->status = Connection::STATUS_ACCEPTED;

                                    $connectionMapper->insert($connection);
                                }
                            }
                        }



                        $this->cache->removeItem('user_share_invitation');


                        if ($currentNetwork->default == Network::DEFAULT_YES) {
                            
                            $response = [
                                'success' => true,
                                'data' => 'LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED'
                            ];
                            
                            return new JsonModel($response);
                            
     
                        } else {

                            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
                            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_REQUEST_ACCESS_PENDING, $currentNetwork->id);

                            if ($emailTemplate) {
                                $arrayCont = [
                                    'firstname'             => $user->first_name,
                                    'lastname'              => $user->last_name,
                                    'other_user_firstname'  => '',
                                    'other_user_lastname'   => '',
                                    'company_name'          => '',
                                    'group_name'            => '',
                                    'content'               => '',
                                    'code'                  => '',
                                    'link'                  => '',
                                ];

                                $email = new QueueEmail($this->adapter);
                                $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
                            }
                            
                            $response = [
                                'success' => true,
                                'data' => 'LABEL_YOUR_EMAIL_HAS_BEEN_VERIFIED_WE_ARE_VERIFYING_YOUR_INFORMATION'
                            ];
                            
                            return new JsonModel($response);


                        }
                    } else {
                        $this->logger->err('Verificación email - Ha ocurrido un error ', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
                        
                        $response = [
                            'success' => false,
                            'data' => 'ERROR_THERE_WAS_AN_ERROR'
                        ];
                        
                        return new JsonModel($response);

                    }
                }
            } else {
                
                
                $this->logger->err('Verificación email - El código no existe ', ['ip' => Functions::getUserIP()]);

                $response = [
                    'success' => false,
                    'data' =>'ERROR_ACTIVATION_CODE_IS_NOT_VALID'
                ];
                
                return new JsonModel($response);
                
                

            }

          
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
        }

        return new JsonModel($response);
    }
    
    public function onroomAction()
    {
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork  = $currentNetworkPlugin->getNetwork();
        
        
        
        $request = $this->getRequest();
        
        if ($request->isPost()) {
            
            $dataPost = $request->getPost()->toArray();
            
            
            $form = new  MoodleForm();
            $form->setData($dataPost);
            if ($form->isValid()) {
                
                $dataPost   = (array) $form->getData();
                $username   = $dataPost['username'];
                $password   = $dataPost['password'];
                $timestamp  = $dataPost['timestamp'];
                $rand       = $dataPost['rand'];
                $data       = $dataPost['data'];
                
                $config_username    = $this->config['leaderslinked.moodle.username'];
                $config_password    = $this->config['leaderslinked.moodle.password'];
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
                $config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];
                
                
                
                
                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
                    exit;
                }
                
                if ($username != $config_username) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
                    exit;
                }
                
                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
                if (!$dt) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
                    exit;
                }
                
                $t0 = $dt->getTimestamp();
                $t1 = strtotime('-5 minutes');
                $t2 = strtotime('+5 minutes');
                
                if ($t0 < $t1 || $t0 > $t2) {
                    //echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
                    //exit;
                }
                
                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
                    exit;
                }
                
                if (empty($data)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
                    exit;
                }
                
                $data = base64_decode($data);
                if (empty($data)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
                    exit;
                }
                
                
                try {
                    $rsa = Rsa::getInstance();
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
                } catch (\Throwable $e) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
                    exit;
                }
                
                $data = (array) json_decode($data);
                if (empty($data)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
                    exit;
                }
                
                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
                
                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
                    exit;
                }
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $user = $userMapper->fetchOneByEmail($email);
                if (!$user) {
                    
                    
                    $user = new User();
                    $user->network_id = $currentNetwork->id;
                    $user->blocked = User::BLOCKED_NO;
                    $user->email = $email;
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
                    $user->first_name = $first_name;
                    $user->last_name = $last_name;
                    $user->login_attempt = 0;
                    $user->password = '-NO-PASSWORD-';
                    $user->usertype_id = UserType::USER;
                    $user->status = User::STATUS_ACTIVE;
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;
                    
                    if ($userMapper->insert($user)) {
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
                        exit;
                    }
                    
                    $user = $userMapper->fetchOne($user->id);
                    
                    
                    
                    
                    $filename   = trim(isset($data['avatar_filename']) ? filter_var($data['avatar_filename'], FILTER_SANITIZE_EMAIL) : '');
                    $content    = isset($data['avatar_content']) ? Functions::sanitizeFilterString($data['avatar_content']) : '';
                    
                    if ($filename && $content) {
                        $source = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
                        try {
                            
                            
                            file_put_contents($source, base64_decode($content));
                            if (file_exists($source)) {
                                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.user_size']);
                                
                                $target_filename    = 'user-' . uniqid() . '.png';
                                $crop_to_dimensions = true;
                                
                                $image = Image::getInstance($this->config);
                                $target_path    = $image->getStorage()->getPathUser();
                                $unlink_source  = true;
                                
                                
                                if (!$image->uploadProcessChangeSize($source, $target_path, $user->uuid, $target_filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
                                    return new JsonModel([
                                        'success'   => false,
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                                    ]);
                                }
                                
                                $user->image = $target_filename;
                                $userMapper->updateImage($user);
                            }
                        } catch (\Throwable $e) {
                        } finally {
                            if (file_exists($source)) {
                                unlink($source);
                            }
                        }
                    }
                }
                
                $auth = new AuthEmailAdapter($this->adapter);
                $auth->setData($email);
                
                $result = $auth->authenticate();
                if ($result->getCode() == AuthResult::SUCCESS) {
                    return $this->redirect()->toRoute('dashboard');
                } else {
                    $message = $result->getMessages()[0];
                    if (!in_array($message, [
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
                        'ERROR_ENTERED_PASS_INCORRECT_1'
                    ])) {
                    }
                    
                    switch ($message) {
                        case 'ERROR_USER_NOT_FOUND':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
                            break;
                            
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
                            break;
                            
                        case 'ERROR_USER_IS_BLOCKED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
                            break;
                            
                        case 'ERROR_USER_IS_INACTIVE':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        default:
                            $message = 'ERROR_UNKNOWN';
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
                            break;
                    }
                    
                    
                    
                    
                    return new JsonModel([
                        'success'   => false,
                        'data'   => $message
                    ]);
                }
            } else {
                $messages = [];
                
                
                
                $form_messages = (array) $form->getMessages();
                foreach ($form_messages  as $fieldname => $field_messages) {
                    
                    $messages[$fieldname] = array_values($field_messages);
                }
                
                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }



    public function cesamsAction()
    {
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork  = $currentNetworkPlugin->getNetwork();

        $request = $this->getRequest();

        if ($request->isPost()) {

            $dataPost = $request->getPost()->toArray();


            $form = new  MoodleForm();
            $form->setData($dataPost);
            if ($form->isValid()) {

                $dataPost   = (array) $form->getData();
                $username   = $dataPost['username'];
                $password   = $dataPost['password'];
                $timestamp  = $dataPost['timestamp'];
                $rand       = $dataPost['rand'];
                $data       = $dataPost['data'];

                $config_username    = $this->config['leaderslinked.moodle.username'];
                $config_password    = $this->config['leaderslinked.moodle.password'];
                $config_rsa_n       = $this->config['leaderslinked.moodle.rsa_n'];
                $config_rsa_d       = $this->config['leaderslinked.moodle.rsa_d'];
                //$config_rsa_e       = $this->config['leaderslinked.moodle.rsa_e'];

                if (empty($username) || empty($password) || empty($timestamp) || empty($rand) || !is_integer($rand)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY1']);
                    exit;
                }

                if ($username != $config_username) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY2']);
                    exit;
                }

                $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s', $timestamp);
                if (!$dt) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY3']);
                    exit;
                }

                $dt = \DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s',  gmdate('Y-m-d\TH:i:s'));
                $dtMax = $dt->add(\DateInterval::createFromDateString('5 minutes'));
                $dtMin = $dt->sub(\DateInterval::createFromDateString('5 minutes'));
                
                
                $t0 = $dt->getTimestamp();
                $t1 = $dtMin->getTimestamp();
                $t2 = $dtMax->getTimestamp();
                if ($t0 < $t1 || $t0 > $t2) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY4']) ;
                    exit;
                }

                if (!password_verify($username . '-' . $config_password . '-' . $rand . '-' . $timestamp, $password)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_SECURITY5']);
                    exit;
                }

                if (empty($data)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS1']);
                    exit;
                }

                $data = base64_decode($data);
                if (empty($data)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS2']);
                    exit;
                }

                try {
                    $rsa = Rsa::getInstance();
                    $data = $rsa->decrypt($data,  $config_rsa_d,  $config_rsa_n);
                } catch (\Throwable $e) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS3']);
                    exit;
                }

                $data = (array) json_decode($data);
                if (empty($data)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS4']);
                    exit;
                }

                $email      = isset($data['email']) ? Functions::sanitizeFilterString($data['email']) : '';
                $first_name = isset($data['first_name']) ? Functions::sanitizeFilterString($data['first_name']) : '';
                $last_name  = isset($data['last_name']) ? Functions::sanitizeFilterString($data['last_name']) : '';
                $password   = isset($data['password']) ? Functions::sanitizeFilterString($data['password']) : '';

                if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($first_name) || empty($last_name) || empty($password)) {
                    echo json_encode(['success' => false, 'data' => 'ERROR_PARAMETERS5']);
                    exit;
                }

                $userMapper = UserMapper::getInstance($this->adapter);
                $user = $userMapper->fetchOneByEmail($email);
                if (!$user) {

                    $user = new User();
                    $user->network_id = $currentNetwork->id;
                    $user->blocked = User::BLOCKED_NO;
                    $user->email = $email;
                    $user->email_verified = User::EMAIL_VERIFIED_YES;
                    $user->first_name = $first_name;
                    $user->last_name = $last_name;
                    $user->login_attempt = 0;
                    $user->password = password_hash($password, PASSWORD_DEFAULT);
                    $user->usertype_id = UserType::USER;
                    $user->status = User::STATUS_ACTIVE;
                    $user->show_in_search = User::SHOW_IN_SEARCH_YES;

                    if ($userMapper->insert($user)) {
                        echo json_encode(['success' => false, 'data' => $userMapper->getError()]);
                        exit;
                    }
                    
                    $user = $userMapper->fetchOne($user->id);
                    
                    $userPassword = new UserPassword();
                    $userPassword->user_id = $user->id;
                    $userPassword->password = password_hash($password, PASSWORD_DEFAULT);
                    
                    $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
                    $userPasswordMapper->insert($userPassword);
                    
                    $userDefaultForConnection = $userMapper->fetchOneDefaultForConnection();
                    if($userDefaultForConnection) {
                    
                        $connection = new Connection();
                        $connection->request_from = $userDefaultForConnection->id; 
                        $connection->request_to = $user->id;
                        $connection->status = Connection::STATUS_ACCEPTED;
                        
                        $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                        $connectionMapper->insert($connection);
                    }
                }

                return new JsonModel([
                    'success'   => true,
                    'data'   => $user->uuid
                ]);
        
            } else {
                $messages = [];



                $form_messages = (array) $form->getMessages();
                foreach ($form_messages  as $fieldname => $field_messages) {

                    $messages[$fieldname] = array_values($field_messages);
                }

                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

    public function csrfAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {
            
            $jwtToken = null;
            $headers = getallheaders();
            
 
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
                
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
                
                
                if (substr($token, 0, 6 ) == 'Bearer') {
                    
                    $token = trim(substr($token, 7));
                    
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
                        $key = $this->config['leaderslinked.jwt.key'];
                        
                        
                        try {
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
                            
                            
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
                            }
                            
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
                            if(!$jwtToken) {
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
                            }
                            
                        } catch(\Exception $e) {
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
                        }
                    } else {
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
                    }
                } else {
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
                }
            } else {
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
            }
            
            $jwtToken->csrf = md5(uniqid('CSFR-' . mt_rand(), true));
            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
            $jwtTokenMapper->update($jwtToken);
             
            
           // error_log('token id = ' . $jwtToken->id . ' csrf = ' . $jwtToken->csrf);


            return new JsonModel([
                'success' => true,
                'data' => $jwtToken->csrf
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function impersonateAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {
            $user_uuid  = Functions::sanitizeFilterString($this->params()->fromQuery('user_uuid'));
            $rand       = filter_var($this->params()->fromQuery('rand'), FILTER_SANITIZE_NUMBER_INT);
            $timestamp  = filter_var($this->params()->fromQuery('time'), FILTER_SANITIZE_NUMBER_INT);
            $password   = Functions::sanitizeFilterString($this->params()->fromQuery('password'));


            if (!$user_uuid || !$rand || !$timestamp || !$password) {
                throw new \Exception('ERROR_PARAMETERS_ARE_INVALID');
            }


            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUserPlugin->clearIdentity();


            $authAdapter = new AuthImpersonateAdapter($this->adapter, $this->config);
            $authAdapter->setDataAdmin($user_uuid, $password, $timestamp, $rand);

            $authService = new AuthenticationService();
            $result = $authService->authenticate($authAdapter);


            if ($result->getCode() == AuthResult::SUCCESS) {
                return $this->redirect()->toRoute('dashboard');
            } else {
                throw new \Exception($result->getMessages()[0]);
            }
        }

        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    
    public function debugAction()
    {
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork = $currentNetworkPlugin->getNetwork();
        
        $request = $this->getRequest();
        
        if ($request->isPost()) {
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
            $currentNetwork = $currentNetworkPlugin->getNetwork();
            
            $jwtToken = null;
            $headers = getallheaders();
            
            
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
                
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
                
                
                if (substr($token, 0, 6 ) == 'Bearer') {
                    
                    $token = trim(substr($token, 7));
                    
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
                        $key = $this->config['leaderslinked.jwt.key'];
                        
                        
                        try {
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
                            
                            
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
                            }
                            
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
                            if(!$jwtToken) {
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Expired',  'fatal'  => true]);
                            }
                            
                        } catch(\Exception $e) {
                            return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong key',  'fatal'  => true]);
                        }
                    } else {
                        return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - SecreteKey required',  'fatal'  => true]);
                    }
                } else {
                    return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Bearer required',  'fatal'  => true]);
                }
            } else {
                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Required',  'fatal'  => true]);
            }
            
            
            
            $form = new  SigninDebugForm($this->config);
            $dataPost = $request->getPost()->toArray();
            
            if (empty($_SESSION['aes'])) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_WEBSERVICE_ENCRYPTION_KEYS_NOT_FOUND'
                ]);
            }
            
            error_log(print_r($dataPost, true));
            
            $aes = $_SESSION['aes'];
            error_log('aes : ' . $aes);
            
            
            unset( $_SESSION['aes'] );
            
            if (!empty($dataPost['email'])) {
                $dataPost['email'] = CryptoJsAes::decrypt($dataPost['email'], $aes);
            }
            
            
            if (!empty($dataPost['password'])) {
                $dataPost['password'] = CryptoJsAes::decrypt($dataPost['password'], $aes);
            }
            
            
            error_log(print_r($dataPost, true));
            
            $form->setData($dataPost);
            
            if ($form->isValid()) {
                
                $dataPost = (array) $form->getData();
                
                
                $email      = $dataPost['email'];
                $password   = $dataPost['password'];
                
                
                
                
                
                $authAdapter = new AuthAdapter($this->adapter, $this->logger);
                $authAdapter->setData($email, $password, $currentNetwork->id);
                $authService = new AuthenticationService();
                
                $result = $authService->authenticate($authAdapter);
                
                if ($result->getCode() == AuthResult::SUCCESS) {
                    
                    $identity = $result->getIdentity();
                    
                    
                    $userMapper = UserMapper::getInstance($this->adapter);
                    $user = $userMapper->fetchOne($identity['user_id']);
                    
                    
                    if($token) {
                        $jwtToken->user_id = $user->id;
                        $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                        $jwtTokenMapper->update($jwtToken);
                    }
                    
                    
                    $navigator = get_browser(null, true);
                    $device_type    =  isset($navigator['device_type']) ? $navigator['device_type'] : '';
                    $platform       =  isset($navigator['platform']) ? $navigator['platform'] : '';
                    $browser        =  isset($navigator['browser']) ? $navigator['browser'] : '';
                    
                    
                    $istablet = isset($navigator['istablet']) ?  intval($navigator['istablet']) : 0;
                    $ismobiledevice = isset($navigator['ismobiledevice']) ? intval($navigator['ismobiledevice']) : 0;
                    $version = isset($navigator['version']) ? $navigator['version'] : '';
                    
                    
                    $userBrowserMapper = UserBrowserMapper::getInstance($this->adapter);
                    $userBrowser = $userBrowserMapper->fetch($user->id, $device_type, $platform, $browser);
                    if ($userBrowser) {
                        $userBrowserMapper->update($userBrowser);
                    } else {
                        $userBrowser = new UserBrowser();
                        $userBrowser->user_id           = $user->id;
                        $userBrowser->browser           = $browser;
                        $userBrowser->platform          = $platform;
                        $userBrowser->device_type       = $device_type;
                        $userBrowser->is_tablet         = $istablet;
                        $userBrowser->is_mobile_device  = $ismobiledevice;
                        $userBrowser->version           = $version;
                        
                        $userBrowserMapper->insert($userBrowser);
                    }
                    //
                    
                    $ip = Functions::getUserIP();
                    $ip = $ip == '127.0.0.1' ? '148.240.211.148' : $ip;
                    
                    $userIpMapper = UserIpMapper::getInstance($this->adapter);
                    $userIp = $userIpMapper->fetch($user->id, $ip);
                    if (empty($userIp)) {
                        
                        if ($this->config['leaderslinked.runmode.sandbox']) {
                            $filename = $this->config['leaderslinked.geoip2.production_database'];
                        } else {
                            $filename = $this->config['leaderslinked.geoip2.sandbox_database'];
                        }
                        
                        $reader = new GeoIp2Reader($filename); //GeoIP2-City.mmdb');
                        $record = $reader->city($ip);
                        if ($record) {
                            $userIp = new UserIp();
                            $userIp->user_id = $user->id;
                            $userIp->city = !empty($record->city->name) ? Functions::utf8_decode($record->city->name) : '';
                            $userIp->state_code = !empty($record->mostSpecificSubdivision->isoCode) ? Functions::utf8_decode($record->mostSpecificSubdivision->isoCode) : '';
                            $userIp->state_name = !empty($record->mostSpecificSubdivision->name) ? Functions::utf8_decode($record->mostSpecificSubdivision->name) : '';
                            $userIp->country_code = !empty($record->country->isoCode) ? Functions::utf8_decode($record->country->isoCode) : '';
                            $userIp->country_name = !empty($record->country->name) ? Functions::utf8_decode($record->country->name) : '';
                            $userIp->ip = $ip;
                            $userIp->latitude = !empty($record->location->latitude) ? $record->location->latitude : 0;
                            $userIp->longitude = !empty($record->location->longitude) ? $record->location->longitude : 0;
                            $userIp->postal_code = !empty($record->postal->code) ? $record->postal->code : '';
                            
                            $userIpMapper->insert($userIp);
                        }
                    } else {
                        $userIpMapper->update($userIp);
                    }
                    
                    /*
                     if ($remember) {
                     $expired = time() + 365 * 24 * 60 * 60;
                     
                     $cookieEmail = new SetCookie('email', $email, $expired);
                     } else {
                     $expired = time() - 7200;
                     $cookieEmail = new SetCookie('email', '', $expired);
                     }
                     
                     
                     $response = $this->getResponse();
                     $response->getHeaders()->addHeader($cookieEmail);
                     */
                    
                    
                    
                    
                    
                    $this->logger->info('Ingreso a LeadersLiked', ['user_id' => $user->id, 'ip' => Functions::getUserIP()]);
                    
                    $user_share_invitation = $this->cache->getItem('user_share_invitation');
                    
                    $url =  $this->url()->fromRoute('dashboard');
                    
                    if ($user_share_invitation && is_array($user_share_invitation)) {
                        
                        $content_uuid = $user_share_invitation['code'];
                        $content_type = $user_share_invitation['type'];
                        $content_user = $user_share_invitation['user'];
                        
                        
                        
                        $userRedirect = $userMapper->fetchOneByUuid($content_user);
                        if ($userRedirect && $userRedirect->status == User::STATUS_ACTIVE && $user->id != $userRedirect->id) {
                            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user->id, $userRedirect->id);
                            
                            if ($connection) {
                                
                                if ($connection->status != Connection::STATUS_ACCEPTED) {
                                    $connectionMapper->approve($connection);
                                }
                            } else {
                                $connection = new Connection();
                                $connection->request_from = $user->id;
                                $connection->request_to = $userRedirect->id;
                                $connection->status = Connection::STATUS_ACCEPTED;
                                
                                $connectionMapper->insert($connection);
                            }
                        }
                        
                        if($content_type == 'feed') {
                            $url = $this->url()->fromRoute('dashboard', ['feed' => $content_uuid ]);
                            
                        }
                        else if($content_type == 'post') {
                            $url = $this->url()->fromRoute('post', ['id' => $content_uuid ]);
                        }
                        else {
                            $url = $this->url()->fromRoute('dashboard');
                        }
                        
                    }
                    
                    
                    $hostname = empty($_SERVER['HTTP_HOST']) ?  '' : $_SERVER['HTTP_HOST'];
                    
                    $networkMapper = NetworkMapper::getInstance($this->adapter);
                    $network = $networkMapper->fetchOneByHostnameForFrontend($hostname);
                    
                    if(!$network) {
                        $network = $networkMapper->fetchOneByDefault();
                    }
                    
                    $hostname = trim($network->main_hostname);
                    $url = 'https://' . $hostname . $url;
                    
                    
                    $data = [
                        'redirect'  => $url,
                        'uuid'      => $user->uuid,
                    ];
                    
                    
                    
                    
                    if($currentNetwork->xmpp_active) {
                        $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
                        $externalCredentials->getUserBy($user->id);
                        
                        
                        $data['xmpp_domain'] = $currentNetwork->xmpp_domain;
                        $data['xmpp_hostname'] = $currentNetwork->xmpp_hostname;
                        $data['xmpp_port'] = $currentNetwork->xmpp_port;
                        $data['xmpp_username'] = $externalCredentials->getUsernameXmpp();
                        $data['xmpp_pasword'] = $externalCredentials->getPasswordXmpp();
                        $data['inmail_username'] = $externalCredentials->getUsernameInmail();
                        $data['inmail_pasword'] = $externalCredentials->getPasswordInmail();
                        
                    }
                    
                    $data = [
                        'success'   => true,
                        'data'      => $data
                    ];
                    
                    
                    $this->cache->removeItem('user_share_invitation');
                } else {
                    
                    $message = $result->getMessages()[0];
                    if (!in_array($message, [
                        'ERROR_USER_NOT_FOUND', 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED', 'ERROR_USER_IS_BLOCKED',
                        'ERROR_USER_IS_INACTIVE', 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED', 'ERROR_ENTERED_PASS_INCORRECT_2',
                        'ERROR_ENTERED_PASS_INCORRECT_1', 'ERROR_USER_REQUEST_ACCESS_IS_PENDING', 'ERROR_USER_REQUEST_ACCESS_IS_REJECTED'
                        
                        
                    ])) {
                    }
                    
                    switch ($message) {
                        case 'ERROR_USER_NOT_FOUND':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no existe', ['ip' => Functions::getUserIP()]);
                            break;
                            
                        case 'ERROR_USER_EMAIL_HASNT_BEEN_VARIFIED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Email no verificado', ['ip' => Functions::getUserIP()]);
                            break;
                            
                        case 'ERROR_USER_IS_BLOCKED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario bloqueado', ['ip' => Functions::getUserIP()]);
                            break;
                            
                        case 'ERROR_USER_IS_INACTIVE':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Usuario inactivo', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        case 'ERROR_ENTERED_PASS_INCORRECT_USER_IS_BLOCKED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 3er Intento Usuario bloqueado', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        case 'ERROR_ENTERED_PASS_INCORRECT_2':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 1er Intento', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        case 'ERROR_ENTERED_PASS_INCORRECT_1':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - 2do Intento', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        case 'ERROR_USER_REQUEST_ACCESS_IS_PENDING':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Falta verificar que pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
                            break;
                            
                        case  'ERROR_USER_REQUEST_ACCESS_IS_REJECTED':
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Rechazado por no pertence a la Red Privada', ['ip' => Functions::getUserIP()]);
                            break;
                            
                            
                        default:
                            $message = 'ERROR_UNKNOWN';
                            $this->logger->err('Error de ingreso a LeadersLinked de ' . $email . ' - Error desconocido', ['ip' => Functions::getUserIP()]);
                            break;
                    }
                    
                    
                    
                    
                    $data = [
                        'success'   => false,
                        'data'   => $message
                    ];
                }
                
                return new JsonModel($data);
            } else {
                $messages = [];
                
                
                
                $form_messages = (array) $form->getMessages();
                foreach ($form_messages  as $fieldname => $field_messages) {
                    
                    $messages[$fieldname] = array_values($field_messages);
                }
                
                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
            }
        } else if ($request->isGet()) {
            
            $aes = '';
            $jwtToken = null;
            $headers = getallheaders();
            
            
            if(!empty($headers['authorization']) || !empty($headers['Authorization'])) {
                
                $token = trim(empty($headers['authorization']) ? $headers['Authorization'] : $headers['authorization']);
                
                
                if (substr($token, 0, 6 ) == 'Bearer') {
                    
                    $token = trim(substr($token, 7));
                    
                    if(!empty($this->config['leaderslinked.jwt.key'])) {
                        $key = $this->config['leaderslinked.jwt.key'];
                        
                        
                        try {
                            $payload = JWT::decode($token, new Key($key, 'HS256'));
                            
                            
                            if(empty($payload->iss) || $payload->iss != $_SERVER['HTTP_HOST']) {
                                return new JsonModel(['success' => false, 'data' => 'Unauthorized - JWT - Wrong server',  'fatal'  => true]);
                            }
                            
                            $uuid = empty($payload->uuid) ? '' : $payload->uuid;
                            $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                            $jwtToken = $jwtTokenMapper->fetchOneByUuid($uuid);
                        } catch(\Exception $e) {
                            //Token invalido
                        }
                    }
                }
            }

            
            if(!$jwtToken) {
                
                $aes = Functions::generatePassword(16);
                
                $jwtToken = new JwtToken();
                $jwtToken->aes = $aes;
                
                $jwtTokenMapper = JwtTokenMapper::getInstance($this->adapter);
                if($jwtTokenMapper->insert($jwtToken)) {
                    $jwtToken = $jwtTokenMapper->fetchOne($jwtToken->id);
                }
                
                $token = '';
                
                if(!empty($this->config['leaderslinked.jwt.key'])) {
                    $issuedAt   = new \DateTimeImmutable();
                    $expire     = $issuedAt->modify('+365 days')->getTimestamp();
                    $serverName = $_SERVER['HTTP_HOST'];
                    $payload = [
                        'iat'  => $issuedAt->getTimestamp(),
                        'iss'  => $serverName,
                        'nbf'  => $issuedAt->getTimestamp(),
                        'exp'  => $expire,
                        'uuid' => $jwtToken->uuid,
                    ];
                    
                    
                    $key = $this->config['leaderslinked.jwt.key'];
                    $token = JWT::encode($payload, $key, 'HS256');
                }
            }
            
            
            
            
            
            
            
            if ($this->config['leaderslinked.runmode.sandbox']) {
                $site_key      = $this->config['leaderslinked.google_captcha.sandbox_site_key'];
            } else {
                $site_key      = $this->config['leaderslinked.google_captcha.production_site_key'];
            }
            
            
            $access_usign_social_networks = $this->config['leaderslinked.runmode.access_usign_social_networks'];
            
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
            if ($sandbox) {
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
            } else {
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
            }
            
            
            $parts = explode('.', $currentNetwork->main_hostname);
            if($parts[1] === 'com') {
                $replace_main = false;
            } else {
                $replace_main = true;
            }
            
            
            $storage = Storage::getInstance($this->config, $this->adapter);
            $path = $storage->getPathNetwork();
            
            if($currentNetwork->logo) {
                $logo_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->logo);
            } else {
                $logo_url = '';
            }
            
            if($currentNetwork->navbar) {
                $navbar_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->navbar);
            } else {
                $navbar_url = '';
            }
            
            if($currentNetwork->favico) {
                $favico_url = $storage->getGenericImage($path, $currentNetwork->uuid, $currentNetwork->favico);
            } else {
                $favico_url = '';
            }
            
            
            
            
            $data = [
                'google_map_key'                => $google_map_key,
                'email'                         => '',
                'remember'                      => false,
                'site_key'                      => $site_key,
                'theme_id'                      => $currentNetwork->theme_id,
                'aes'                           => $aes,
                'jwt'                           => $token,
                'defaultNetwork'                => $currentNetwork->default,
                'access_usign_social_networks'  => $access_usign_social_networks && $currentNetwork->default == Network::DEFAULT_YES ? 'y' : 'n',
                'logo_url'                      => $logo_url,
                'navbar_url'                    => $navbar_url,
                'favico_url'                    => $favico_url,
                'intro'                         => $currentNetwork->intro ? $currentNetwork->intro : '',
                'is_logged_in'                  => $jwtToken->user_id ? true : false,
                
            ];
            
            if($currentNetwork->default == Network::DEFAULT_YES) {
                
                
                
                $currentUserPlugin = $this->plugin('currentUserPlugin');
                if ($currentUserPlugin->hasIdentity()) {
                    
                    
                    $externalCredentials = ExternalCredentials::getInstancia($this->config, $this->adapter);
                    $externalCredentials->getUserBy($currentUserPlugin->getUserId());
                    
                    
                    if($currentNetwork->xmpp_active) {
                        $data['xmpp_domain']      = $currentNetwork->xmpp_domain;
                        $data['xmpp_hostname']    = $currentNetwork->xmpp_hostname;
                        $data['xmpp_port']        = $currentNetwork->xmpp_port;
                        $data['xmpp_username']    = $externalCredentials->getUsernameXmpp();
                        $data['xmpp_password']    = $externalCredentials->getPasswordXmpp();
                        $data['inmail_username']    = $externalCredentials->getUsernameInmail();
                        $data['inmail_password']    = $externalCredentials->getPasswordInmail();
                    }
                }
            }
            
            $data = [
                'success' => true,
                'data' =>  $data
            ];
            
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
   
    
   
}