This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
@@ -0,0 +1,238 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Security\Model;
/**
* @magentoAppArea adminhtml
*/
class AdminSessionsManagerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Backend\Model\Auth
*/
protected $auth;
/**
* @var \Magento\Backend\Model\Auth\Session
*/
protected $authSession;
/**
* @var \Magento\Security\Model\AdminSessionInfo
*/
protected $adminSessionInfo;
/**
* @var \Magento\Security\Model\AdminSessionsManager
*/
protected $adminSessionsManager;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* Set up
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->objectManager->get(\Magento\Framework\Config\ScopeInterface::class)
->setCurrentScope(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$this->auth = $this->objectManager->create(\Magento\Backend\Model\Auth::class);
$this->authSession = $this->objectManager->create(\Magento\Backend\Model\Auth\Session::class);
$this->adminSessionInfo = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
$this->auth->setAuthStorage($this->authSession);
$this->messageManager = $this->objectManager->get(\Magento\Framework\Message\ManagerInterface::class);
$this->adminSessionsManager = $this->objectManager->create(\Magento\Security\Model\AdminSessionsManager::class);
}
/**
* Tear down
*/
protected function tearDown(): void
{
$this->auth = null;
$this->authSession = null;
$this->adminSessionInfo = null;
$this->adminSessionsManager = null;
$this->objectManager = null;
parent::tearDown();
}
/**
* Test if current admin user is logged out
*
* @magentoDbIsolation enabled
*/
public function testProcessLogout()
{
$this->auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$this->auth->logout();
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$this->assertEquals($this->adminSessionInfo->getStatus(), AdminSessionInfo::LOGGED_OUT);
}
/**
* Test if the admin session is created in database
*
* @magentoDbIsolation enabled
*/
public function testIsAdminSessionIsCreated()
{
$this->auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$this->assertGreaterThanOrEqual(1, (int)$this->adminSessionInfo->getId());
$this->auth->logout();
}
/**
* Test if other sessions are terminated if admin_account_sharing is disabled
*
* @magentoAdminConfigFixture admin/security/session_lifetime 100
* @magentoConfigFixture default_store admin/security/admin_account_sharing 0
* @magentoDbIsolation enabled
*/
public function testTerminateOtherSessionsProcessLogin()
{
$session = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
$session->setSessionId('669e2e3d752e8')
->setUserId(1)
->setStatus(1)
->setCreatedAt(time() - 10)
->setUpdatedAt(time() - 9)
->save();
$this->auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$session->load($adminSessionInfoId, 'id');
$this->assertEquals(
AdminSessionInfo::LOGGED_OUT_BY_LOGIN,
(int) $session->getStatus()
);
}
/**
* Test if current session is retrieved
*
* @magentoDbIsolation enabled
*/
public function testGetCurrentSession()
{
$this->auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$this->assertEquals(
$this->adminSessionInfo->getId(),
$this->adminSessionsManager->getCurrentSession()->getId()
);
}
/**
* Test if other sessions were logged out if logoutOtherUserSessions() action was performed
*
* @magentoAdminConfigFixture admin/security/session_lifetime 100
* @magentoConfigFixture default_store admin/security/admin_account_sharing 1
* @magentoDbIsolation enabled
*/
public function testLogoutOtherUserSessions()
{
/** @var \Magento\Security\Model\AdminSessionInfo $session */
$session = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
$session->setSessionId('669e2e3d752e8')
->setUserId(1)
->setStatus(1)
->setCreatedAt(time() - 50)
->setUpdatedAt(time() - 49)
->save();
$this->auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$collection = $this->getCollectionForLogoutOtherUserSessions($session);
$this->assertGreaterThanOrEqual(1, $collection->getSize());
$this->adminSessionsManager->logoutOtherUserSessions();
$collection = $this->getCollectionForLogoutOtherUserSessions($session);
$this->assertEquals(0, $collection->getSize());
}
/**
* Collection getter with filters populated for testLogoutOtherUserSessions() method
*
* @param AdminSessionInfo $session
* @return ResourceModel\AdminSessionInfo\Collection
*/
protected function getCollectionForLogoutOtherUserSessions(\Magento\Security\Model\AdminSessionInfo $session)
{
/** @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection $collection */
$collection = $session->getResourceCollection();
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$collection->filterByUser(
$this->authSession->getUser()->getId(),
\Magento\Security\Model\AdminSessionInfo::LOGGED_IN,
$adminSessionInfoId
)
->filterExpiredSessions(100)
->load();
return $collection;
}
/**
* Test for cleanExpiredSessions() method
*
* @magentoDataFixture Magento/Security/_files/adminsession.php
* @magentoAdminConfigFixture admin/security/session_lifetime 1
* @magentoDbIsolation enabled
*/
public function testCleanExpiredSessions()
{
/** @var \Magento\Security\Model\AdminSessionInfo $session */
$session = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
$collection = $this->getCollectionForCleanExpiredSessions($session);
$sizeBefore = $collection->getSize();
$this->adminSessionsManager->cleanExpiredSessions();
$collection = $this->getCollectionForCleanExpiredSessions($session);
$sizeAfter = $collection->getSize();
$this->assertGreaterThan($sizeAfter, $sizeBefore);
}
/**
* Collection getter with filters populated for testCleanExpiredSessions() method
*
* @param AdminSessionInfo $session
* @return ResourceModel\AdminSessionInfo\Collection
*/
protected function getCollectionForCleanExpiredSessions(\Magento\Security\Model\AdminSessionInfo $session)
{
/** @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection $collection */
$collection = $session->getResourceCollection()
->load();
return $collection;
}
}
@@ -0,0 +1,196 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Security\Model\Plugin;
use Laminas\Stdlib\Parameters;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\AccountManagement as CustomerAccountManagement;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\SecurityViolationException;
use Magento\Framework\Module\Manager;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Phrase;
use Magento\Security\Model\ConfigInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Interception\PluginList;
use PHPUnit\Framework\TestCase;
/**
* Tests for account manager plugin.
*
* @magentoAppArea frontend
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AccountManagementTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Manager */
private $moduleManager;
/** @var AccountManagementInterface */
private $accountManagement;
/** @var ConfigInterface */
private $securityConfig;
/** @var RequestInterface */
private $request;
/** @var Phrase */
private $errorMessage;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->moduleManager = $this->objectManager->get(Manager::class);
//This check is needed because Magento_Security independent of Magento_Customer
if (!$this->moduleManager->isEnabled('Magento_Customer')) {
$this->markTestSkipped('Magento_Customer module disabled.');
}
$this->accountManagement = $this->objectManager->get(AccountManagementInterface::class);
$this->request = $this->objectManager->get(RequestInterface::class);
$this->securityConfig = $this->objectManager->get(ConfigInterface::class);
$this->errorMessage = __(
'We received too many requests for password resets. Please wait and try again later or contact %1.',
$this->securityConfig->getCustomerServiceEmail()
);
}
/**
* @return void
*/
public function testPluginIsRegistered(): void
{
$pluginInfo = $this->objectManager->get(PluginList::class)->get(CustomerAccountManagement::class);
$this->assertSame(
AccountManagement::class,
$pluginInfo['security_check_customer_password_reset_attempt']['instance']
);
}
/**
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 1
* @magentoDataFixture Magento/Security/_files/customer_reset_password.php
*
* @return void
*/
public function testMaxNumberPasswordResetRequests(): void
{
$this->prepareServerParameters();
$this->expectExceptionObject(new SecurityViolationException($this->errorMessage));
$this->accountManagement->initiatePasswordReset(
'customer@example.com',
CustomerAccountManagement::EMAIL_REMINDER
);
}
/**
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 10
* @magentoDataFixture Magento/Security/_files/customer_reset_password.php
*
* @return void
*/
public function testTimeBetweenPasswordResetRequests(): void
{
$this->prepareServerParameters();
$this->expectExceptionObject(new SecurityViolationException($this->errorMessage));
$this->accountManagement->initiatePasswordReset(
'customer@example.com',
CustomerAccountManagement::EMAIL_REMINDER
);
}
/**
* @magentoConfigFixture current_store customer/password/password_reset_protection_type 0
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 1
* @magentoDataFixture Magento/Security/_files/customer_reset_password.php
*
* @return void
*/
public function testPasswordResetProtectionTypeDisabled(): void
{
$this->prepareServerParameters();
$result = $this->accountManagement->initiatePasswordReset(
'customer@example.com',
CustomerAccountManagement::EMAIL_REMINDER
);
$this->assertTrue($result);
}
/**
* @magentoConfigFixture current_store customer/password/password_reset_protection_type 1
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 1
* @magentoDataFixture Magento/Security/_files/customer_reset_password.php
*
* @return void
*/
public function testPasswordResetProtectionTypeByIpAndEmail(): void
{
$this->prepareServerParameters();
$this->expectExceptionObject(new SecurityViolationException($this->errorMessage));
$this->accountManagement->initiatePasswordReset(
'customer@example.com',
CustomerAccountManagement::EMAIL_REMINDER
);
}
/**
* @magentoConfigFixture current_store customer/password/password_reset_protection_type 2
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 1
* @magentoDataFixture Magento/Security/_files/customer_reset_password.php
*
* @return void
*/
public function testPasswordResetProtectionTypeByIp(): void
{
$this->markTestSkipped('Test blocked by issue MC-32988.');
$this->prepareServerParameters();
$this->expectExceptionObject(new SecurityViolationException($this->errorMessage));
$this->accountManagement->initiatePasswordReset(
'customer@example.com',
CustomerAccountManagement::EMAIL_REMINDER
);
}
/**
* @magentoConfigFixture current_store customer/password/password_reset_protection_type 3
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 1
* @magentoDataFixture Magento/Security/_files/customer_reset_password.php
*
* @return void
*/
public function testPasswordResetProtectionTypeByEmail(): void
{
$this->prepareServerParameters();
$this->expectExceptionObject(new SecurityViolationException($this->errorMessage));
$this->accountManagement->initiatePasswordReset(
'customer@example.com',
CustomerAccountManagement::EMAIL_REMINDER
);
}
/**
* Prepare server parameters.
*
* @return void
*/
private function prepareServerParameters(): void
{
$parameters = $this->objectManager->create(Parameters::class);
$parameters->set('REMOTE_ADDR', '127.0.0.1');
$this->request->setServer($parameters);
}
}
@@ -0,0 +1,187 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Security\Model\Plugin;
/**
* @magentoAppArea adminhtml
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AuthSessionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Backend\Model\Auth
*/
protected $auth;
/**
* @var \Magento\Backend\Model\Auth\Session
*/
protected $authSession;
/**
* @var \Magento\Security\Model\AdminSessionInfo
*/
protected $adminSessionInfo;
/**
* @var \Magento\Security\Model\AdminSessionsManager
*/
protected $adminSessionsManager;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* @var \Magento\Framework\Stdlib\DateTime
*/
protected $dateTime;
/**
* @var \Magento\Security\Model\ConfigInterface
*/
protected $securityConfig;
/**
* Set up
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->objectManager->get(\Magento\Framework\Config\ScopeInterface::class)
->setCurrentScope(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$this->auth = $this->objectManager->create(\Magento\Backend\Model\Auth::class);
$this->authSession = $this->objectManager->create(\Magento\Backend\Model\Auth\Session::class);
$this->adminSessionInfo = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
$this->auth->setAuthStorage($this->authSession);
$this->adminSessionsManager = $this->objectManager->get(\Magento\Security\Model\AdminSessionsManager::class);
$this->dateTime = $this->objectManager->create(\Magento\Framework\Stdlib\DateTime::class);
$this->securityConfig = $this->objectManager->create(\Magento\Security\Model\ConfigInterface::class);
}
/**
* Tear down
*/
protected function tearDown(): void
{
$this->auth = null;
$this->authSession = null;
$this->adminSessionInfo = null;
$this->adminSessionsManager = null;
$this->objectManager = null;
parent::tearDown();
}
/**
* Test of prolong user action
* session manager will not trigger new prolong if previous prolong was less than X sec ago
* X - is calculated based on current admin session lifetime
*
* @see \Magento\Security\Model\AdminSessionsManager::lastProlongIsOldEnough
* @magentoDbIsolation enabled
*/
public function testConsecutiveProcessProlong()
{
$this->auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$prolongsDiff = log($this->securityConfig->getAdminSessionLifetime()) - 2; // X from comment above
$dateInPast = $this->dateTime->formatDate((int) ($this->authSession->getUpdatedAt() - $prolongsDiff));
$this->adminSessionsManager->getCurrentSession()
->setData(
'updated_at',
$dateInPast
)
->save();
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$oldUpdatedAt = $this->adminSessionInfo->getUpdatedAt();
$this->authSession->prolong();
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$updatedAt = $this->adminSessionInfo->getUpdatedAt();
$this->assertSame(strtotime($oldUpdatedAt), strtotime($updatedAt));
}
/**
* Test of prolong user action
* session manager will trigger new prolong if previous prolong was more than X sec ago
* X - is calculated based on current admin session lifetime
*
* @see \Magento\Security\Model\AdminSessionsManager::lastProlongIsOldEnough
* @magentoDbIsolation enabled
*/
public function testProcessProlong()
{
$this->auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$prolongsDiff = 4 * log($this->securityConfig->getAdminSessionLifetime()) + 2; // X from comment above
$dateInPast = $this->dateTime->formatDate((int) ($this->authSession->getUpdatedAt() - $prolongsDiff));
$this->adminSessionsManager->getCurrentSession()
->setData(
'updated_at',
$dateInPast
)
->save();
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$oldUpdatedAt = $this->adminSessionInfo->getUpdatedAt();
$this->authSession->prolong();
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$updatedAt = $this->adminSessionInfo->getUpdatedAt();
$this->assertGreaterThan(strtotime($oldUpdatedAt), strtotime($updatedAt));
}
/**
* Test processing prolong with an expired user.
*
* @magentoDbIsolation enabled
*/
public function testProcessProlongWithExpiredUser()
{
$this->auth->login(
\Magento\TestFramework\Bootstrap::ADMIN_NAME,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$expireDate = new \DateTime();
$expireDate->modify('-10 days');
/** @var \Magento\User\Model\User $user */
$user = $this->objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername(\Magento\TestFramework\Bootstrap::ADMIN_NAME);
$userExpirationFactory =
$this->objectManager->create(\Magento\Security\Api\Data\UserExpirationInterfaceFactory::class);
/** @var \Magento\Security\Api\Data\UserExpirationInterface $userExpiration */
$userExpiration = $userExpirationFactory->create();
$userExpiration->setId($user->getId())
->setExpiresAt($expireDate->format('Y-m-d H:i:s'))
->save();
// need to trigger a prolong
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$prolongsDiff = 4 * log($this->securityConfig->getAdminSessionLifetime()) + 2;
$dateInPast = $this->dateTime->formatDate((int) ($this->authSession->getUpdatedAt() - $prolongsDiff));
$this->adminSessionsManager->getCurrentSession()
->setData(
'updated_at',
$dateInPast
)
->save();
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$this->authSession->prolong();
static::assertFalse($this->auth->isLoggedIn());
$user->reload();
static::assertFalse((bool)$user->getIsActive());
}
}
@@ -0,0 +1,94 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Security\Model\ResourceModel\AdminSessionInfo;
use Magento\Framework\Stdlib\DateTime\DateTime;
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection
*/
protected $collectionModel;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* Set up
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->collectionModel = $this->objectManager
->create(\Magento\Security\Model\ResourceModel\AdminSessionInfo\Collection::class);
}
/**
* updateActiveSessionsStatus() test
*
* @magentoDataFixture Magento/Security/_files/adminsession.php
*/
public function testUpdateActiveSessionsStatus()
{
$quantity = $this->collectionModel->updateActiveSessionsStatus(
\Magento\Security\Model\AdminSessionInfo::LOGGED_OUT_BY_LOGIN,
1,
'569e2277752e9'
);
$this->assertGreaterThanOrEqual(1, $quantity);
}
/**
* filterByUser() test
*
* @magentoDataFixture Magento/Security/_files/adminsession.php
*/
public function testFilterByUser()
{
$this->collectionModel->filterByUser(
1,
\Magento\Security\Model\AdminSessionInfo::LOGGED_IN,
'569e2e3d752e9'
);
$this->collectionModel->load();
$this->assertGreaterThanOrEqual(1, $this->collectionModel->getSize());
}
/**
* filterExpiredSessions() test
*
* @magentoDataFixture Magento/Security/_files/adminsession.php
*/
public function testFilterExpiredSessions()
{
$startTime = strtotime('2016-01-19 15:42:13') - 1;
$dateTime = $this->objectManager
->get(DateTime::class);
$currentTime = $dateTime->gmtTimestamp();
$sessionLifetime = $currentTime - $startTime;
$this->collectionModel->filterExpiredSessions($sessionLifetime);
$this->collectionModel->load();
$this->assertGreaterThanOrEqual(1, $this->collectionModel->getSize());
}
/**
* deleteSessionsOlderThen() test
*
* @magentoDataFixture Magento/Security/_files/adminsession.php
*/
public function testDeleteSessionsOlderThen()
{
$startTime = strtotime('2016-01-19 15:42:13');
$this->collectionModel->deleteSessionsOlderThen($startTime);
$this->collectionModel->load();
$this->assertGreaterThanOrEqual(1, $this->collectionModel->getSize());
}
}
@@ -0,0 +1,116 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Security\Model\ResourceModel;
class AdminSessionInfoTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Model\AbstractModel
*/
protected $model;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
protected function setUp(): void
{
parent::setUp();
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
}
protected function tearDown(): void
{
$this->objectManager = null;
parent::tearDown();
}
/**
* Test data for saving
* @return array
*/
public function getTestData()
{
return [
'user_id' => 1,
'status' => 1,
'created_at' => '2016-01-21 15:00:00',
'updated_at' => '2016-01-21 18:00:00'
];
}
/**
* @return mixed
*/
protected function saveTestData()
{
foreach ($this->getTestData() as $key => $value) {
$this->model->setData($key, $value);
}
$this->model->save();
return $this->model->getId();
}
/**
* Check that model is saving data to database
*
* @magentoDbIsolation enabled
*/
public function testIsModelSavingDataToDatabase()
{
$modelId = $this->saveTestData();
$newModel = $this->model->load($modelId);
$testData = $this->getTestData();
$newModelData = [];
foreach (array_keys($testData) as $key) {
$newModelData[$key] = $newModel->getData($key);
}
$this->assertEquals($testData, $newModelData);
}
/**
* Test for deleteSessionsOlderThen() method
*
* @magentoDataFixture Magento/Security/_files/adminsession.php
*/
public function testDeleteSessionsOlderThen()
{
$session = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
/** @var $session \Magento\Security\Model\AdminSessionInfo */
$session->getResource()->deleteSessionsOlderThen(strtotime('2016-01-20 12:00:00'));
$collection = $session->getResourceCollection()
->addFieldToFilter('main_table.updated_at', ['lt' => '2016-01-20 12:00:00'])
->load();
$count = $collection->count();
$this->assertEquals(0, $count);
}
/**
* Test for updateStatusByUserId() method
*
* @magentoDataFixture Magento/Security/_files/adminsession.php
*/
public function testUpdateStatusByUserId()
{
$session = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
/** @var $session \Magento\Security\Model\AdminSessionInfo */
$session->getResource()->updateStatusByUserId(
\Magento\Security\Model\AdminSessionInfo::LOGGED_OUT_BY_LOGIN,
1,
[1],
[1],
'2016-01-19 12:00:00'
);
$collection = $session->getResourceCollection()
->addFieldToFilter('main_table.user_id', 1)
->addFieldToFilter('main_table.status', \Magento\Security\Model\AdminSessionInfo::LOGGED_OUT_BY_LOGIN)
->load();
$count = $collection->count();
$this->assertGreaterThanOrEqual(1, $count);
}
}
@@ -0,0 +1,128 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Security\Model\ResourceModel\PasswordResetRequestEvent;
use Magento\Framework\Stdlib\DateTime\DateTime;
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection
*/
protected $collectionModel;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* Set up
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->collectionModel = $this->objectManager
->create(\Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection::class);
}
/**
* filterByAccountReference() test
*
* @magentoDataFixture Magento/Security/_files/password_reset_request_events.php
*/
public function testFilterByAccountReference()
{
$this->collectionModel->filterByAccountReference('test27.dev@gmail.com')
->load();
$this->assertEquals(1, $this->collectionModel->getSize());
}
/**
* filterByIp() test
*
* @magentoDataFixture Magento/Security/_files/password_reset_request_events.php
*/
public function testFilterByIp()
{
$this->collectionModel->filterByIp('3232249856')
->load();
$this->assertEquals(1, $this->collectionModel->getSize());
}
/**
* filterByRequestType() test
*
* @magentoDataFixture Magento/Security/_files/password_reset_request_events.php
*/
public function testFilterByRequestType()
{
$this->collectionModel
->filterByRequestType(\Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST)
->load();
$this->assertGreaterThanOrEqual(3, $this->collectionModel->getSize());
}
/**
* filterByLifetime() test
*
* @magentoDataFixture Magento/Security/_files/password_reset_request_events.php
*/
public function testFilterByLifetime()
{
$startTime = strtotime('2016-01-19 15:42:13') - 10;
$dateTime = $this->objectManager
->create(DateTime::class);
$currentTime = $dateTime->gmtTimestamp();
$sessionLifetime = $currentTime - $startTime;
$this->collectionModel->filterByLifetime($sessionLifetime)
->load();
$this->assertGreaterThanOrEqual(1, $this->collectionModel->getSize());
}
/**
* filterLastItem() test
*
* @magentoDataFixture Magento/Security/_files/password_reset_request_events.php
*/
public function testFilterLastItem()
{
$this->collectionModel->filterLastItem()
->load();
$this->assertEquals('2016-01-20 13:00:13', $this->collectionModel->getFirstItem()->getData('created_at'));
}
/**
* filterByIpOrAccountReference() test
*
* @magentoDataFixture Magento/Security/_files/password_reset_request_events.php
*/
public function testFilterByIpOrAccountReference()
{
$this->collectionModel->filterByIpOrAccountReference('3232249856', 'test273.dev@gmail.com')
->load();
$this->assertEquals(2, $this->collectionModel->getSize());
}
/**
* deleteRecordsOlderThen() test
*
* @magentoDataFixture Magento/Security/_files/password_reset_request_events.php
*/
public function testDeleteRecordsOlderThen()
{
$startTime = strtotime('2016-01-20 13:00:13');
$this->collectionModel->deleteRecordsOlderThen($startTime)
->load();
$this->assertGreaterThanOrEqual(1, $this->collectionModel->getSize());
}
}
@@ -0,0 +1,99 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Security\Model\ResourceModel;
/**
* Class PasswordResetRequestEventTest
* @package Magento\Security\Model
*/
class PasswordResetRequestEventTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\Model\AbstractModel
*/
protected $model;
/**
* @var \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent
*/
protected $resourceModel;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
protected function setUp(): void
{
parent::setUp();
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->model = $this->objectManager->create(\Magento\Security\Model\PasswordResetRequestEvent::class);
$this->resourceModel = $this->model->getResource();
}
protected function tearDown(): void
{
$this->objectManager = null;
$this->resourceModel = null;
parent::tearDown();
}
/**
* Test data
* @return array
*/
public function getTestData()
{
return [
'request_type' => \Magento\Security\Model\PasswordResetRequestEvent::ADMIN_PASSWORD_RESET_REQUEST,
'account_reference' => 'test27.dev@gmail.com',
'created_at' => '2016-01-20 13:00:13',
'ip' => '3232249856'
];
}
/**
* Saving test data to database
* @return mixed
*/
protected function saveTestData()
{
foreach ($this->getTestData() as $key => $value) {
$this->model->setData($key, $value);
}
$this->model->save();
return $this->model->getId();
}
/**
* Checking that test data is saving to database
*
* @magentoDbIsolation enabled
*/
public function testIsModelSavingDataToDatabase()
{
$modelId = $this->saveTestData();
$newModel = $this->model->load($modelId);
$testData = $this->getTestData();
$newModelData = [];
foreach (array_keys($testData) as $key) {
$newModelData[$key] = $newModel->getData($key);
}
$this->assertEquals($testData, $newModelData);
}
/**
* @magentoDataFixture Magento/Security/_files/password_reset_request_events.php
*/
public function testDeleteRecordsOlderThen()
{
/** @var \Magento\Security\Model\PasswordResetRequestEvent $passwordResetRequestEvent */
$countBefore = $this->model->getCollection()->count();
$this->resourceModel->deleteRecordsOlderThen(strtotime('2016-01-20 12:00:00'));
$countAfter = $this->model->getCollection()->count();
$this->assertLessThan($countBefore, $countAfter);
}
}
@@ -0,0 +1,74 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Security\Model\ResourceModel\UserExpiration;
/**
* Test UserExpiration collection filters.
*/
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Security\Model\ResourceModel\UserExpiration\CollectionFactory
*/
protected $collectionModelFactory;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* Set up
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->collectionModelFactory = $this->objectManager
->create(\Magento\Security\Model\ResourceModel\UserExpiration\CollectionFactory::class);
}
/**
* @magentoDataFixture Magento/Security/_files/expired_users.php
*/
public function testAddExpiredActiveUsersFilter()
{
/** @var \Magento\Security\Model\ResourceModel\UserExpiration\Collection $collectionModel */
$collectionModel = $this->collectionModelFactory->create();
$collectionModel->addActiveExpiredUsersFilter();
static::assertEquals(1, $collectionModel->getSize());
}
/**
* @magentoDataFixture Magento/Security/_files/expired_users.php
*/
public function testAddUserIdsFilter()
{
$adminUserNameFromFixture = 'adminUserExpired';
$user = $this->objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername($adminUserNameFromFixture);
/** @var \Magento\Security\Model\ResourceModel\UserExpiration\Collection $collectionModel */
$collectionModel = $this->collectionModelFactory->create()->addUserIdsFilter([$user->getId()]);
static::assertEquals(1, $collectionModel->getSize());
}
/**
* @magentoDataFixture Magento/Security/_files/expired_users.php
*/
public function testAddExpiredRecordsForUserFilter()
{
$adminUserNameFromFixture = 'adminUserExpired';
$user = $this->objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername($adminUserNameFromFixture);
/** @var \Magento\Security\Model\ResourceModel\UserExpiration\Collection $collectionModel */
$collectionModel = $this->collectionModelFactory->create()->addExpiredRecordsForUserFilter($user->getId());
static::assertEquals(1, $collectionModel->getSize());
}
}
@@ -0,0 +1,100 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Security\Model\ResourceModel;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Security\Model\UserExpirationFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\User\Model\ResourceModel\User as UserResource;
use PHPUnit\Framework\TestCase;
/**
* Verify user expiration resource model.
*/
class UserExpirationTest extends TestCase
{
/**
* @var UserExpiration
*/
private $userExpirationResource;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->userExpirationResource = Bootstrap::getObjectManager()->get(UserExpiration::class);
}
/**
* Verify user expiration saved with correct date.
*
* @magentoDataFixture Magento/User/_files/dummy_user.php
* @dataProvider userExpirationSaveDataProvider
* @magentoAppArea adminhtml
* @return void
*/
public function testUserExpirationSave(string $locale): void
{
$localeResolver = Bootstrap::getObjectManager()->get(ResolverInterface::class);
$timeZone = Bootstrap::getObjectManager()->get(TimezoneInterface::class);
$localeResolver->setLocale($locale);
$initialExpirationDate = $timeZone->date()->modify('+10 day');
$expireDate = $timeZone->formatDateTime(
$initialExpirationDate,
\IntlDateFormatter::MEDIUM,
\IntlDateFormatter::MEDIUM
);
if (version_compare(PHP_VERSION, '8.3', '>=') && $locale === 'uk_UA') {
$expireDate = str_replace(' р.', ' р.', $expireDate);
}
$userExpirationFactory = Bootstrap::getObjectManager()->get(UserExpirationFactory::class);
$userExpiration = $userExpirationFactory->create();
$userExpiration->setExpiresAt($expireDate);
$userExpiration->setUserId($this->getUserId());
$this->userExpirationResource->save($userExpiration);
$loadedUserExpiration = $userExpirationFactory->create();
$this->userExpirationResource->load($loadedUserExpiration, $userExpiration->getId());
self::assertEquals($initialExpirationDate->format('Y-m-d H:i:s'), $loadedUserExpiration->getExpiresAt());
}
/**
* Provides locale codes for validation test.
*
* @return array
*/
public function userExpirationSaveDataProvider(): array
{
return [
'default' => [
'locale_code' => 'en_US',
],
'non_default_english_textual' => [
'locale_code' => 'de_DE',
],
'non_default_non_english_textual' => [
'locale_code' => 'uk_UA',
],
];
}
/**
* Retrieve user id from db.
*
* @return int
*/
private function getUserId(): int
{
$userResource = Bootstrap::getObjectManager()->get(UserResource::class);
$data = $userResource->loadByUsername('dummy_username');
return (int)$data['user_id'];
}
}
@@ -0,0 +1,171 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Security\Model;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\TestFramework\Helper\Bootstrap;
class SecurityManagerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Security\Model\SecurityManager
*/
protected $securityManager;
/**
* @var AccountManagementInterface
*/
protected $accountManagement;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $objectManager;
/**
* @var \Magento\Security\Model\PasswordResetRequestEvent
*/
protected $passwordResetRequestEvent;
/**
* Set up
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->accountManagement = $this->objectManager->create(
\Magento\Customer\Api\AccountManagementInterface::class
);
$this->securityManager = $this->objectManager->create(\Magento\Security\Model\SecurityManager::class);
$this->passwordResetRequestEvent = $this->objectManager
->get(\Magento\Security\Model\PasswordResetRequestEvent::class);
}
/**
* Tear down
*/
protected function tearDown(): void
{
$this->objectManager = null;
$this->accountManagement = null;
$this->securityManager = null;
parent::tearDown();
}
/**
* Test for performSecurityCheck() method
*
* @magentoConfigFixture current_store customer/password/limit_password_reset_requests_method 0
* @magentoDbIsolation enabled
*/
public function testPerformSecurityCheck()
{
$collection = $this->getPasswordResetRequestEventCollection();
$sizeBefore = $collection->getSize();
$requestType = \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST;
$longIp = 127001;
$accountReference = 'customer@example.com';
$this->assertInstanceOf(
\Magento\Security\Model\SecurityManager::class,
$this->securityManager->performSecurityCheck(
$requestType,
$accountReference,
$longIp
)
);
$collection = $this->getPasswordResetRequestEventCollection();
$sizeAfter = $collection->getSize();
$this->assertEquals(1, $sizeAfter - $sizeBefore);
}
/**
* Get PasswordResetRequestEvent collection
*
* @return \Magento\Security\Model\ResourceModel\PasswordResetRequestEvent\Collection
*/
protected function getPasswordResetRequestEventCollection()
{
$collection = $this->passwordResetRequestEvent->getResourceCollection();
$collection->load();
return $collection;
}
/**
* Test for performSecurityCheck() method when number of password reset events is exceeded
*
* @magentoConfigFixture current_store customer/password/limit_password_reset_requests_method 1
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 1
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 0
* @magentoConfigFixture current_store contact/email/recipient_email hi@example.com
* @magentoDbIsolation enabled
*/
public function testPerformSecurityCheckLimitNumber()
{
$this->expectException(\Magento\Framework\Exception\SecurityViolationException::class);
$attempts = 2;
$requestType = \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST;
$longIp = 127001;
$accountReference = 'customer@example.com';
try {
for ($i = 0; $i < $attempts; $i++) {
$this->securityManager->performSecurityCheck($requestType, $accountReference, $longIp);
}
} catch (\Magento\Framework\Exception\SecurityViolationException $e) {
$this->assertEquals(1, $i);
throw new \Magento\Framework\Exception\SecurityViolationException(
__($e->getMessage())
);
}
$this->expectExceptionMessage(
'We received too many requests for password resets. '
. 'Please wait and try again later or contact hi@example.com.'
);
}
/**
* Test for performSecurityCheck() method when time between password reset events is exceeded
*
* @magentoConfigFixture current_store customer/password/limit_password_reset_requests_method 1
* @magentoConfigFixture current_store customer/password/max_number_password_reset_requests 0
* @magentoConfigFixture current_store customer/password/min_time_between_password_reset_requests 1
* @magentoConfigFixture current_store contact/email/recipient_email hi@example.com
* @magentoDbIsolation enabled
*/
public function testPerformSecurityCheckLimitTime()
{
$this->expectException(\Magento\Framework\Exception\SecurityViolationException::class);
$attempts = 2;
$requestType = \Magento\Security\Model\PasswordResetRequestEvent::CUSTOMER_PASSWORD_RESET_REQUEST;
$longIp = 127001;
$accountReference = 'customer@example.com';
try {
for ($i = 0; $i < $attempts; $i++) {
$this->securityManager->performSecurityCheck($requestType, $accountReference, $longIp);
}
} catch (\Magento\Framework\Exception\SecurityViolationException $e) {
$this->assertEquals(1, $i);
throw new \Magento\Framework\Exception\SecurityViolationException(
__($e->getMessage())
);
}
$this->fail('Something went wrong. Please check method execution logic.');
$this->expectExceptionMessage(
'We received too many requests for password resets. '
. 'Please wait and try again later or contact hi@example.com.'
);
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Security\Model\UserExpiration;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Verify user expiration validation model.
*/
class ValidatorTest extends TestCase
{
/**
* @var Validator
*/
private $validator;
/**
* @var ResolverInterface
*/
private $localeResolver;
/**
* @var TimezoneInterface
*/
private $timeZone;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->validator = Bootstrap::getObjectManager()->get(Validator::class);
$this->localeResolver = Bootstrap::getObjectManager()->get(ResolverInterface::class);
$this->timeZone = Bootstrap::getObjectManager()->get(TimezoneInterface::class);
}
/**
* Verify validation for date expiration with different locales.
*
* @magentoAppArea adminhtml
* @dataProvider validateUserExpiresAtDataProvider
* @return void
*/
public function testValidateUserExpiresAt(string $locale): void
{
$this->markTestSkipped('Test is blocked by issue AC-285');
$this->localeResolver->setLocale($locale);
$date = $this->timeZone->date()->modify('+10 day');
$expireDate = $this->timeZone->formatDateTime($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::MEDIUM);
self::assertTrue($this->validator->isValid($expireDate));
$date = $this->timeZone->date()->modify('-10 day');
$expireDate = $this->timeZone->formatDateTime($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::MEDIUM);
self::assertFalse($this->validator->isValid($expireDate));
self::assertEquals(
$this->validator->getMessages(),
['expires_at' => __('"%1" must be later than the current date.', 'Expiration date')]
);
}
/**
* Provides locale codes for validation test.
*
* @return array
*/
public function validateUserExpiresAtDataProvider(): array
{
return [
'default' => [
'locale_code' => 'en_US',
],
'non_default_english_textual' => [
'locale_code' => 'de_DE',
],
'non_default_non_english_textual' => [
'locale_code' => 'uk_UA',
],
];
}
}
@@ -0,0 +1,177 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Security\Model;
/**
* Tests for \Magento\Security\Model\UserExpirationManager
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class UserExpirationManagerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var \Magento\Backend\Model\Auth
*/
private $auth;
/**
* @var \Magento\Backend\Model\Auth\Session
*/
private $authSession;
/**
* @var \Magento\Security\Model\AdminSessionInfo
*/
private $adminSessionInfo;
/**
* @var \Magento\Security\Model\UserExpirationManager
*/
private $userExpirationManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->auth = $this->objectManager->create(\Magento\Backend\Model\Auth::class);
$this->authSession = $this->objectManager->create(\Magento\Backend\Model\Auth\Session::class);
$this->adminSessionInfo = $this->objectManager->create(\Magento\Security\Model\AdminSessionInfo::class);
$this->auth->setAuthStorage($this->authSession);
$this->userExpirationManager =
$this->objectManager->create(\Magento\Security\Model\UserExpirationManager::class);
}
/**
* @magentoDataFixture Magento/Security/_files/expired_users.php
*/
public function testUserIsExpired()
{
$adminUserNameFromFixture = 'adminUserExpired';
$user = $this->loadUserByUsername($adminUserNameFromFixture);
static::assertTrue($this->userExpirationManager->isUserExpired($user->getId()));
}
/**
* @magentoDataFixture Magento/Security/_files/expired_users.php
* @magentoAppIsolation enabled
*/
public function testDeactivateExpiredUsersWithExpiredUser()
{
$adminUsernameFromFixture = 'adminUserNotExpired';
$this->loginUser($adminUsernameFromFixture);
$user = $this->loadUserByUsername($adminUsernameFromFixture);
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$this->expireUser($user);
$this->userExpirationManager->deactivateExpiredUsersById([$user->getId()]);
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
$user->reload();
$userExpirationModel = $this->loadExpiredUserModelByUser($user);
static::assertEquals(0, $user->getIsActive());
static::assertNull($userExpirationModel->getId());
static::assertEquals(AdminSessionInfo::LOGGED_OUT, (int)$this->adminSessionInfo->getStatus());
}
/**
* @magentoDataFixture Magento/Security/_files/expired_users.php
* @magentoAppIsolation enabled
*/
public function testDeactivateExpiredUsersWithNonExpiredUser()
{
$adminUsernameFromFixture = 'adminUserNotExpired';
$this->loginUser($adminUsernameFromFixture);
$user = $this->loadUserByUsername($adminUsernameFromFixture);
$adminSessionInfoId = $this->authSession->getAdminSessionInfoId();
$this->userExpirationManager->deactivateExpiredUsersById([$user->getId()]);
$user->reload();
$userExpirationModel = $this->loadExpiredUserModelByUser($user);
$this->adminSessionInfo->load($adminSessionInfoId, 'id');
static::assertEquals(1, $user->getIsActive());
static::assertEquals($user->getId(), $userExpirationModel->getId());
static::assertEquals(AdminSessionInfo::LOGGED_IN, (int)$this->adminSessionInfo->getStatus());
}
/**
* Test deactivating without inputting a user.
*
* @magentoDataFixture Magento/Security/_files/expired_users.php
*/
public function testDeactivateExpiredUsers()
{
$notExpiredUser = $this->loadUserByUsername('adminUserNotExpired');
$expiredUser = $this->loadUserByUsername('adminUserExpired');
$this->userExpirationManager->deactivateExpiredUsers();
$notExpiredUserExpirationModel = $this->loadExpiredUserModelByUser($notExpiredUser);
$expiredUserExpirationModel = $this->loadExpiredUserModelByUser($expiredUser);
static::assertNotNull($notExpiredUserExpirationModel->getId());
static::assertNull($expiredUserExpirationModel->getId());
$notExpiredUser->reload();
$expiredUser->reload();
static::assertEquals($notExpiredUser->getIsActive(), 1);
static::assertEquals($expiredUser->getIsActive(), 0);
}
/**
* Login the given user and return a user model.
*
* @param string $username
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function loginUser(string $username)
{
$this->auth->login(
$username,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
}
/**
* @param $username
* @return \Magento\User\Model\User
*/
private function loadUserByUsername(string $username): \Magento\User\Model\User
{
/** @var \Magento\User\Model\User $user */
$user = $this->objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername($username);
return $user;
}
/**
* Expire the given user and return the UserExpiration model.
*
* @param \Magento\User\Model\User $user
* @throws \Exception
*/
private function expireUser(\Magento\User\Model\User $user)
{
$expireDate = new \DateTime();
$expireDate->modify('-10 days');
/** @var \Magento\Security\Api\Data\UserExpirationInterface $userExpiration */
$userExpiration = $this->objectManager->create(\Magento\Security\Api\Data\UserExpirationInterface::class);
$userExpiration->setId($user->getId())
->setExpiresAt($expireDate->format('Y-m-d H:i:s'))
->save();
}
/**
* @param \Magento\User\Model\User $user
* @return \Magento\Security\Model\UserExpiration
*/
private function loadExpiredUserModelByUser(\Magento\User\Model\User $user): \Magento\Security\Model\UserExpiration
{
/** @var \Magento\Security\Model\UserExpiration $expiredUserModel */
$expiredUserModel = $this->objectManager->create(\Magento\Security\Model\UserExpiration::class);
$expiredUserModel->load($user->getId());
return $expiredUserModel;
}
}