Skip to content

Programatically logged in customer not persistent with magento 2 fpc enabled

i have created a a ajax controller which log in customer programatically after getting the otp from the customer and after getting the response i refresh the page , the problem is when full page caching is enabled it do not work properly and somtime the customer gets logged in and sometime not but if i disable full page caching , it works perfectly .

below is my js and controller code

js code

jQuery.ajax({
url:  baseUrl+'employeepopup/index/loginemployee',
type: "GET",
data: {email:email,mobile:mobile,emailDomain:emailDomain,isNumberPrefilled:isNumberPrefilled,employeeType:employeeType,otp:otp},
showLoader: true,
cache:false,
success:function(response){
    if(response == 'true'){
        location.reload();
    }
    else{
        $('body').trigger('processStop');
        $('.employee-error-msg').text('Incorrect OTP');
        $('.employee-error-msg').show();
    }
}

});

and in the controller i have

use MagentoCustomerModelSession;
use MagentoFrameworkControllerResultFactory;

class LoginEmployee extends MagentoFrameworkAppActionAction
{

public function __construct(
  Context $context,
  Session $customerSession,

) {
  $this->session = $customerSession;
  parent::__construct($context);
}

public function execute()
{

    $writer = new Zend_Log_Writer_Stream(BP . '/var/log/loogin.log');
    $logger = new Zend_Log();
    $logger->addWriter($writer);


    $customerData = $objectManager->create('MagentoCustomerModelCustomer');
    $customer = $customerData->getCollection()->addFieldToFilter("mobilenumber", $mobile)->getFirstItem();
    $this->session->setCustomerAsLoggedIn($customer);
    $this->session->regenerateId();
    $sessionid = $this->session->getSessionId();
    $logger->info("newly generate session id is " .$sessionid);
    $return = 'true';    
    
    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
    $logger->info("$return");
    $resultJson->setData($return);
    return $resultJson;
}
}