Skip to content

Commit

Permalink
Merge pull request #1170 from magento-okapis/2.2-develop-pr-1
Browse files Browse the repository at this point in the history
[Okapis] Bugs P1
  • Loading branch information
cpartica authored Jun 6, 2017
2 parents 6086595 + 48051a4 commit b98c652
Show file tree
Hide file tree
Showing 24 changed files with 1,444 additions and 50 deletions.
57 changes: 57 additions & 0 deletions app/code/Magento/Integration/Cron/CleanExpiredTokens.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Integration\Cron;

use Magento\Integration\Model\ResourceModel\Oauth\Token as TokenResourceModel;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Integration\Helper\Oauth\Data as OauthHelper;

/**
* Cron class for deleting expired OAuth tokens.
*/
class CleanExpiredTokens
{
/**
* @var TokenResourceModel
*/
private $tokenResourceModel;

/**
* @var OauthHelper
*/
private $oauthHelper;

/**
* Initialize dependencies.
*
* @param TokenResourceModel $tokenResourceModel
* @param OauthHelper $oauthHelper
*/
public function __construct(
TokenResourceModel $tokenResourceModel,
OauthHelper $oauthHelper
) {
$this->tokenResourceModel = $tokenResourceModel;
$this->oauthHelper = $oauthHelper;
}

/**
* Delete expired customer and admin tokens.
*
* @return void
*/
public function execute()
{
$this->tokenResourceModel->deleteExpiredTokens(
$this->oauthHelper->getAdminTokenLifetime(),
[UserContextInterface::USER_TYPE_ADMIN]
);
$this->tokenResourceModel->deleteExpiredTokens(
$this->oauthHelper->getCustomerTokenLifetime(),
[UserContextInterface::USER_TYPE_CUSTOMER]
);
}
}
47 changes: 27 additions & 20 deletions app/code/Magento/Integration/Helper/Oauth/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,7 @@ public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $
public function isCleanupProbability()
{
// Safe get cleanup probability value from system configuration
$configValue = (int)$this->_scopeConfig->getValue(
self::XML_PATH_CLEANUP_PROBABILITY,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
$configValue = (int)$this->_scopeConfig->getValue(self::XML_PATH_CLEANUP_PROBABILITY);
return $configValue > 0 ? 1 == \Magento\Framework\Math\Random::getRandomNumber(1, $configValue) : false;
}

Expand All @@ -77,10 +74,7 @@ public function isCleanupProbability()
*/
public function getCleanupExpirationPeriod()
{
$minutes = (int)$this->_scopeConfig->getValue(
self::XML_PATH_CLEANUP_EXPIRATION_PERIOD,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
$minutes = (int)$this->_scopeConfig->getValue(self::XML_PATH_CLEANUP_EXPIRATION_PERIOD);
return $minutes > 0 ? $minutes : self::CLEANUP_EXPIRATION_PERIOD_DEFAULT;
}

Expand All @@ -91,10 +85,7 @@ public function getCleanupExpirationPeriod()
*/
public function getConsumerExpirationPeriod()
{
$seconds = (int)$this->_scopeConfig->getValue(
self::XML_PATH_CONSUMER_EXPIRATION_PERIOD,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
$seconds = (int)$this->_scopeConfig->getValue(self::XML_PATH_CONSUMER_EXPIRATION_PERIOD);
return $seconds > 0 ? $seconds : self::CONSUMER_EXPIRATION_PERIOD_DEFAULT;
}

Expand All @@ -105,10 +96,7 @@ public function getConsumerExpirationPeriod()
*/
public function getConsumerPostMaxRedirects()
{
$redirects = (int)$this->_scopeConfig->getValue(
self::XML_PATH_CONSUMER_POST_MAXREDIRECTS,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
$redirects = (int)$this->_scopeConfig->getValue(self::XML_PATH_CONSUMER_POST_MAXREDIRECTS);
return $redirects > 0 ? $redirects : 0;
}

Expand All @@ -119,10 +107,29 @@ public function getConsumerPostMaxRedirects()
*/
public function getConsumerPostTimeout()
{
$seconds = (int)$this->_scopeConfig->getValue(
self::XML_PATH_CONSUMER_POST_TIMEOUT,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
$seconds = (int)$this->_scopeConfig->getValue(self::XML_PATH_CONSUMER_POST_TIMEOUT);
return $seconds > 0 ? $seconds : self::CONSUMER_POST_TIMEOUT_DEFAULT;
}

/**
* Get customer token lifetime from config.
*
* @return int hours
*/
public function getCustomerTokenLifetime()
{
$hours = (int)$this->_scopeConfig->getValue('oauth/access_token_lifetime/customer');
return $hours > 0 ? $hours : 0;
}

/**
* Get customer token lifetime from config.
*
* @return int hours
*/
public function getAdminTokenLifetime()
{
$hours = (int)$this->_scopeConfig->getValue('oauth/access_token_lifetime/admin');
return $hours > 0 ? $hours : 0;
}
}
26 changes: 26 additions & 0 deletions app/code/Magento/Integration/Model/ResourceModel/Oauth/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,32 @@ public function deleteOldEntries($minutes)
}
}

/**
* Delete expired tokens for the specified user types
*
* @param int $hours token lifetime
* @param int[] $userTypes @see \Magento\Authorization\Model\UserContextInterface
* @return int number of deleted tokens
*/
public function deleteExpiredTokens($hours, $userTypes)
{
if ($hours > 0) {
$connection = $this->getConnection();

$userTypeCondition = $connection->quoteInto('user_type IN (?)', $userTypes);
$createdAtCondition = $connection->quoteInto(
'created_at <= ?',
$this->_dateTime->formatDate($this->date->gmtTimestamp() - $hours * 60 * 60)
);
return $connection->delete(
$this->getMainTable(),
$userTypeCondition . ' AND ' . $createdAtCondition
);
} else {
return 0;
}
}

/**
* Select a single token of the specified type for the specified consumer.
*
Expand Down
40 changes: 40 additions & 0 deletions app/code/Magento/Integration/Test/Unit/Helper/Oauth/DataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,44 @@ public function testGetConsumerPostTimeoutNonZero()
$this->_scopeConfigMock->expects($this->once())->method('getValue')->will($this->returnValue(10));
$this->assertEquals(10, $this->_dataHelper->getConsumerPostTimeout());
}

public function testGetCustomerTokenLifetimeNotEmpty()
{
$this->_scopeConfigMock
->expects($this->once())
->method('getValue')
->with('oauth/access_token_lifetime/customer')
->will($this->returnValue(10));
$this->assertEquals(10, $this->_dataHelper->getCustomerTokenLifetime());
}

public function testGetCustomerTokenLifetimeEmpty()
{
$this->_scopeConfigMock
->expects($this->once())
->method('getValue')
->with('oauth/access_token_lifetime/customer')
->will($this->returnValue(null));
$this->assertEquals(0, $this->_dataHelper->getCustomerTokenLifetime());
}

public function testGetAdminTokenLifetimeNotEmpty()
{
$this->_scopeConfigMock
->expects($this->once())
->method('getValue')
->with('oauth/access_token_lifetime/admin')
->will($this->returnValue(10));
$this->assertEquals(10, $this->_dataHelper->getAdminTokenLifetime());
}

public function testGetAdminTokenLifetimeEmpty()
{
$this->_scopeConfigMock
->expects($this->once())
->method('getValue')
->with('oauth/access_token_lifetime/admin')
->will($this->returnValue(null));
$this->assertEquals(0, $this->_dataHelper->getAdminTokenLifetime());
}
}
11 changes: 11 additions & 0 deletions app/code/Magento/Integration/etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@
<label>OAuth</label>
<tab>service</tab>
<resource>Magento_Integration::config_oauth</resource>
<group id="access_token_lifetime" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Access Token Expiration</label>
<field id="customer" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0" canRestore="1">
<label>Customer Token Lifetime (hours)</label>
<comment>We will disable this feature if the value is empty.</comment>
</field>
<field id="admin" translate="label" type="text" sortOrder="60" showInDefault="1" showInWebsite="0" showInStore="0" canRestore="1">
<label>Admin Token Lifetime (hours)</label>
<comment>We will disable this feature if the value is empty.</comment>
</field>
</group>
<group id="cleanup" translate="label" type="text" sortOrder="300" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Cleanup Settings</label>
<field id="cleanup_probability" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0" canRestore="1">
Expand Down
4 changes: 4 additions & 0 deletions app/code/Magento/Integration/etc/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
<max_failures_count>6</max_failures_count>
<timeout>1800</timeout>
</authentication_lock>
<access_token_lifetime>
<customer>1</customer>
<admin>4</admin>
</access_token_lifetime>
</oauth>
</default>
</config>
3 changes: 3 additions & 0 deletions app/code/Magento/Integration/etc/crontab.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@
<job name="outdated_authentication_failures_cleanup" instance="Magento\Integration\Cron\CleanExpiredAuthenticationFailures" method="execute">
<schedule>* * * * *</schedule>
</job>
<job name="expired_tokens_cleanup" instance="Magento\Integration\Cron\CleanExpiredTokens" method="execute">
<schedule>0 * * * *</schedule>
</job>
</group>
</config>
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

namespace Magento\Persistent\Model\Checkout;

use Magento\Checkout\Model\GuestPaymentInformationManagement;
use Magento\Checkout\Model\Session;

/**
* Plugin to convert shopping cart from persistent cart to guest cart before order save when customer not logged in
*/
class GuestPaymentInformationManagementPlugin
{
/**
* Persistence Session Helper
*
* @var \Magento\Persistent\Helper\Session
*/
private $persistenceSessionHelper;

/**
* Persistence Data Helper
*
* @var \Magento\Persistent\Helper\Data
*/
private $persistenceDataHelper;

/**
* Customer Session
*
* @var \Magento\Customer\Model\Session
*/
private $customerSession;

/**
* Checkout Session
*
* @var \Magento\Checkout\Model\Session
*/
private $checkoutSession;

/**
* Quote Manager
*
* @var \Magento\Persistent\Model\QuoteManager
*/
private $quoteManager;

/**
* Cart Repository
*
* @var \Magento\Quote\Api\CartRepositoryInterface
*/
private $cartRepository;

/**
* Initialize dependencies
*
* @param \Magento\Persistent\Helper\Data $persistenceDataHelper
* @param \Magento\Persistent\Helper\Session $persistenceSessionHelper
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Persistent\Model\QuoteManager $quoteManager
* @param \Magento\Quote\Api\CartRepositoryInterface $cartRepository
*/
public function __construct(
\Magento\Persistent\Helper\Data $persistenceDataHelper,
\Magento\Persistent\Helper\Session $persistenceSessionHelper,
\Magento\Customer\Model\Session $customerSession,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Persistent\Model\QuoteManager $quoteManager,
\Magento\Quote\Api\CartRepositoryInterface $cartRepository
) {
$this->persistenceDataHelper = $persistenceDataHelper;
$this->persistenceSessionHelper = $persistenceSessionHelper;
$this->customerSession = $customerSession;
$this->checkoutSession = $checkoutSession;
$this->quoteManager = $quoteManager;
$this->cartRepository = $cartRepository;
}

/**
* Convert customer cart to guest cart before order is placed if customer is not logged in
*
* @param GuestPaymentInformationManagement $subject
* @param string $cartId
* @param string $email
* @param \Magento\Quote\Api\Data\PaymentInterface $paymentMethod
* @param \Magento\Quote\Api\Data\AddressInterface|null $billingAddress
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeSavePaymentInformationAndPlaceOrder(
GuestPaymentInformationManagement $subject,
$cartId,
$email,
\Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
\Magento\Quote\Api\Data\AddressInterface $billingAddress = null
) {
if ($this->persistenceSessionHelper->isPersistent()
&& !$this->customerSession->isLoggedIn()
&& $this->persistenceDataHelper->isShoppingCartPersist()
&& $this->quoteManager->isPersistent()
) {
$this->customerSession->setCustomerId(null);
$this->customerSession->setCustomerGroupId(null);
$this->quoteManager->convertCustomerCartToGuest();
/** @var \Magento\Quote\Api\Data\CartInterface $quote */
$quote = $this->cartRepository->get($this->checkoutSession->getQuote()->getId());
$quote->setCustomerEmail($email);
$quote->getAddressesCollection()->walk('setEmail', ['email' => $email]);
$this->cartRepository->save($quote);
}
}
}
Loading

0 comments on commit b98c652

Please sign in to comment.