/**
  * 
  * @param type $entityId
  * @param type $profileData
  * @return type
  */
 public function loginRadiusSocialLinking($entityId, $profileData)
 {
     $session = Mage::getSingleton('customer/session');
     $redirectionLink = 'customer/account';
     $activationBlockObj = Mage::getBlockSingleton('activation/activation');
     $socialLoginLinkData = array();
     $socialLoginLinkData['sociallogin_id'] = $profileData->ID;
     $socialLoginLinkData['entity_id'] = $entityId;
     $socialLoginLinkData['provider'] = $profileData->Provider;
     $socialLoginLinkData['avatar'] = $this->socialLoginFilterAvatar($socialLoginLinkData['sociallogin_id'], $profileData->ThumbnailImageUrl, $socialLoginLinkData['provider']);
     $socialLoginLinkData['uid'] = isset($profileData->Uid) ? $profileData->Uid : '';
     $socialLoginLinkData['status'] = 'unblocked';
     if ($activationBlockObj->raasEnable() == 1) {
         if ($this->loginRadiusRead("lr_sociallogin", "provider exists in sociallogin", array($entityId, $socialLoginLinkData['provider']))) {
             $redirectionLink .= '?LoginRadiusLinked=0';
         } else {
             $customerEntity['uid'] = Mage::getSingleton("customer/session")->getLoginRadiusUid();
             if (isset($customerEntity['uid']) && !empty($customerEntity['uid'])) {
                 require_once Mage::getModuleDir('', 'Loginradius_Sociallogin') . DS . 'Helper' . DS . 'SDKClient.php';
                 global $apiClient_class;
                 $apiClient_class = 'Loginradius_Sociallogin_Helper_SDKClient';
                 $activationBlockObj = Mage::getBlockSingleton('activation/activation');
                 $accountAPI = new LoginRadiusSDK\CustomerRegistration\AccountAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
                 $innerJoinQuery = $this->getCustomerData(array('customer_entity', 'lr_sociallogin'), array($socialLoginLinkData['sociallogin_id']), 'id');
                 if ($innerJoinQuery->fetch()) {
                     Mage::getSingleton('core/session')->addError('Account already exists or linked with another account.');
                 } else {
                     try {
                         $response = $accountAPI->accountLink($customerEntity['uid'], $socialLoginLinkData['sociallogin_id'], $socialLoginLinkData['provider']);
                         if (isset($response->isPosted) && $response->isPosted == true) {
                             $this->SocialLoginInsert("lr_sociallogin", $socialLoginLinkData);
                             $session->addSuccess(__('Account linked successfully.'));
                         } else {
                             $session->addError(__('An Error here'));
                         }
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $session->addError($e->getErrorResponse()->description);
                     }
                 }
             }
         }
     } else {
         // check if any account from this provider is already linked
         $existAccount = $this->getCustomerData(array('customer_entity', 'lr_sociallogin'), array($socialLoginLinkData['sociallogin_id']), 'id');
         if (is_array($existAccount->fetch())) {
             $session->addError(__('This accounts is already linked with an account.'));
         } elseif ($this->loginRadiusRead("lr_sociallogin", "provider exists in sociallogin", array($entityId, $socialLoginLinkData['provider']))) {
             $session->addError(__('Multiple accounts cannot be linked from the same Social ID Provider.'));
         } else {
             $this->SocialLoginInsert("lr_sociallogin", $socialLoginLinkData);
             $session->addSuccess(__('Account linked successfully.'));
         }
     }
     Mage::app()->getResponse()->setRedirect(Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) . $redirectionLink);
     return;
 }
 /**
  * Load the page defined in view/frontend/layout/samplenewpage_index_index.xml
  *
  * @return \Magento\Framework\View\Result\Page
  */
 public function execute()
 {
     $token = isset($_REQUEST['token']) && !empty($_REQUEST['token']) ? trim($_REQUEST['token']) : '';
     if (empty($token)) {
         return $this->redirectLoginPage('customer/account');
     }
     $this->_messageManager = $this->_objectManager->get('Magento\\Framework\\Message\\ManagerInterface');
     $this->_helperActivation = $this->_objectManager->get('LoginRadius\\Activation\\Model\\Helper\\Data');
     $this->_accountManagement = $this->_objectManager->get('Magento\\Customer\\Api\\AccountManagementInterface');
     $this->_customerUrl = $this->_objectManager->get('Magento\\Customer\\Model\\Url');
     $this->_storeManager = $this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface');
     $this->_helperCustomerRegistration = $this->_objectManager->get('LoginRadius\\' . $this->_helperActivation->getAuthDirectory() . '\\Model\\Helper\\Data');
     $socialLoginObject = new \LoginRadiusSDK\SocialLogin\SocialLoginAPI($this->_helperActivation->siteApiKey(), $this->_helperActivation->siteApiSecret(), array('authentication' => false, 'output_format' => 'json'));
     if (!empty($token)) {
         // Social API's
         try {
             $accessTokenObject = $socialLoginObject->exchangeAccessToken($token);
         } catch (\LoginRadiusSDK\LoginRadiusException $e) {
             $this->_eventManager->dispatch('lr_logout_sso', array('exception' => $e));
         }
         if (isset($accessTokenObject->access_token) && !empty($accessTokenObject->access_token)) {
             $this->_accessToken = isset($accessTokenObject->access_token) && !empty($accessTokenObject->access_token) ? trim($accessTokenObject->access_token) : '';
             try {
                 $userProfileData = $socialLoginObject->getUserProfiledata($this->_accessToken);
             } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                 $e->getMessage();
                 $e->getErrorResponse();
             }
             if (isset($userProfileData) && isset($userProfileData->ID)) {
                 /* Checking  provider id in local database */
                 $socialEntityId = $this->getEntityIdbyProfileData($userProfileData);
                 if (isset($socialEntityId['is_verified']) && $socialEntityId['is_verified'] == true) {
                     $this->_customerSession->setLoginRadiusStatus('Error');
                     $this->_customerSession->setLoginRadiusMessage(__('This account is not confirmed. <a href="' . $this->_customerUrl->getEmailConfirmationUrl($socialEntityId['email']) . '"Click here to resend confirmation email.'));
                 } elseif ($this->_customerSession->isLoggedIn()) {
                     //Account Linking
                     if (empty($socialEntityId)) {
                         $customer = $this->_customerSession->getCustomer();
                         if ($this->_helperCustomerRegistration->enableRaas() == '1') {
                             $accountAPI = new \LoginRadiusSDK\CustomerRegistration\AccountAPI($this->_helperActivation->siteApiKey(), $this->_helperActivation->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
                             try {
                                 $accountLink = $accountAPI->accountLink($this->_customerSession->getLoginRadiusUid(), $userProfileData->ID, $userProfileData->Provider);
                             } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                                 //$this->_eventManager->dispatch('lr_logout_sso', array('exception' => $e));
                             }
                         } else {
                             if ($this->isAccountLinkablesocialId($customer->getId(), $userProfileData->Provider)) {
                                 $accountLink = new \stdClass();
                                 $accountLink->isPosted = true;
                             }
                         }
                         if (isset($accountLink) && $accountLink->isPosted == true) {
                             $this->socialLinkingData($customer->getId(), $userProfileData);
                             $this->_customerSession->setLoginRadiusStatus('Success');
                             $this->_customerSession->setLoginRadiusMessage('Your Account is successfully linked.');
                         } else {
                             //
                             $this->_customerSession->setLoginRadiusStatus('Error');
                             $this->_customerSession->setLoginRadiusMessage('This account is already linked with an account.');
                         }
                     } else {
                         //This account cant be linked
                         if ($this->_helperCustomerRegistration->enableRaas() == '1') {
                             $this->_customerSession->setLoginRadiusStatus('Error');
                             $this->_customerSession->setLoginRadiusMessage('This account is already linked with an account.');
                         } else {
                             $this->_customerSession->setLoginRadiusStatus('Error');
                             $this->_customerSession->setLoginRadiusMessage('Cannot link same provider.');
                         }
                     }
                     return $this->redirectLoginPage('customerregistration/accounts/linking');
                 } else {
                     /* If provider id exists then update user profile */
                     if (!empty($socialEntityId)) {
                         /* update query */
                         $customer = $this->updateEntitiesData($socialEntityId, $userProfileData);
                         $this->socialLinkingData($socialEntityId, $userProfileData, true);
                         if ($this->_helperCustomerRegistration->enableRaas() == '1') {
                             $accountAPI = new \LoginRadiusSDK\CustomerRegistration\AccountAPI($this->_helperActivation->siteApiKey(), $this->_helperActivation->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
                             try {
                                 $getAccount = $accountAPI->getAccounts($userProfileData->Uid);
                             } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                                 //$this->_eventManager->dispatch('lr_logout_sso', array('exception' => $e));
                             }
                             if (isset($getAccount) && !empty($getAccount)) {
                                 foreach ($getAccount as $key => $value) {
                                     $output = '';
                                     $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
                                     $ruleTable = $resource->getTableName('lr_sociallogin');
                                     $connection = $resource->getConnection();
                                     $select = $connection->select()->from(['r' => $ruleTable])->where('uid=?', $value->Uid)->where('provider=?', $value->Provider);
                                     $output = $connection->fetchAll($select);
                                     if (empty($output)) {
                                         $this->socialLinkingData($socialEntityId, $value);
                                     }
                                 }
                             }
                         }
                         return $this->setCustomerLoggedIn($customer, $userProfileData);
                     } else {
                         /* Checking if email is not empty */
                         $email = isset($_REQUEST['email']) && !empty($_REQUEST['email']) ? trim($_REQUEST['email']) : '';
                         $isActive = 1;
                         //$userProfileData->Email[0]->Value = $email;
                         if (!empty($email)) {
                             $userProfileData->Email = array(json_decode(json_encode(array('Value' => $email))));
                             $userProfileData->EmailVerified = true;
                             $isActive = 0;
                         }
                         if (isset($userProfileData->Email[0]->Value) && !empty($userProfileData->Email[0]->Value)) {
                             $customerEmail = $this->getEntityIdbyEmail($userProfileData->Email[0]->Value);
                             if (isset($customerEmail[0]['email']) && !empty($customerEmail[0]['email'])) {
                                 if (!empty($email)) {
                                     $this->_customerSession->setLoginRadiusAccessToken($this->_accessToken);
                                     $this->_customerSession->setLoginRadiusPopupMessage('emailexist');
                                     $resultPageFactory = $this->_objectManager->get('\\Magento\\Framework\\View\\Result\\PageFactory');
                                     $resultPage = $resultPageFactory->create();
                                     $resultPage->getConfig()->getTitle()->set('');
                                     $block = $resultPage->getLayout()->getBlock('emailpopup');
                                     if ($block) {
                                         $block->setRefererUrl($this->_redirect->getRefererUrl());
                                     }
                                     return $resultPage;
                                 }
                                 $customer = $this->updateEntitiesData($customerEmail[0]['entity_id'], $userProfileData);
                                 $this->socialLinkingData($customerEmail[0]['entity_id'], $userProfileData);
                                 return $this->setCustomerLoggedIn($customer, $userProfileData);
                             } else {
                                 // Register
                                 $customer = $this->saveEntitiesData($userProfileData, $isActive);
                                 $this->socialLinkingData($customer->getId(), $userProfileData);
                                 if (!empty($email)) {
                                     if ($this->_helperCustomerRegistration->enableRaas() != '1') {
                                         $this->_customerSession->setLoginRadiusStatus('Success');
                                         $this->_customerSession->setLoginRadiusMessage('An email has been sent to your email address. please verify your account.');
                                     } else {
                                         $this->_customerSession->setCustomerAsLoggedIn($customer);
                                     }
                                     return $this->redirectLoginPage('customer/account');
                                 } else {
                                     return $this->setCustomerLoggedIn($customer, $userProfileData, true);
                                 }
                             }
                         } else {
                             //show popup for ask email
                             if ($this->_helperCustomerRegistration->enableRaas() != '1') {
                                 $this->_customerSession->setLoginRadiusAccessToken($this->_accessToken);
                                 $this->_customerSession->setLoginRadiusPopupMessage('initial');
                                 $resultPageFactory = $this->_objectManager->get('\\Magento\\Framework\\View\\Result\\PageFactory');
                                 $resultPage = $resultPageFactory->create();
                                 $resultPage->getConfig()->getTitle()->set('');
                                 $block = $resultPage->getLayout()->getBlock('emailpopup');
                                 if ($block) {
                                     $block->setRefererUrl($this->_redirect->getRefererUrl());
                                 }
                                 return $resultPage;
                             }
                             $this->_eventManager->dispatch('lr_logout_sso', array('exception' => ''));
                             return;
                         }
                     }
                 }
             }
         }
         return $this->redirectLoginPage('customer/account');
     }
 }