/**
  * 
  * @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;
 }
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $activationHelper = $this->_objectManager->get('LoginRadius\\Activation\\Model\\Helper\\Data');
     $customerRegistrationHelper = $this->_objectManager->get("LoginRadius" . "\\" . $activationHelper->getAuthDirectory() . "\\Model\\Helper\\Data");
     if ($customerRegistrationHelper->enableRaas() != '1') {
         return;
     }
     $customer = $observer->getEvent()->getCustomer();
     $customerId = $customer->getId();
     $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
     $changelogName = $resource->getTableName('lr_sociallogin');
     $connection = $resource->getConnection();
     $select = $connection->select()->from(['r' => $changelogName])->where('entity_id=?', $customerId);
     $output = $connection->fetchAll($select);
     /* Delete raas profile from local db */
     $accountAPI = new \LoginRadiusSDK\CustomerRegistration\AccountAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
     try {
         $output[0]['uid'] = isset($output[0]['uid']) ? $output[0]['uid'] : '';
         if (!empty($output[0]['uid'])) {
             $userRaasDelete = $accountAPI->deleteAccount($output[0]['uid']);
             $changelogName = $resource->getTableName('lr_sociallogin');
             $connection = $resource->getConnection();
             $where = array("entity_id =" . $customerId);
             $connection->delete($changelogName, $where);
         }
     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
     }
 }
 public function updateUserStatus($entity_id)
 {
     $result = Mage::helper('sociallogin/data')->loginRadiusRead("lr_sociallogin", "get status", array($entity_id), true);
     if (isset($result['status']) && $result['status'] == 'blocked') {
         $params['isblock'] = 'false';
         $displayText = "Block";
         $tableStatus = 'unblocked';
     } else {
         $params['isblock'] = 'true';
         $displayText = 'Unblock';
         $tableStatus = 'blocked';
     }
     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'));
     $accountAPI->setStatus($result['uid'], $params['isblock']);
     Mage::helper('sociallogin/data')->SocialLoginInsert("lr_sociallogin", array('status' => $tableStatus, 'entity_id' => $entity_id), true, '', true);
     die($displayText);
 }
 /**
  * Load the page defined in view/frontend/layout/samplenewpage_index_index.xml
  *
  * @return \Magento\Framework\View\Result\Page
  */
 public function execute()
 {
     ///////////////////////////////////RAAS Linking Interface////////////////////////////////////////
     /** @var \Magento\Framework\App\ObjectManager $om */
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     /** @var \Magento\Framework\App\Http\Context $context */
     $context = $objectManager->get('Magento\\Framework\\App\\Http\\Context');
     /** @var bool $isLoggedIn */
     $isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
     $customerSession = $objectManager->get('Magento\\Customer\\Model\\Session');
     $redirectPage = 'customer/account';
     if ($isLoggedIn) {
         $providerid = isset($_REQUEST['providerid']) && !empty($_REQUEST['providerid']) ? trim($_REQUEST['providerid']) : '';
         $provider = isset($_REQUEST['provider']) && !empty($_REQUEST['provider']) ? trim($_REQUEST['provider']) : '';
         $redirectPage = '';
         if (!empty($providerid) && !empty($provider)) {
             $this->_helperActivation = $this->_objectManager->get('LoginRadius\\Activation\\Model\\Helper\\Data');
             $customerRegistrationHelper = $this->_objectManager->get('LoginRadius\\CustomerRegistration\\Model\\Helper\\Data');
             if ($customerRegistrationHelper->enableRaas() == '1') {
                 $accountAPI = new \LoginRadiusSDK\CustomerRegistration\AccountAPI($this->_helperActivation->siteApiKey(), $this->_helperActivation->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
                 try {
                     $accountUnlink = $accountAPI->accountUnlink($customerSession->getLoginRadiusUid(), $providerid, $provider);
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                     //$this->_eventManager->dispatch('lr_logout_sso', array('exception' => $e));
                 }
             } else {
                 $linkedAccounts = $customerRegistrationHelper->selectSocialLinkingData($customerSession->getId());
                 if (is_array($linkedAccounts) && count($linkedAccounts) > 0) {
                     foreach ($linkedAccounts as $linkedAccount) {
                         if ($linkedAccount['sociallogin_id'] == $providerid && $linkedAccount['provider'] == $provider) {
                             $accountUnlink = new \stdClass();
                             $accountUnlink->isPosted = true;
                         }
                     }
                 }
             }
             $this->_messageManager = $this->_objectManager->get('Magento\\Framework\\Message\\ManagerInterface');
             if (isset($accountUnlink) && $accountUnlink->isPosted == true) {
                 $this->removeSocialLinkingData($providerid);
                 $customerSession->setLoginRadiusStatus('Success');
                 $customerSession->setLoginRadiusMessage('Your Account has been Removed successfully.');
             } else {
                 $customerSession->setLoginRadiusStatus('Error');
                 $customerSession->setLoginRadiusMessage('You can not remove this account.');
             }
             $redirectPage = 'customerregistration/accounts/linking';
         }
         if (empty($redirectPage)) {
             $resultPage = $this->_resultPageFactory->create();
             $resultPage->getConfig()->getTitle()->set('');
             $block = $resultPage->getLayout()->getBlock('accountlinking');
             if ($block) {
                 $block->setRefererUrl($this->_redirect->getRefererUrl());
             }
         }
     }
     if (!empty($redirectPage)) {
         $resultPage = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
         $resultPage->setPath($redirectPage);
     }
     return $resultPage;
 }
 public function admin_customer_save_before($observer)
 {
     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');
     $userAPI = new LoginRadiusSDK\CustomerRegistration\UserAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
     $postData = Mage::app()->getRequest()->getPost();
     $formattedDate = '';
     if (isset($postData['account']['dob']) && !empty($postData['account']['dob'])) {
         $dateString = strtotime($postData['account']['dob']);
         $formattedDate = date('m-d-Y', $dateString);
     }
     /**
      * Creating user on RAAS
      */
     if (!isset($postData['customer_id'])) {
         if ($postData['account']['website_id'] != 0) {
             $params = array('EmailId' => $postData['account']['email'], 'firstname' => $postData['account']['firstname'], 'lastname' => $postData['account']['lastname'], 'birthdate' => $formattedDate, 'password' => $postData['account']['password']);
             if (isset($postData['account']['gender'])) {
                 if ($postData['account']['gender'] == '1') {
                     $params['gender'] = 'M';
                 } elseif ($postData['account']['gender'] == '0') {
                     $params['gender'] = 'F';
                 }
             }
             if ($postData['account']['password'] == 'auto') {
                 $charsPass = "******";
                 $autoGenratedPassParams = array('EmailId' => $postData['account']['email'], 'firstname' => $postData['account']['firstname'], 'lastname' => $postData['account']['lastname'], 'birthdate' => $formattedDate, 'password' => substr(str_shuffle($charsPass), 0, 8));
                 try {
                     $response = $userAPI->create($params);
                     $_POST['lr_raas_resonse'] = $response;
                     $forgotPassDomain = Mage::getBaseUrl() . 'customerregistration/index/verification/';
                     try {
                         $rsetPasswordUrl = 'https://api.loginradius.com/raas/client/password/forgot?apikey=' . $activationBlockObj->apiKey() . '&emailid=' . $postData['account']['email'] . '&resetpasswordurl=' . $forgotPassDomain;
                     } catch (LoginRadiusSDK\LoginRadiusException $e) {
                         Mage::throwException($e->getErrorResponse()->description);
                     }
                     $result = LoginRadiusSDK\LoginRadius::apiClient($rsetPasswordUrl, FALSE, array('output_format' => 'json'));
                 } catch (LoginRadiusSDK\LoginRadiusException $e) {
                     Mage::throwException($e->getErrorResponse()->description);
                 }
             } else {
                 try {
                     $response = $userAPI->create($params);
                     $_POST['lr_raas_resonse'] = $response;
                 } catch (LoginRadiusSDK\LoginRadiusException $e) {
                     Mage::throwException($e->getErrorResponse()->description);
                 }
             }
         }
     } else {
         // Updating user profile
         $params = array('EmailId' => $postData['account']['email'], 'firstname' => $postData['account']['firstname'], 'lastname' => $postData['account']['lastname'], 'birthdate' => $formattedDate);
         if (isset($postData['account']['gender'])) {
             if ($postData['account']['gender'] == '1') {
                 $params['gender'] = 'M';
             } elseif ($postData['account']['gender'] == '0') {
                 $params['gender'] = 'F';
             }
         }
         $connection = Mage::getSingleton('core/resource');
         $readConnection = $connection->getConnection('core_read');
         $tableName = $connection->getTableName('lr_sociallogin');
         $query = "select sociallogin_id, uid from {$tableName} where entity_id= '" . $postData['customer_id'] . "'";
         $result = $readConnection->query($query)->fetch();
         if (isset($result['sociallogin_id']) && !empty($result['sociallogin_id'])) {
             //Code for password changing
             if (isset($postData['account']['new_password']) && !empty($postData['account']['new_password'])) {
                 $accountAPI = new LoginRadiusSDK\CustomerRegistration\AccountAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
                 $getRaasProfile = $accountAPI->getAccounts($result['uid']);
                 $checkProviderStatus = '';
                 foreach ($getRaasProfile as $key => $value) {
                     if ($value->Provider == 'RAAS') {
                         $checkProviderStatus = 'true';
                     }
                 }
                 if ($checkProviderStatus == 'true') {
                     if ($postData['account']['new_password'] == 'auto') {
                         $forgotPassDomain = Mage::getBaseUrl() . 'customerregistration/index/verification/';
                         try {
                             $rsetPasswordUrl = 'https://api.loginradius.com/raas/client/password/forgot?apikey=' . $activationBlockObj->apiKey() . '&emailid=' . $postData['account']['email'] . '&resetpasswordurl=' . $forgotPassDomain;
                         } catch (LoginRadiusSDK\LoginRadiusException $e) {
                             Mage::throwException($e->getErrorResponse()->description);
                         }
                         $result = LoginRadiusSDK\LoginRadius::apiClient($rsetPasswordUrl, FALSE, array('output_format' => 'json'));
                     } else {
                         try {
                             $accountAPI->setPassword(trim($result['uid']), trim($postData['account']['new_password']));
                         } catch (LoginRadiusSDK\LoginRadiusException $e) {
                             Mage::throwException($e->getErrorResponse()->description);
                         }
                     }
                 } else {
                     if ($postData['account']['new_password'] == 'auto') {
                         $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%^&*()_-=?";
                         try {
                             $data = array('accountid' => trim($result['uid']), 'emailid' => trim($postData['account']['email']), 'password' => substr(str_shuffle($chars), 0, 8));
                             $res = $accountAPI->createUserRegistrationProfile($data);
                             try {
                                 $forgotPassDomain = Mage::getBaseUrl() . 'customerregistration/index/verification/';
                                 try {
                                     $rsetPasswordUrl = 'https://api.loginradius.com/raas/client/password/forgot?apikey=' . $activationBlockObj->apiKey() . '&emailid=' . $postData['account']['email'] . '&resetpasswordurl=' . $forgotPassDomain;
                                 } catch (LoginRadiusSDK\LoginRadiusException $e) {
                                     Mage::throwException($e->getErrorResponse()->description);
                                 }
                                 $result = LoginRadiusSDK\LoginRadius::apiClient($rsetPasswordUrl, FALSE, array('output_format' => 'json'));
                             } catch (LoginRadiusSDK\LoginRadiusException $e) {
                                 Mage::throwException($e->getErrorResponse()->description);
                             }
                         } catch (LoginRadiusSDK\LoginRadiusException $e) {
                             Mage::throwException($e->getErrorResponse()->description);
                         }
                     } else {
                         try {
                             $data = array('accountid' => trim($result['uid']), 'emailid' => trim($postData['account']['email']), 'password' => trim($postData['account']['new_password']));
                             $res = $accountAPI->createUserRegistrationProfile($data);
                         } catch (LoginRadiusSDK\LoginRadiusException $e) {
                             Mage::throwException($e->getErrorResponse()->description);
                         }
                     }
                 }
             }
             $connectionDb = Mage::getSingleton('core/resource');
             $readConnectionDb = $connection->getConnection('core_read');
             $tableNameCustomer = $connection->getTableName('customer_entity');
             $queryCustomer = "select email from {$tableNameCustomer} where entity_id= '" . $postData['customer_id'] . "'";
             $resultCustomer = $readConnectionDb->query($queryCustomer)->fetch();
             if ($postData['account']['email'] != $resultCustomer["email"]) {
                 $accountAPI = new LoginRadiusSDK\CustomerRegistration\AccountAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
                 /* Adding New Email by Add/Remove Email Api */
                 $addEmailData = array('EmailId' => $postData['account']['email'], 'EmailType' => 'Primary');
                 try {
                     $addEmail = $accountAPI->userAdditionalEmail($result['uid'], 'add', $addEmailData);
                 } catch (LoginRadiusSDK\LoginRadiusException $e) {
                     if (isset($e->getErrorResponse()->description)) {
                         /* Getting Raas Profile By User Profile by UID Api */
                         $getRaasProfile = $accountAPI->getAccounts($result['uid']);
                         $providerStatus = '';
                         foreach ($getRaasProfile as $key => $value) {
                             if ($value->Provider == 'RAAS') {
                                 $providerStatus = 'true';
                             }
                         }
                         if ($providerStatus == 'true') {
                             $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                             Mage::throwException($errorDescription);
                         } else {
                             Mage::throwException('Please Set Password then change the email id.');
                         }
                     }
                     return;
                 }
                 if (isset($addEmail->isPosted) && $addEmail->isPosted == 'true') {
                     /* Removing Old Email by Add/Remove Email Api */
                     $removeEmailData = array('EmailId' => $resultCustomer["email"], 'EmailType' => 'Primary');
                     try {
                         $removeEmail = $accountAPI->userAdditionalEmail($result['uid'], 'remove', $removeEmailData);
                     } catch (LoginRadiusSDK\LoginRadiusException $e) {
                         Mage::throwException($e->getErrorResponse()->description);
                         return;
                     }
                 }
             }
             //                if(empty($postData['account']['new_password']) || $postData['account']['new_password'] != 'auto'){
             //
             //
             //                    try {
             //                        $customer = Mage::getSingleton("customer/session")->getCustomer();
             //
             //
             //                   $userAPI->edit($result['sociallogin_id'], $params);
             //
             //                } catch (LoginRadiusSDK\LoginRadiusException $e) {
             //
             //                    Mage::throwException($e->getErrorResponse()->description);
             //                    return;
             //                }
             //                }
         }
     }
 }
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $customer = $observer->getEvent()->getCustomerDataObject();
     $activationHelper = $this->_objectManager->get('LoginRadius\\Activation\\Model\\Helper\\Data');
     $customerRegistrationHelper = $this->_objectManager->get("LoginRadius" . "\\" . $activationHelper->getAuthDirectory() . "\\Model\\Helper\\Data");
     if ($customerRegistrationHelper->enableRaas() != '1') {
         return;
     }
     $customerSession = $this->_objectManager->get('Magento\\Customer\\Model\\Session');
     $editUserData = array('firstname' => $customer->getFirstname(), 'lastname' => $customer->getLastname(), 'emailid' => $customer->getEmail(), 'gender' => $customer->getGender(), 'birthdate' => $customer->getDob());
     $userAPI = new \LoginRadiusSDK\CustomerRegistration\UserAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
     try {
         $userEditdata = $userAPI->edit($customerSession->getLoginRadiusId(), $editUserData);
         /* Edit profile in local db */
     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
         if ($customerRegistrationHelper->debug() == '1') {
             $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
             $this->_messageManager->addError($errorDescription);
         }
     }
     if (isset($_REQUEST['changepassword']) && $_REQUEST['changepassword'] == '1') {
         $accountAPI = new \LoginRadiusSDK\CustomerRegistration\AccountAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
         $postData = $_REQUEST;
         if (isset($postData['emailid']) && !empty($postData['emailid'])) {
             if ($customerRegistrationHelper->minPassword() != 0 && $customerRegistrationHelper->minPassword() > strlen($postData['password'])) {
                 $this->_messageManager->addError('The Password field must be at least ' . $customerRegistrationHelper->minPassword() . ' characters in length.');
             } elseif ($customerRegistrationHelper->maxPassword() != 0 && strlen($postData['password']) > $customerRegistrationHelper->maxPassword()) {
                 $this->_messageManager->addError('The Password field must not exceed ' . $customerRegistrationHelper->maxPassword() . ' characters in length.');
             } elseif ($postData['password'] === $postData['confirmpassword']) {
                 //check both password
                 //setpassword
                 $data = array('accountid' => $customerSession->getLoginRadiusUid(), 'password' => trim($postData['password']), 'emailid' => trim($postData['emailid']));
                 try {
                     $setUserPassword = $accountAPI->createUserRegistrationProfile($data);
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                     $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                     $this->_messageManager->addError($errorDescription);
                 }
             } else {
                 //password not match
                 $this->_messageManager->addError('Password don\'t match');
             }
         } else {
             if (isset($postData['oldpassword']) && isset($postData['newpassword']) && isset($postData['confirmnewpassword'])) {
                 if ($customerRegistrationHelper->minPassword() != 0 && $customerRegistrationHelper->minPassword() > strlen($postData['newpassword'])) {
                     $this->_messageManager->addError('The Password field must be at least ' . $customerRegistrationHelper->minPassword() . ' characters in length.');
                 } elseif ($customerRegistrationHelper->maxPassword() != 0 && strlen($postData['newpassword']) > $customerRegistrationHelper->maxPassword()) {
                     $this->_messageManager->addError('The Password field must not exceed ' . $customerRegistrationHelper->maxPassword() . ' characters in length.');
                 } elseif ($postData['newpassword'] !== $postData['confirmnewpassword']) {
                     //password not match
                     $this->_messageManager->addError('Password and Confirm Password don\'t match');
                 } else {
                     try {
                         $changeUserPassword = $accountAPI->changeAccountPassword($customerSession->getLoginRadiusUid(), $postData['oldpassword'], $postData['newpassword']);
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     }
                 }
             }
         }
     }
 }
 /**
  * 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');
     }
 }
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $activationHelper = $this->_objectManager->get('LoginRadius\\Activation\\Model\\Helper\\Data');
     $customerRegistrationHelper = $this->_objectManager->get("LoginRadius" . "\\" . $activationHelper->getAuthDirectory() . "\\Model\\Helper\\Data");
     if ($customerRegistrationHelper->enableRaas() != '1') {
         return;
     }
     $events = $observer->getEvent();
     $customerData = $events->getRequest()->getPostValue();
     $customer = $observer->getEvent()->getCustomer();
     $this->_date = $this->_objectManager->create('Magento\\Framework\\Stdlib\\DateTime');
     $customer->setDob($this->_date->gmDate('m-d-Y', $this->_date->strToTime($customerData['customer']['dob'])));
     if (isset($_POST['customer']['entity_id'])) {
         $editUserData = array('firstname' => $customerData['customer']['firstname'], 'lastname' => $customerData['customer']['lastname'], 'birthdate' => $customer->getDob());
         $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
         $ruleTable = $resource->getTableName('lr_sociallogin');
         $connection = $resource->getConnection();
         $select = $connection->select()->from(['r' => $ruleTable])->where('entity_id=?', $customerData['customer']['entity_id']);
         $output = $connection->fetchAll($select);
         $userAPI = new \LoginRadiusSDK\CustomerRegistration\UserAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
         $accountApi = new \LoginRadiusSDK\CustomerRegistration\AccountAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
         /* Getting Raas Profile By User Profile by UID Api */
         $getRaasProfileEmailByUid = $accountApi->getAccounts($output[0]['uid']);
         $checkProvider = '';
         foreach ($getRaasProfileEmailByUid as $key => $value) {
             if ($getRaasProfileEmailByUid[$key]->Provider == 'RAAS') {
                 $emailRaas = $getRaasProfileEmailByUid[$key]->Email[0]->Value;
                 $checkProvider = 'true';
             }
         }
         if ($checkProvider == 'true') {
             if ($customerData['customer']['email'] != $emailRaas) {
                 /* Adding New Email by Add/Remove Email Api */
                 $addEmailData = array('EmailId' => $customerData['customer']['email'], 'EmailType' => 'Primary');
                 try {
                     $addEmailRaas = $accountApi->userAdditionalEmail($output[0]['uid'], 'add', $addEmailData);
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                     /* Getting Raas Profile By User Profile by UID Api */
                     $getRaasProfileByUid = $accountApi->getAccounts($output[0]['uid']);
                     $providerStatus = '';
                     foreach ($getRaasProfileByUid as $key => $value) {
                         if ($getRaasProfileByUid[$key]->Provider == 'RAAS') {
                             $providerStatus = 'true';
                         }
                     }
                     if ($providerStatus == 'true') {
                         $getRaasProfile = $userAPI->getProfileByID($output[0]['sociallogin_id']);
                         /* Updating email in local database */
                         $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
                         $updateRuleTable = $resource->getTableName('customer_entity');
                         $updateGridTable = $resource->getTableName('customer_grid_flat');
                         $updateConnection = $resource->getConnection();
                         $data = array("email" => $getRaasProfile->Email[0]->Value);
                         $updateConnection->update($updateRuleTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                         $updateConnection->update($updateGridTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     } else {
                         $getRaasProfile = $userAPI->getProfileByID($output[0]['sociallogin_id']);
                         /* Updating email in local database */
                         $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
                         $updateRuleTable = $resource->getTableName('customer_entity');
                         $updateGridTable = $resource->getTableName('customer_grid_flat');
                         $updateConnection = $resource->getConnection();
                         $data = array("email" => $getRaasProfile->Email[0]->Value);
                         $updateConnection->update($updateRuleTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                         $updateConnection->update($updateGridTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError('Please Reset Set Password then change the email id.');
                     }
                 }
                 if (isset($addEmailRaas->isPosted) && $addEmailRaas->isPosted == 'true') {
                     // $getRaasProfile = $userAPI->getProfileByID($output[0]['sociallogin_id']);
                     $getRaasProfileUid = $accountApi->getAccounts($output[0]['uid']);
                     foreach ($getRaasProfileUid as $key => $value) {
                         if ($getRaasProfileUid[$key]->Provider == 'RAAS') {
                             $raasEmail = $getRaasProfileUid[$key]->Email[0]->Value;
                         }
                     }
                     /* Removing Old Email by Add/Remove Email Api */
                     $removeEmailData = array('EmailId' => $raasEmail, 'EmailType' => 'Primary');
                     try {
                         $removeEmail = $accountApi->userAdditionalEmail($output[0]['uid'], 'remove', $removeEmailData);
                         try {
                             $getUserDataByEmail = $userAPI->getProfileByEmail($customerData['customer']['email']);
                             try {
                                 $userEditdata = $userAPI->edit($getUserDataByEmail[0]->ID, $editUserData);
                             } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                                 $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                                 $this->_messageManager->addError($errorDescription);
                             }
                         } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         }
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     }
                 }
             } else {
                 try {
                     $getUserDataByEmail = $userAPI->getProfileByEmail($customerData['customer']['email']);
                     try {
                         $userEditdata = $userAPI->edit($getUserDataByEmail[0]->ID, $editUserData);
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     }
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                 }
             }
         } else {
             try {
                 $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%^&*()_-=?";
                 $data = array('accountid' => $output[0]['uid'], 'emailid' => $customerData['customer']['email'], 'password' => substr(str_shuffle($chars), 0, 8));
                 $accountApi->createUserRegistrationProfile($data);
                 /* Updating Basic profile */
                 try {
                     $getUserDataByEmail = $userAPI->getProfileByEmail($customerData['customer']['email']);
                     try {
                         $userEditdata = $userAPI->edit($getUserDataByEmail[0]->ID, $editUserData);
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     }
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                     $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                     $this->_messageManager->addError($errorDescription);
                 }
             } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                 $getRaasProfile = $userAPI->getProfileByID($output[0]['sociallogin_id']);
                 /* Updating email in local database */
                 $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
                 $updateRuleTable = $resource->getTableName('customer_entity');
                 $updateGridTable = $resource->getTableName('customer_grid_flat');
                 $updateConnection = $resource->getConnection();
                 $data = array("email" => $getRaasProfile->Email[0]->Value);
                 $updateConnection->update($updateRuleTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                 $updateConnection->update($updateGridTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                 //$errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                 $this->_messageManager->addError('Not able to change the email of social user.');
             }
             return;
         }
     }
 }