I am trying to get the customer's name by POST Method API if it's logged in but when I hit the link the postman, returns the Customer's Name even if it's not logged in. Please take a look
CODE:
<?php
namespace Vendor\Login\Model\Customer;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Block\Account\AuthorizationLink;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Url;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\LocalizedException;
//use Vendor\Login\Controller\Index\ApiController;
/**
* Implementing the logic
*/
class Extra
{
protected AuthorizationLink $ath;
protected UserContextInterface $userContext;
/**
* @var Session
*/
protected Session $customerSession;
/**
* @var AccountManagementInterface
*/
protected AccountManagementInterface $customerAccountManagement;
/**
* @var Url
*/
protected Url $customerUrl;
protected JsonFactory $jsonFactory;
/**
* @param Context $context
* @param Url $customerUrl
* @param AccountManagementInterface $customerAccountManagement
* @param Session $customerSession
* @param JsonFactory $jsonFactory
* @param UserContextInterface $userContext
* @param AuthorizationLink $ath
*/
public function __construct(
Context $context,
Url $customerUrl,
AccountManagementInterface $customerAccountManagement,
Session $customerSession,
JsonFactory $jsonFactory,
UserContextInterface $userContext,
AuthorizationLink $ath
) {
parent::__construct($context);
$this->customerUrl = $customerUrl;
$this->customerAccountManagement = $customerAccountManagement;
$this->customerSession = $customerSession;
$this->jsonFactory = $jsonFactory;
$this->userContext = $userContext;
$this->ath = $ath;
}
/**
* @param string $email
* @param string $password
* @return array[]
* @throws LocalizedException
*/
public function login(string $email, string $password): array
{
$validate = array();
$login = array();
$result = $this->jsonFactory->create();
$customerinfo = array();
if ($email) {
$login['username'] = $email;
}
if ($password) {
$login['password'] = $password;
}
try {
if (($email == null) || ($password == null)) {
$message = __('Invalid Username');
return array($message);
}
else {
$customer = $this->customerAccountManagement->authenticate($email, $password);
$this->customerSession->setCustomerDataAsLoggedIn($customer);
$this->customerSession->regenerateId();
if (!$this->ath->isLoggedIn()) {
$customer_data = $this->customerSession->getCustomer()->getData();
$customerinfo = array(
"name" => $customer_data['firstname'] . $customer_data['lastname']
);
return array($customerinfo);
}
else {
$error = __('Error');
return array($error);
}
}
}
catch (AuthenticationException $e) {
$new = __('You are not logged in');
return array($new);
}
}
}