Question

I'm making a call to Magento API and I need to save the current admin id

POST /rest/V1/precart/create HTTP/1.1
Host: magento2.local
Content-Type: application/json
Authorization: Bearer 59f6t7aso8a37g1hxbkd5ol0pem3cd3b
Cache-Control: no-cache
Postman-Token: 7456cf04-634e-4f6f-acb9-c85ca18d849a

{
    "preCart" : {
        "sku": "123",
    }
}

I tried some suggestions, but I think this only work with normal site session. How I do this by API?

protected $_authSession;
public function __construct(
    \Magento\Backend\Model\Auth\Session $authSession,
    ...
)
{
    $this->_authSession = $authSession;
    ...
}

/**
 * Processing data before model save
 *
 * @return $this
 */
public function beforeSave()
{    
    if (empty($this->getUserId()) && $user = $this->getCurrentUser()) {
        $this->setUserId($user->getId());
    }

    return parent::beforeSave();
}
/**
 * @return \Magento\User\Model\User|null
 */
public function getCurrentUser()
{
    return $this->_authSession->getUser();
}
Was it helpful?

Solution

We can do this using the user context.

User context store all user authentication types and returns the used.

See at: CompositeUserContext.php

How to use:

/**
 * @var \Magento\Authorization\Model\UserContextInterface 
 */
protected $_userContext;

/**
 * constructor.
 * @param \Magento\Authorization\Model\UserContextInterface $userContext
 */
public function __construct(
    \Magento\Authorization\Model\UserContextInterface $userContext,
)
{
    $this->_userContext = $userContext;
    parent::__construct();
}

/**
 * @return int
 */
public function getCurrentUserId()
{
    return $this->_userContext->getUserId();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top