ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,34 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Block\Role\Grid;
/**
* @magentoAppArea adminhtml
*/
class UserTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\User\Block\Role\Grid\User
*/
protected $_block;
protected function setUp(): void
{
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
$this->_block = $layout->createBlock(\Magento\User\Block\Role\Grid\User::class);
}
public function testPreparedCollection()
{
$this->_block->toHtml();
$this->assertInstanceOf(
\Magento\User\Model\ResourceModel\Role\User\Collection::class,
$this->_block->getCollection()
);
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Block\Role\Tab;
/**
* @magentoAppArea adminhtml
*/
class EditTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\User\Block\Role\Tab\Edit
*/
protected $_block;
protected function setUp(): void
{
$roleAdmin = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Authorization\Model\Role::class);
$roleAdmin->load(\Magento\TestFramework\Bootstrap::ADMIN_ROLE_NAME, 'role_name');
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\RequestInterface::class
)->setParam(
'rid',
$roleAdmin->getId()
);
$this->_block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\User\Block\Role\Tab\Edit::class
);
}
public function testConstructor()
{
$this->assertNotEmpty($this->_block->getSelectedResources());
$this->assertContains('Magento_Backend::all', $this->_block->getSelectedResources());
}
public function testGetTree()
{
$encodedTree = $this->_block->getTree();
$this->assertNotEmpty($encodedTree);
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Block\User\Edit\Tab;
/**
* @magentoAppArea adminhtml
*/
class MainTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @var \Magento\User\Block\User\Edit\Tab\Main
*/
protected $_block;
/**
* @var \Magento\User\Model\User
*/
protected $_user;
protected function setUp(): void
{
parent::setUp();
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_block = $objectManager->create(\Magento\User\Block\User\Edit\Tab\Main::class);
$this->_block->setArea('adminhtml');
$this->_block->setNameInLayout('test');
$this->_user = $objectManager->create(\Magento\User\Model\User::class);
$objectManager->get(\Magento\Framework\Registry::class)->register('permissions_user', $this->_user);
}
protected function tearDown(): void
{
$this->_block = null;
$this->_user = null;
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\Registry::class)->unregister('permissions_user');
parent::tearDown();
}
public function testToHtmlPasswordFieldsExistingEntry()
{
$this->_user->loadByUsername(\Magento\TestFramework\Bootstrap::ADMIN_NAME);
$actualHtml = $this->_block->toHtml();
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//input[contains(@class,"required-entry") and @type="password"]',
$actualHtml
),
'There should be 1 required password entry: current user password.'
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//input[contains(@class,"validate-admin-password") and @type="password" and @name="password"]',
$actualHtml
)
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//input[contains(@class,"validate-cpassword") and @type="password" and ' .
'@name="password_confirmation"]',
$actualHtml
)
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//input[contains(@class,"validate-current-password") and @type="password" and @name="'
. Main::CURRENT_USER_PASSWORD_FIELD . '"]',
$actualHtml
)
);
}
public function testToHtmlPasswordFieldsNewEntry()
{
$actualHtml = $this->_block->toHtml();
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//input[contains(@class,"validate-admin-password") and contains(@class,"required-entry") and '
. '@type="password" and @name="password"]',
$actualHtml
)
);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//input[contains(@class,"validate-cpassword") and contains(@class,"required-entry") and '
. '@type="password" and @name="password_confirmation"]',
$actualHtml
)
);
}
}
@@ -0,0 +1,388 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml;
use Magento\Framework\Intl\DateTimeFactory;
use Magento\Framework\Stdlib\DateTime;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test class for \Magento\User\Controller\Adminhtml\Auth
*
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AuthTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Test form existence
* @covers \Magento\User\Controller\Adminhtml\Auth\Forgotpassword::execute
*/
public function testFormForgotpasswordAction()
{
$this->dispatch('backend/admin/auth/forgotpassword');
$expected = 'Password Help';
$this->assertStringContainsString($expected, $this->getResponse()->getBody());
}
/**
* Test redirection to startup page after success password recovering posting
*
* @covers \Magento\User\Controller\Adminhtml\Auth\Forgotpassword::execute
* @magentoDbIsolation enabled
*/
public function testForgotpasswordAction()
{
$this->getRequest()->setPostValue('email', 'test@test.com');
$this->dispatch('backend/admin/auth/forgotpassword');
$this->assertRedirect(
$this->equalTo(
Bootstrap::getObjectManager()->get(
\Magento\Backend\Helper\Data::class
)->getHomePageUrl()
)
);
}
/**
* Test email sending for forgotPassword action
*
* @magentoAdminConfigFixture admin/emails/forgot_email_template admin_emails_forgot_email_template
* @magentoAdminConfigFixture admin/emails/forgot_email_identity general
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testEmailSendForgotPasswordAction()
{
/** @var TransportBuilderMock $transportMock */
$transportMock = Bootstrap::getObjectManager()->get(
TransportBuilderMock::class
);
$this->getRequest()->setPostValue('email', 'adminUser@example.com');
$this->dispatch('backend/admin/auth/forgotpassword');
$this->assertRedirect(
$this->equalTo(
Bootstrap::getObjectManager()->get(
\Magento\Backend\Helper\Data::class
)->getHomePageUrl()
)
);
$message = $transportMock->getSentMessage();
$this->assertNotEmpty($message);
$this->assertEquals(
__('Password Reset Confirmation for %1', ['John Doe'])->render(),
$message->getSubject()
);
}
/**
* Test reset password action
*
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordAction()
{
/** @var $user \Magento\User\Model\User */
$user = Bootstrap::getObjectManager()->create(
\Magento\User\Model\User::class
)->loadByUsername(
'dummy_username'
);
$this->assertNotEmpty($user->getId(), 'Broken fixture');
$resetPasswordToken = Bootstrap::getObjectManager()->get(
\Magento\User\Helper\Data::class
)->generateResetPasswordLinkToken();
$user->changeResetPasswordLinkToken($resetPasswordToken);
$user->save();
$this->getRequest()->setQueryValue('token', $resetPasswordToken)->setQueryValue('id', $user->getId());
$this->dispatch('backend/admin/auth/resetpassword');
$this->assertEquals('adminhtml', $this->getRequest()->getRouteName());
$this->assertEquals('auth', $this->getRequest()->getControllerName());
$this->assertEquals('resetpassword', $this->getRequest()->getActionName());
$this->assertTrue((bool)strpos($this->getResponse()->getBody(), $resetPasswordToken));
}
/**
* Test reset password action extends expiry of token
*
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordActionWithTokenNearExpiry()
{
/** @var $user \Magento\User\Model\User */
$user = Bootstrap::getObjectManager()->create(
\Magento\User\Model\User::class
)->loadByUsername(
'dummy_username'
);
$this->assertNotEmpty($user->getId(), 'Broken fixture');
$resetPasswordToken = Bootstrap::getObjectManager()->get(
\Magento\User\Helper\Data::class
)->generateResetPasswordLinkToken();
$user->changeResetPasswordLinkToken($resetPasswordToken);
$anHourAgo = Bootstrap::getObjectManager()->create(DateTimeFactory::class)
->create()
->sub(\DateInterval::createFromDateString('1 hour'))
->format(DateTime::DATETIME_PHP_FORMAT);
$user->setRpTokenCreatedAt($anHourAgo);
$user->save();
$this->getRequest()->setQueryValue('token', $resetPasswordToken)->setQueryValue('id', $user->getId());
$this->dispatch('backend/admin/auth/resetpassword');
$this->assertEquals('adminhtml', $this->getRequest()->getRouteName());
$this->assertEquals('auth', $this->getRequest()->getControllerName());
$this->assertEquals('resetpassword', $this->getRequest()->getActionName());
$this->assertTrue((bool)strpos($this->getResponse()->getBody(), $resetPasswordToken));
$this->assertNotEquals($anHourAgo, $user->reload()->getRpTokenCreatedAt());
}
/**
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPassword::_validateResetPasswordLinkToken
*/
public function testResetPasswordActionWithDummyToken()
{
$this->getRequest()->setQueryValue('token', 'dummy')->setQueryValue('id', 1);
$this->dispatch('backend/admin/auth/resetpassword');
$this->assertSessionMessages(
$this->equalTo(['Your password reset link has expired.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$this->assertRedirect();
}
/**
* @dataProvider resetPasswordDataProvider
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordPostAction($password, $passwordConfirmation, $isPasswordChanged)
{
$objectManager = Bootstrap::getObjectManager();
/** @var $user \Magento\User\Model\User */
$user = $objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername('dummy_username');
$this->assertNotEmpty($user->getId(), 'Broken fixture');
/** @var \Magento\User\Helper\Data $helper */
$helper = $objectManager->get(\Magento\User\Helper\Data::class);
$resetPasswordToken = $helper->generateResetPasswordLinkToken();
$user->changeResetPasswordLinkToken($resetPasswordToken);
$user->save();
$oldPassword = $user->getPassword();
$this->getRequest()->setQueryValue(
'token',
$resetPasswordToken
)->setQueryValue(
'id',
$user->getId()
)->setPostValue(
'password',
$password
)->setPostValue(
'confirmation',
$passwordConfirmation
);
$this->dispatch('backend/admin/auth/resetpasswordpost');
/** @var \Magento\Backend\Helper\Data $backendHelper */
$backendHelper = $objectManager->get(\Magento\Backend\Helper\Data::class);
if ($isPasswordChanged) {
$this->assertRedirect($this->equalTo($backendHelper->getHomePageUrl()));
} else {
$this->assertRedirect(
$this->stringContains('backend/admin/auth/resetpassword')
);
}
/** @var $user \Magento\User\Model\User */
$user = $objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername('dummy_username');
if ($isPasswordChanged) {
/** @var \Magento\Framework\Encryption\EncryptorInterface $encryptor */
$encryptor = $objectManager->get(\Magento\Framework\Encryption\EncryptorInterface::class);
$this->assertTrue($encryptor->validateHash($password, $user->getPassword()));
} else {
$this->assertEquals($oldPassword, $user->getPassword());
}
}
public function resetPasswordDataProvider()
{
$password = uniqid('123q');
return [
[$password, $password, true],
[$password, '', false],
[$password, $password . '123', false],
['', '', false],
['', $password, false]
];
}
/**
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordPostActionWithDummyToken()
{
$this->getRequest()->setQueryValue('token', 'dummy')->setQueryValue('id', 1);
$this->dispatch('backend/admin/auth/resetpasswordpost');
$this->assertSessionMessages(
$this->equalTo(['Your password reset link has expired.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$objectManager = Bootstrap::getObjectManager();
/** @var \Magento\Backend\Helper\Data $backendHelper */
$backendHelper = $objectManager->get(\Magento\Backend\Helper\Data::class);
$this->assertRedirect($this->equalTo($backendHelper->getHomePageUrl()));
}
/**
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::execute
* @covers \Magento\User\Controller\Adminhtml\Auth\ResetPasswordPost::_validateResetPasswordLinkToken
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testResetPasswordPostActionWithInvalidPassword()
{
$objectManager = Bootstrap::getObjectManager();
$user = $objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername('dummy_username');
$resetPasswordToken = null;
if ($user->getId()) {
/** @var \Magento\User\Helper\Data $userHelper */
$userHelper = $objectManager->get(\Magento\User\Helper\Data::class);
$resetPasswordToken = $userHelper->generateResetPasswordLinkToken();
$user->changeResetPasswordLinkToken($resetPasswordToken);
$user->save();
}
$newDummyPassword = 'new_dummy_password2';
$this->getRequest()->setQueryValue(
'token',
$resetPasswordToken
)->setQueryValue(
'id',
$user->getId()
)->setPostValue(
'password',
$newDummyPassword
)->setPostValue(
'confirmation',
'invalid'
);
$this->dispatch('backend/admin/auth/resetpasswordpost');
$this->assertSessionMessages(
$this->equalTo(['Your password confirmation must match your password.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$this->assertRedirect();
}
/**
* Prepare email mock to test emails
*
* @param int $occurrenceNumber
* @param string $templateId
* @param string $sender
* @return \PHPUnit\Framework\MockObject\MockObject
*/
protected function prepareEmailMock($occurrenceNumber, $templateId, $sender)
{
$transportMock = $this->getMockBuilder(\Magento\Framework\Mail\TransportInterface::class)
->setMethods(['sendMessage'])
->getMockForAbstractClass();
$transportMock->expects($this->exactly($occurrenceNumber))
->method('sendMessage');
$transportBuilderMock = $this->getMockBuilder(\Magento\Framework\Mail\Template\TransportBuilder::class)
->disableOriginalConstructor()
->setMethods(
[
'setTemplateModel',
'addTo',
'setFrom',
'setTemplateIdentifier',
'setTemplateVars',
'setTemplateOptions',
'getTransport'
]
)
->getMock();
$transportBuilderMock->method('setTemplateIdentifier')
->with($templateId)
->willReturnSelf();
$transportBuilderMock->method('setTemplateModel')
->with(\Magento\Email\Model\BackendTemplate::class)
->willReturnSelf();
$transportBuilderMock->method('setTemplateOptions')
->willReturnSelf();
$transportBuilderMock->method('setTemplateVars')
->willReturnSelf();
$transportBuilderMock->method('setFrom')
->with($sender)
->willReturnSelf();
$transportBuilderMock->method('addTo')
->willReturnSelf();
$transportBuilderMock->expects($this->exactly($occurrenceNumber))
->method('getTransport')
->willReturn($transportMock);
return $transportBuilderMock;
}
/**
* Add mocked object to environment
*
* @param \PHPUnit\Framework\MockObject\MockObject $transportBuilderMock
* @param string $originalClassName
*/
protected function addMockToClass(
\PHPUnit\Framework\MockObject\MockObject $transportBuilderMock,
$originalClassName
) {
$userMock = $this->_objectManager->create(
$originalClassName,
['transportBuilder' => $transportBuilderMock]
);
$factoryMock = $this->getMockBuilder(\Magento\User\Model\UserFactory::class)
->disableOriginalConstructor()
->setMethods(
[
'create'
]
)
->getMock();
$factoryMock->method('create')
->willReturn($userMock);
$this->_objectManager->addSharedInstance(
$factoryMock,
\Magento\User\Model\UserFactory::class
);
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\Locks;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Testing the list of locked users.
*
* @magentoAppArea adminhtml
*/
class GridTest extends AbstractBackendController
{
/**
* Test index action
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/User/_files/locked_users.php
*/
public function testGridAction()
{
$this->dispatch('backend/admin/locks/grid');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('data-column="username"', $body);
$this->assertStringContainsString('data-column="last_login"', $body);
$this->assertStringContainsString('data-column="last_login"', $body);
$this->assertStringContainsString('data-column="failures_num"', $body);
$this->assertStringContainsString('data-column="lock_expires"', $body);
$this->assertMatchesRegularExpression(
'/<td data-column\="username"\s*class\="[^"]*col-name[^"]*col-username[^"]*"\s*>\s*adminUser1\s*<\/td>/',
$body
);
$this->assertMatchesRegularExpression(
'/<td data-column\="username"\s*class\="[^"]*col-name[^"]*col-username[^"]*"\s*>\s*adminUser2\s*<\/td>/',
$body
);
}
}
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\Locks;
/**
* Locked users page test.
*
* @magentoAppArea adminhtml
*/
class IndexTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Test index action
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/User/_files/locked_users.php
*/
public function testIndexAction()
{
$this->dispatch('backend/admin/locks/index');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('<h1 class="page-title">Locked Users</h1>', $body);
$this->assertMatchesRegularExpression(
'/<td data-column\="username"\s*class\="[^"]*col-name[^"]*col-username[^"]*"\s*>\s*adminUser1\s*<\/td>/',
$body
);
$this->assertMatchesRegularExpression(
'/<td data-column\="username"\s*class\="[^"]*col-name[^"]*col-username\s*"[^"]*>\s*adminUser2\s*<\/td>/',
$body
);
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\Locks;
/**
* Testing unlock controller.
*
* @magentoAppArea adminhtml
*/
class MassUnlockTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Test index action
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/User/_files/locked_users.php
*/
public function testMassUnlockAction()
{
$userIds = [];
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $model \Magento\User\Model\User */
$model = $objectManager->create(\Magento\User\Model\User::class);
$userIds[] = $model->loadByUsername('adminUser1')->getId();
$userIds[] = $model->loadByUsername('adminUser2')->getId();
$request = $this->getRequest();
$request->setPostValue(
'unlock',
$userIds
);
$this->dispatch('backend/admin/locks/massunlock');
$this->assertSessionMessages(
$this->containsEqual((string)__('Unlocked %1 user(s).', count($userIds))),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect();
}
}
@@ -0,0 +1,31 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\User;
/**
* Test class for \Magento\User\Controller\Adminhtml\User\Delete
* @magentoAppArea adminhtml
*/
class DeleteTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @covers \Magento\User\Controller\Adminhtml\User\Delete::execute
*/
public function testDeleteActionWithError()
{
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\User\Model\User::class);
/** @var \Magento\Framework\Message\ManagerInterface $messageManager */
$messageManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Message\ManagerInterface::class);
$user->load(1);
$this->getRequest()->setPostValue('user_id', $user->getId() . '_suffix_ignored_in_mysql_casting_to_int');
$this->dispatch('backend/admin/user/delete');
$message = $messageManager->getMessages()->getLastAddedMessage()->getText();
$this->assertEquals('You cannot delete your own account.', $message);
}
}
@@ -0,0 +1,112 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\User;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test class for Magento\User\Controller\Adminhtml\User\InvalidateToken.
*
* @magentoAppArea adminhtml
*/
class InvalidateTokenTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testInvalidateSingleToken()
{
/** @var \Magento\Integration\Api\AdminTokenServiceInterface $tokenService */
$tokenService = Bootstrap::getObjectManager()->get(\Magento\Integration\Api\AdminTokenServiceInterface::class);
/** @var \Magento\Integration\Model\Oauth\Token $tokenModel */
$tokenModel = Bootstrap::getObjectManager()->get(\Magento\Integration\Model\Oauth\Token::class);
/** @var \Magento\User\Model\User $userModel */
$userModel = Bootstrap::getObjectManager()->get(\Magento\User\Model\User::class);
$adminUserNameFromFixture = 'adminUser';
$tokenService->createAdminAccessToken(
$adminUserNameFromFixture,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminUserId = $userModel->loadByUsername($adminUserNameFromFixture)->getId();
// invalidate token
$this->getRequest()->setParam('user_id', $adminUserId);
$this->dispatch('backend/admin/user/invalidateToken');
$token = $tokenModel->loadByAdminId($adminUserId);
$this->assertNull($token->getId());
}
/**
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testInvalidateMultipleTokens()
{
/** @var \Magento\Integration\Api\AdminTokenServiceInterface $tokenService */
$tokenService = Bootstrap::getObjectManager()->get(\Magento\Integration\Api\AdminTokenServiceInterface::class);
/** @var \Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory $tokenModelCollectionFactory */
$tokenModelCollectionFactory = Bootstrap::getObjectManager()->get(
\Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory::class
);
/** @var \Magento\User\Model\User $userModel */
$userModel = Bootstrap::getObjectManager()->get(\Magento\User\Model\User::class);
$adminUserNameFromFixture = 'adminUser';
$tokenService->createAdminAccessToken(
$adminUserNameFromFixture,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$tokenService->createAdminAccessToken(
$adminUserNameFromFixture,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$adminUserId = $userModel->loadByUsername($adminUserNameFromFixture)->getId();
// invalidate tokens
$this->getRequest()->setParam('user_id', $adminUserId);
$this->dispatch('backend/admin/user/invalidateToken');
foreach ($tokenModelCollectionFactory->create()->addFilterByAdminId($adminUserId) as $token) {
$this->assertEquals(1, $token->getRevoked());
}
}
/**
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testInvalidateTokenNoTokens()
{
/** @var \Magento\User\Model\User $userModel */
$userModel = Bootstrap::getObjectManager()->get(\Magento\User\Model\User::class);
$adminUserNameFromFixture = 'adminUser';
$adminUserId = $userModel->loadByUsername($adminUserNameFromFixture)->getId();
// invalidate token
$this->getRequest()->setParam('user_id', $adminUserId);
$this->dispatch('backend/admin/user/invalidateToken');
}
public function testInvalidateTokenNoUser()
{
$this->dispatch('backend/admin/user/invalidateToken');
$this->assertSessionMessages(
$this->equalTo(['We can\'t find a user to revoke.']),
MessageInterface::TYPE_ERROR
);
}
public function testInvalidateTokenInvalidUser()
{
$adminUserId = 999;
// invalidate token
$this->getRequest()->setParam('user_id', $adminUserId);
$this->dispatch('backend/admin/user/invalidateToken');
}
}
@@ -0,0 +1,50 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml\User;
/**
* Test class for \Magento\User\Controller\Adminhtml\User\Role.
*
* @magentoAppArea adminhtml
*/
class RoleTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
public function testEditRoleAction()
{
$roleAdmin = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Authorization\Model\Role::class);
$roleAdmin->load(\Magento\TestFramework\Bootstrap::ADMIN_ROLE_NAME, 'role_name');
$this->getRequest()->setParam('rid', $roleAdmin->getId());
$this->dispatch('backend/admin/user_role/editrole');
$this->assertStringContainsString('Role Information', $this->getResponse()->getBody());
$this->assertStringContainsString($roleAdmin->getRoleName(), $this->getResponse()->getBody());
}
/**
* @covers \Magento\User\Controller\Adminhtml\User\Role\Editrolegrid::execute
*/
public function testEditrolegridAction()
{
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true);
$this->dispatch('backend/admin/user_role/editrolegrid');
$expected = '%a<table %a id="roleUserGrid_table">%a';
$this->assertStringMatchesFormat($expected, $this->getResponse()->getBody());
}
/**
* @covers \Magento\User\Controller\Adminhtml\User\Role\RoleGrid::execute
*/
public function testRoleGridAction()
{
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true)->setParam('user_id', 1);
$this->dispatch('backend/admin/user_role/roleGrid');
$expected = '%a<table %a id="roleGrid_table">%a';
$this->assertStringMatchesFormat($expected, $this->getResponse()->getBody());
}
}
@@ -0,0 +1,336 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Controller\Adminhtml;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\TestFramework\Bootstrap;
/**
* @magentoAppArea adminhtml
*/
class UserTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Verify that the main user page contains the user grid
*/
public function testIndexAction()
{
$this->dispatch('backend/admin/user/index');
$response = $this->getResponse()->getBody();
$this->assertStringContainsString('Users', $response);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="permissionsUserGrid_table"]',
$response
)
);
}
/**
* Verify that attempting to save a user when no data is present redirects back to the main user page
*/
public function testSaveActionNoData()
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->dispatch('backend/admin/user/save');
$this->assertRedirect($this->stringContains('backend/admin/user/index/'));
}
/**
* Verify that a user cannot be saved if it no longer exists
*
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testSaveActionWrongId()
{
/** @var $user \Magento\User\Model\User */
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\User\Model\User::class
)->loadByUsername(
'dummy_username'
);
$userId = $user->getId();
$this->assertNotEmpty($userId, 'Broken fixture');
$user->delete();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue('user_id', $userId);
$this->dispatch('backend/admin/user/save');
$this->assertSessionMessages(
$this->equalTo(['This user no longer exists.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains('backend/admin/user/index/'));
}
/**
* Verify that users cannot be saved if the admin password is not correct
*
* @magentoDbIsolation enabled
*/
public function testSaveActionMissingCurrentAdminPassword()
{
$fixture = uniqid();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'username' => $fixture,
'email' => "{$fixture}@example.com",
'firstname' => 'First',
'lastname' => 'Last',
'password' => 'password_with_1_number',
'password_confirmation' => 'password_with_1_number',
]
);
$this->dispatch('backend/admin/user/save');
$this->assertSessionMessages(
$this->equalTo(
['The password entered for the current user is invalid. Verify the password and try again.']
)
);
$this->assertRedirect($this->stringContains('backend/admin/user/edit'));
}
/**
* Verify that users can be successfully saved when data is correct
*
* @magentoDbIsolation enabled
*/
public function testSaveAction()
{
$fixture = uniqid();
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'username' => $fixture,
'email' => "{$fixture}@example.com",
'firstname' => 'First',
'lastname' => 'Last',
'password' => 'password_with_1_number',
'password_confirmation' => 'password_with_1_number',
\Magento\User\Block\User\Edit\Tab\Main::CURRENT_USER_PASSWORD_FIELD => Bootstrap::ADMIN_PASSWORD,
]
);
$this->dispatch('backend/admin/user/save');
$this->assertSessionMessages(
$this->equalTo(['You saved the user.']),
\Magento\Framework\Message\MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('backend/admin/user/index/'));
}
/**
* Verify that users with the same username or email as an existing user cannot be created
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testSaveActionDuplicateUser()
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue(
[
'username' => 'adminUser',
'email' => 'adminUser@example.com',
'firstname' => 'John',
'lastname' => 'Doe',
'password' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD,
'password_confirmation' => \Magento\TestFramework\Bootstrap::ADMIN_PASSWORD,
\Magento\User\Block\User\Edit\Tab\Main::CURRENT_USER_PASSWORD_FIELD => Bootstrap::ADMIN_PASSWORD,
]
);
$this->dispatch('backend/admin/user/save/active_tab/main_section');
$this->assertSessionMessages(
$this->equalTo(['A user with the same user name or email already exists.']),
\Magento\Framework\Message\MessageInterface::TYPE_ERROR
);
$this->assertRedirect($this->stringContains('backend/admin/user/edit/'));
$this->assertRedirect($this->matchesRegularExpression('/^((?!active_tab).)*$/'));
}
/**
* Verify password change properly updates fields when the request is valid.
*
* @param array $postData
* @param bool $isPasswordCorrect
*
* @magentoDbIsolation enabled
* @dataProvider saveActionPasswordChangeDataProvider
*/
public function testSaveActionPasswordChange($postData, $isPasswordCorrect)
{
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($postData);
$this->dispatch('backend/admin/user/save');
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $user \Magento\User\Model\User */
$user = $objectManager->create(\Magento\User\Model\User::class);
$user->loadByUsername($postData['username']);
if ($isPasswordCorrect) {
$this->assertRedirect($this->stringContains('backend/admin/user/index'));
$this->assertEquals($postData['username'], $user->getUsername());
$this->assertEquals($postData['email'], $user->getEmail());
$this->assertEquals($postData['firstname'], $user->getFirstname());
$this->assertEquals($postData['lastname'], $user->getLastname());
$encryptor = $objectManager->get(\Magento\Framework\Encryption\EncryptorInterface::class);
$this->assertTrue($encryptor->validateHash($postData['password'], $user->getPassword()));
} else {
$this->assertRedirect($this->stringContains('backend/admin/user/edit'));
$this->assertEmpty($user->getData());
}
}
/**
* Dataprovider for testSaveActionPasswordChange
*
* @return array
*/
public function saveActionPasswordChangeDataProvider()
{
$password = uniqid('123q');
$passwordPairs = [
['password' => $password, 'password_confirmation' => $password, 'is_correct' => true],
['password' => $password, 'password_confirmation' => '', 'is_correct' => false],
['password' => $password, 'password_confirmation' => $password . '123', 'is_correct' => false],
['password' => '', 'password_confirmation' => '', 'is_correct' => false],
['password' => '', 'password_confirmation' => $password, 'is_correct' => false],
];
$data = [];
foreach ($passwordPairs as $passwordPair) {
$fixture = uniqid();
$postData = [
'username' => $fixture,
'email' => "{$fixture}@example.com",
'firstname' => 'First',
'lastname' => 'Last',
'password' => $passwordPair['password'],
'password_confirmation' => $passwordPair['password_confirmation'],
\Magento\User\Block\User\Edit\Tab\Main::CURRENT_USER_PASSWORD_FIELD => Bootstrap::ADMIN_PASSWORD,
];
$data[] = [$postData, $passwordPair['is_correct']];
}
return $data;
}
/**
* Verify that the role grid is present when requested
*/
public function testRoleGridAction()
{
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true);
$this->dispatch('backend/admin/user/roleGrid');
$expected = '%a<table %a id="permissionsUserGrid_table">%a';
$this->assertStringMatchesFormat($expected, $this->getResponse()->getBody());
}
/**
* Verify that the roles grid is present when requested
*
* @depends testSaveAction
*/
public function testRolesGridAction()
{
$this->getRequest()->setParam('ajax', true)->setParam('isAjax', true)->setParam('user_id', 1);
$this->dispatch('backend/admin/user/rolesGrid');
$expected = '%a<table %a id="permissionsUserRolesGrid_table">%a';
$this->assertStringMatchesFormat($expected, $this->getResponse()->getBody());
}
/**
* Verify that expected header and fieldsets are present for edit
*
* @depends testSaveAction
*/
public function testEditAction()
{
$this->getRequest()->setParam('user_id', 1);
$this->dispatch('backend/admin/user/edit');
$response = $this->getResponse()->getBody();
//check "User Information" header and fieldset
$this->assertStringContainsString('data-ui-id="adminhtml-user-edit-tabs-title"', $response);
$this->assertStringContainsString('User Information', $response);
$this->assertEquals(
1,
\Magento\TestFramework\Helper\Xpath::getElementsCountForXpath(
'//*[@id="user_base_fieldset"]',
$response
)
);
}
/**
* Verify that validation passes on correct data
*/
public function testValidateActionSuccess()
{
$data = [
'username' => 'admin2',
'firstname' => 'new firstname',
'lastname' => 'new lastname',
'email' => 'example@domain.com',
'password' => 'password123',
'password_confirmation' => 'password123',
];
$this->getRequest()->setPostValue($data);
$this->dispatch('backend/admin/user/validate');
$body = $this->getResponse()->getBody();
$this->assertEquals('{"error":0}', $body);
}
/**
* Verify that an unknown top level domain on an email address does not fail validation
*/
public function testValidateActionUnknownTldSuccess()
{
$data = [
'username' => 'admin2',
'firstname' => 'new firstname',
'lastname' => 'new lastname',
'email' => 'example@domain.unknown',
'password' => 'password123',
'password_confirmation' => 'password123',
];
$this->getRequest()->setPostValue($data);
$this->dispatch('backend/admin/user/validate');
$body = $this->getResponse()->getBody();
$this->assertEquals('{"error":0}', $body);
}
/**
* Verify that an invalid email address format fails the validation
*/
public function testValidateActionError()
{
$data = [
'username' => 'admin2',
'firstname' => 'new firstname',
'lastname' => 'new lastname',
'email' => 'example@-domain.cim',
'password' => 'password123',
'password_confirmation' => 'password123',
];
/**
* set customer data
*/
$this->getRequest()->setPostValue($data);
$this->dispatch('backend/admin/user/validate');
$body = $this->getResponse()->getBody();
$this->assertStringContainsString('{"error":1,"html_message":', $body);
$this->assertStringContainsString(
"'-domain.cim' is not a valid hostname for email address 'example@-domain.cim",
$body
);
}
}
@@ -0,0 +1,54 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Helper;
/**
* @magentoAppArea adminhtml
*/
class DataTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Backend\Helper\Data
*/
protected $_helper;
protected function setUp(): void
{
parent::setUp();
$this->_helper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\User\Helper\Data::class
);
}
/**
* Test generate unique token for reset password confirmation link
*
* @covers \Magento\User\Helper\Data::generateResetPasswordLinkToken
*/
public function testGenerateResetPasswordLinkToken()
{
$actual = $this->_helper->generateResetPasswordLinkToken();
$this->assertGreaterThan(15, strlen($actual));
}
/**
* Test retrieve customer reset password link expiration period in days
*
*/
public function testGetResetPasswordLinkExpirationPeriod()
{
/** @var $configModel \Magento\Backend\App\ConfigInterface */
$configModel = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\Config\MutableScopeConfigInterface::class
);
$this->assertEquals(
2,
(int)$configModel->getValue(
\Magento\User\Helper\Data::XML_PATH_ADMIN_RESET_PASSWORD_LINK_EXPIRATION_PERIOD
)
);
}
}
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Model\ResourceModel\Role\User;
/**
* Role user collection test
* @magentoAppArea adminhtml
*/
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\User\Model\ResourceModel\Role\User\Collection
*/
protected $_collection;
protected function setUp(): void
{
$this->_collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\User\Model\ResourceModel\Role\User\Collection::class
);
}
public function testSelectQueryInitialized()
{
$this->assertStringContainsString('user_id > 0', $this->_collection->getSelect()->__toString());
}
}
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Model\ResourceModel\User;
/**
* User collection test
* @magentoAppArea adminhtml
*/
class CollectionTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\User\Model\ResourceModel\User\Collection
*/
protected $_collection;
protected function setUp(): void
{
$this->_collection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\User\Model\ResourceModel\User\Collection::class
);
}
public function testFilteringCollectionByUserId()
{
$this->assertEquals(1, $this->_collection->addFieldToFilter('user_id', 1)->count());
}
}
@@ -0,0 +1,157 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\User\Model\ResourceModel;
use Laminas\Validator\ValidatorInterface;
use Magento\Authorization\Model\ResourceModel\Role\Collection as UserRoleCollection;
use Magento\Authorization\Model\ResourceModel\Role\CollectionFactory as UserRoleCollectionFactory;
use Magento\Authorization\Model\UserContextInterface;
use Magento\Framework\Math\Random;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\User\Model\ResourceModel\User as UserResourceModel;
use Magento\User\Model\User;
use Magento\User\Model\UserFactory;
/**
* @magentoAppArea adminhtml
*/
class UserTest extends \PHPUnit\Framework\TestCase
{
/**
* @var UserResourceModel
*/
private $model;
/**
* @var UserRoleCollectionFactory
*/
private $userRoleCollectionFactory;
/**
* @var UserFactory
*/
private $userFactory;
/**
* @var Random
*/
private $random;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->model = Bootstrap::getObjectManager()->get(UserResourceModel::class);
$this->userRoleCollectionFactory = Bootstrap::getObjectManager()->get(UserRoleCollectionFactory::class);
$this->userFactory = Bootstrap::getObjectManager()->get(UserFactory::class);
$this->random = Bootstrap::getObjectManager()->get(Random::class);
}
/**
* Tests if latest password is stored after user creating
* when password lifetime config value is zero (disabled as fact)
*
* @return void
* @magentoConfigFixture current_store admin/security/password_lifetime 0
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testGetLatestPasswordWhenZeroPasswordLifetime(): void
{
/** @var User $user */
$user = $this->userFactory->create();
$user->loadByUsername('dummy_username');
$latestPassword = $this->model->getLatestPassword($user->getId());
$this->assertNotEmpty(
$latestPassword,
'Latest password should be stored even if password lifetime config value is 0'
);
}
/**
* Test that user role is not deleted after deleting empty user.
*
* @return void
*/
public function testDelete(): void
{
$this->checkRoleCollectionSize();
/** @var User $user */
$user = $this->userFactory->create();
$this->model->delete($user);
$this->checkRoleCollectionSize();
}
/**
* Ensure that role collection size is correct.
*
* @return void
*/
private function checkRoleCollectionSize(): void
{
/** @var UserRoleCollection $roleCollection */
$roleCollection = $this->userRoleCollectionFactory->create();
$roleCollection->setUserFilter(0, UserContextInterface::USER_TYPE_ADMIN);
$this->assertEquals(1, $roleCollection->getSize());
}
/**
* Check total user count.
*
* @return void
*/
public function testCountAll(): void
{
$this->assertSame(1, $this->model->countAll());
}
/**
* Check validation rules has correct type.
*
* @return void
*/
public function testGetValidationRulesBeforeSave(): void
{
$rules = $this->model->getValidationRulesBeforeSave();
$this->assertInstanceOf(ValidatorInterface::class, $rules);
}
/**
* Test save rp token
*
* @throws \Exception
*/
public function testSave(): void
{
$token = 'randomstring';
$username = $this->random->getRandomString(6);
$email = $username . "@example.com";
$password = uniqid() . $this->random->getRandomString(10);
$userModel = Bootstrap::getObjectManager()->get(User::class);
$userModel->setData(
[
'email' => $email,
'rp_token' => $token,
'firstname' => 'John',
'lastname' => 'Doe',
'password' => $password,
'username' => $username
]
)->save();
$userResourceModel = $this->model;
$this->assertEquals($token, $userModel->getRpToken());
$this->assertNotEquals(
$userModel->getRpToken(),
$userResourceModel->load($userModel, 'rp_token')
);
}
}
@@ -0,0 +1,675 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\User\Model;
use Magento\Authorization\Model\Role;
use Magento\Email\Model\ResourceModel\Template\Collection as TemplateCollection;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\App\Config\MutableScopeConfigInterface;
use Magento\Framework\Encryption\Encryptor;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NotFoundException;
use Magento\Framework\Exception\State\UserLockedException;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Phrase;
use Magento\Framework\Stdlib\DateTime;
use Magento\TestFramework\Bootstrap as TestFrameworkBootstrap;
use Magento\TestFramework\Entity;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Mail\Template\TransportBuilderMock;
use Magento\User\Model\User as UserModel;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class UserTest extends TestCase
{
/**
* @var UserModel
*/
protected $_model;
/**
* @var DateTime
*/
protected $_dateTime;
/**
* @var Role
*/
protected static $_newRole;
/**
* @var Encryptor
*/
private $encryptor;
/**
* @var CacheInterface
*/
private $cache;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->_model = $this->objectManager->create(UserModel::class);
$this->_dateTime = $this->objectManager->get(DateTime::class);
$this->encryptor = $this->objectManager->get(Encryptor::class);
$this->cache = $this->objectManager->get(CacheInterface::class);
}
/**
* @magentoDbIsolation enabled
*/
public function testCRUD()
{
$this->_model->setFirstname(
"John"
)->setLastname(
"Doe"
)->setUsername(
'user2'
)->setPassword(
TestFrameworkBootstrap::ADMIN_PASSWORD
)->setEmail(
'user@magento.com'
);
$crud = new Entity($this->_model, ['firstname' => '_New_name_']);
$crud->testCrud();
}
/**
* @magentoDataFixture Magento/User/_files/dummy_user.php
*/
public function testCreatedOnUpdate()
{
$this->_model->loadByUsername('user_created_date');
$this->assertEquals('2010-01-06 00:00:00', $this->_model->getCreated());
//reload to update lognum record
$this->_model->getResource()->recordLogin($this->_model);
$this->_model->reload();
$this->assertEquals('2010-01-06 00:00:00', $this->_model->getCreated());
}
/**
* Ensure that an exception is not thrown, if the user does not exist
*/
public function testLoadByUsername()
{
$this->_model->loadByUsername('non_existing_user');
$this->assertNull($this->_model->getId(), 'The admin user has an unexpected ID');
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$this->assertNotEmpty($this->_model->getId(), 'The admin user should have been loaded');
}
/**
* Test that user role is updated after save
*
* @magentoDataFixture roleDataFixture
*/
public function testUpdateRoleOnSave()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$this->assertEquals(TestFrameworkBootstrap::ADMIN_ROLE_NAME, $this->_model->getRole()->getRoleName());
$this->_model->setRoleId(self::$_newRole->getId())->save();
$this->assertEquals('admin_role', $this->_model->getRole()->getRoleName());
}
/**
* phpcs:disable Magento2.Functions.StaticFunction
*/
public static function roleDataFixture()
{
self::$_newRole = Bootstrap::getObjectManager()->create(
Role::class
);
self::$_newRole->setName('admin_role')->setRoleType('G')->setPid('1');
self::$_newRole->save();
}
/**
* @magentoDbIsolation enabled
*/
public function testSaveExtra()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$this->_model->saveExtra(['test' => 'val']);
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$extra = $this->_model->getExtra();
$this->assertEquals($extra['test'], 'val');
}
/**
* @magentoDataFixture roleDataFixture
*/
public function testGetRoles()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$roles = $this->_model->getRoles();
$this->assertCount(1, $roles);
$this->assertEquals(TestFrameworkBootstrap::ADMIN_ROLE_NAME, $this->_model->getRole()->getRoleName());
$this->_model->setRoleId(self::$_newRole->getId())->save();
$roles = $this->_model->getRoles();
$this->assertCount(1, $roles);
$this->assertEquals(self::$_newRole->getId(), $roles[0]);
}
/**
* @magentoDataFixture roleDataFixture
*/
public function testGetRole()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$role = $this->_model->getRole();
$this->assertInstanceOf(Role::class, $role);
$this->assertEquals(TestFrameworkBootstrap::ADMIN_ROLE_NAME, $this->_model->getRole()->getRoleName());
$this->_model->setRoleId(self::$_newRole->getId())->save();
$role = $this->_model->getRole();
$this->assertEquals(self::$_newRole->getId(), $role->getId());
}
/**
* @magentoDbIsolation enabled
*/
public function testDeleteFromRole()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$roles = $this->_model->getRoles();
$this->_model->setRoleId(reset($roles))->deleteFromRole();
$role = $this->_model->getRole();
$this->assertNull($role->getId());
}
public function testRoleUserExists()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$role = $this->_model->getRole();
$this->_model->setRoleId($role->getId());
$this->assertTrue($this->_model->roleUserExists());
$this->_model->setRoleId(100);
$this->assertFalse($this->_model->roleUserExists());
}
public function testGetCollection()
{
$this->assertInstanceOf(
AbstractCollection::class,
$this->_model->getCollection()
);
}
public function testGetName()
{
$firstname = TestFrameworkBootstrap::ADMIN_FIRSTNAME;
$lastname = TestFrameworkBootstrap::ADMIN_LASTNAME;
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$this->assertEquals("$firstname $lastname", $this->_model->getName());
$this->assertEquals("$firstname///$lastname", $this->_model->getName('///'));
}
public function testGetUninitializedAclRole()
{
$newuser = $this->objectManager->create(UserModel::class);
$newuser->setUserId(10);
$this->assertNull($newuser->getAclRole(), "User role was not initialized and is expected to be empty.");
}
/**
* @magentoAppIsolation enabled
* @magentoAdminConfigFixture admin/captcha/enable 0
* @magentoAdminConfigFixture admin/security/use_case_sensitive_login 1
*/
public function testAuthenticate()
{
$this->assertFalse($this->_model->authenticate('User', TestFrameworkBootstrap::ADMIN_PASSWORD));
$this->assertTrue(
$this->_model->authenticate(
TestFrameworkBootstrap::ADMIN_NAME,
TestFrameworkBootstrap::ADMIN_PASSWORD
)
);
}
/**
* @magentoAppIsolation enabled
* @magentoAdminConfigFixture admin/captcha/enable 0
* @magentoConfigFixture current_store admin/security/use_case_sensitive_login 0
*/
public function testAuthenticateCaseInsensitive()
{
$this->assertTrue($this->_model->authenticate('user', TestFrameworkBootstrap::ADMIN_PASSWORD));
$this->assertTrue(
$this->_model->authenticate(
TestFrameworkBootstrap::ADMIN_NAME,
TestFrameworkBootstrap::ADMIN_PASSWORD
)
);
}
/**
* @magentoDbIsolation enabled
*/
public function testAuthenticateInactiveUser()
{
$this->expectException(AuthenticationException::class);
$this->_model->load(1);
$this->_model->setIsActive(0)->save();
$this->_model->authenticate(
TestFrameworkBootstrap::ADMIN_NAME,
TestFrameworkBootstrap::ADMIN_PASSWORD
);
}
/**
* @magentoDataFixture Magento/User/_files/user_with_custom_role.php
* @magentoDbIsolation enabled
*/
public function testAuthenticateUserWithoutRole()
{
$this->expectException(AuthenticationException::class);
$this->_model->loadByUsername('customRoleUser');
$roles = $this->_model->getRoles();
$this->_model->setRoleId(reset($roles))->deleteFromRole();
$this->_model->authenticate(
'customRoleUser',
TestFrameworkBootstrap::ADMIN_PASSWORD
);
}
/**
* @magentoDbIsolation enabled
* @magentoAdminConfigFixture admin/captcha/enable 0
*/
public function testLoginsAreLogged()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$lognum = $this->_model->getLognum();
$beforeLogin = time();
$this->_model->login(
TestFrameworkBootstrap::ADMIN_NAME,
TestFrameworkBootstrap::ADMIN_PASSWORD
)->reload();
$loginTime = strtotime($this->_model->getLogdate());
$this->assertTrue($beforeLogin <= $loginTime && $loginTime <= time());
$this->assertEquals(++$lognum, $this->_model->getLognum());
$beforeLogin = time();
$this->_model->login(
TestFrameworkBootstrap::ADMIN_NAME,
TestFrameworkBootstrap::ADMIN_PASSWORD
)->reload();
$loginTime = strtotime($this->_model->getLogdate());
$this->assertTrue($beforeLogin <= $loginTime && $loginTime <= time());
$this->assertEquals(++$lognum, $this->_model->getLognum());
}
public function testReload()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$this->_model->setFirstname('NewFirstName');
$this->assertEquals('NewFirstName', $this->_model->getFirstname());
$this->_model->reload();
$this->assertEquals(TestFrameworkBootstrap::ADMIN_FIRSTNAME, $this->_model->getFirstname());
}
/**
* @magentoDbIsolation enabled
*/
public function testHasAssigned2Role()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$role = $this->_model->hasAssigned2Role($this->_model);
$this->assertCount(1, $role);
$this->assertArrayHasKey('role_id', $role[0]);
$roles = $this->_model->getRoles();
$this->_model->setRoleId(reset($roles))->deleteFromRole();
$this->cache->clean(['user_assigned_role']);
$this->assertEmpty($this->_model->hasAssigned2Role($this->_model));
}
/**
* @magentoDbIsolation enabled
*/
public function testBeforeSaveRequiredFieldsValidation()
{
$expectedMessages = '"User Name" is required. Enter and try again.' . PHP_EOL
. '"First Name" is required. Enter and try again.' . PHP_EOL
. '"Last Name" is required. Enter and try again.' . PHP_EOL
. 'Please enter a valid email.' . PHP_EOL
. 'Password is required field.' . PHP_EOL
. 'Invalid type given. String expected' . PHP_EOL
. 'Invalid type given. String, integer or float expected';
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage($expectedMessages);
$this->_model->setSomething('some_value');
// force model change
$this->_model->save();
}
/**
* @magentoDbIsolation enabled
*/
public function testBeforeSavePasswordHash()
{
$this->_model->setUsername(
'john.doe'
)->setFirstname(
'John'
)->setLastname(
'Doe'
)->setEmail(
'jdoe@example.com'
)->setPassword(
'123123q'
);
$this->_model->save();
$this->assertStringNotContainsString(
'123123q',
$this->_model->getPassword(),
'Password is expected to be hashed'
);
$this->assertMatchesRegularExpression(
'/^[^\:]+\:[^\:]+\:/i',
$this->_model->getPassword(),
'Salt is expected to be saved along with the password'
);
/** @var UserModel $model */
$model = $this->objectManager->create(UserModel::class);
$model->load($this->_model->getId());
$this->assertEquals(
$this->_model->getPassword(),
$model->getPassword(),
'Password data has been corrupted during saving'
);
}
/**
* @magentoDbIsolation enabled
*/
public function testBeforeSavePasswordsDoNotMatch()
{
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage('Your password confirmation must match your password.');
$this->_model->setPassword('password2');
$this->_model->setPasswordConfirmation('password1');
$this->_model->save();
}
/**
* @magentoDbIsolation enabled
*/
public function testBeforeSavePasswordTooShort()
{
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage('Your password must include both numeric and alphabetic characters.');
$this->_model->setPassword('123456');
$this->_model->save();
}
/**
* @dataProvider beforeSavePasswordInsecureDataProvider
* @magentoDbIsolation enabled
* @param string $password
*/
public function testBeforeSavePasswordInsecure($password)
{
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage('Your password must include both numeric and alphabetic characters.');
$this->_model->setPassword($password);
$this->_model->save();
}
public function beforeSavePasswordInsecureDataProvider()
{
return ['alpha chars only' => ['aaaaaaaa'], 'digits only' => ['1234567']];
}
/**
* @magentoDbIsolation enabled
*/
public function testBeforeSaveUserIdentityViolation()
{
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage('A user with the same user name or email already exists.');
$this->_model->setUsername('user');
$this->_model->save();
}
/**
* @magentoDbIsolation enabled
*/
public function testBeforeSaveValidationSuccess()
{
$this->_model->setUsername(
'user1'
)->setFirstname(
'John'
)->setLastname(
'Doe'
)->setEmail(
'jdoe@example.com'
)->setPassword(
'1234abc'
)->setPasswordConfirmation(
'1234abc'
);
$this->_model->save();
}
/**
* @magentoDbIsolation enabled
*/
public function testChangeResetPasswordLinkToken()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$userId = $this->_model->getId();
$this->_model->changeResetPasswordLinkToken('test');
$date = $this->_model->getRpTokenCreatedAt();
$this->assertNotNull($date);
$this->_model->save();
$this->_model->load($userId);
$this->assertEquals('test', $this->_model->getRpToken());
$this->assertEquals(strtotime($date), strtotime($this->_model->getRpTokenCreatedAt()));
}
/**
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoConfigFixture default/admin/emails/password_reset_link_expiration_period 2
*/
public function testIsResetPasswordLinkTokenExpired()
{
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$this->assertTrue($this->_model->isResetPasswordLinkTokenExpired());
$this->_model->changeResetPasswordLinkToken('test');
$this->_model->save();
$this->_model->loadByUsername(TestFrameworkBootstrap::ADMIN_NAME);
$this->assertFalse($this->_model->isResetPasswordLinkTokenExpired());
$this->_model->setRpTokenCreatedAt($this->_dateTime->formatDate(time() - 60 * 60 * 2 + 2));
$this->assertFalse($this->_model->isResetPasswordLinkTokenExpired());
$this->_model->setRpTokenCreatedAt($this->_dateTime->formatDate(time() - 60 * 60 * 2 - 1));
$this->assertTrue($this->_model->isResetPasswordLinkTokenExpired());
}
public function testGetSetHasAvailableResources()
{
$this->_model->setHasAvailableResources(true);
$this->assertTrue($this->_model->hasAvailableResources());
$this->_model->setHasAvailableResources(false);
$this->assertFalse($this->_model->hasAvailableResources());
}
/**
* Here we test if admin identity check executed successfully
*
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testPerformIdentityCheck()
{
$this->_model->loadByUsername('adminUser');
$passwordString = TestFrameworkBootstrap::ADMIN_PASSWORD;
$this->_model->performIdentityCheck($passwordString);
}
/**
* Here we check for a wrong password
*
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testPerformIdentityCheckWrongPassword()
{
$this->expectException(AuthenticationException::class);
$this->_model->loadByUsername('adminUser');
$passwordString = 'wrongPassword';
$this->_model->performIdentityCheck($passwordString);
$this->expectExceptionMessage(
'The password entered for the current user is invalid. Verify the password and try again.'
);
}
/**
* Here we check for a locked user
*
* @magentoDataFixture Magento/User/_files/locked_users.php
*/
public function testPerformIdentityCheckLockExpires()
{
$this->expectException(UserLockedException::class);
$this->_model->loadByUsername('adminUser2');
$this->_model->performIdentityCheck(TestFrameworkBootstrap::ADMIN_PASSWORD);
$this->expectExceptionMessage(
'The account sign-in was incorrect or your account is disabled temporarily. '
. 'Please wait and try again later.'
);
}
/**
* Verify custom notification is sent when new user created
*
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Email/Model/_files/email_template_new_user_notification.php
*/
public function testSendNotificationEmailsIfRequired()
{
/** @var MutableScopeConfigInterface $config */
$config = Bootstrap::getObjectManager()
->get(MutableScopeConfigInterface::class);
$config->setValue(
'admin/emails/new_user_notification_template',
$this->getCustomEmailTemplateId(
'admin_emails_new_user_notification_template'
)
);
$userModel = Bootstrap::getObjectManager()
->create(User::class);
$userModel->setFirstname(
'John'
)->setLastname(
'Doe'
)->setUsername(
'user2'
)->setPassword(
TestFrameworkBootstrap::ADMIN_PASSWORD
)->setEmail(
'user@magento.com'
);
$userModel->save();
$userModel->sendNotificationEmailsIfRequired();
/** @var TransportBuilderMock $transportBuilderMock */
$transportBuilderMock = Bootstrap::getObjectManager()
->get(TransportBuilderMock::class);
$sentMessage = $transportBuilderMock->getSentMessage();
$this->assertSame(
'New User Notification Custom Text ' . $userModel->getFirstname() . ', ' . $userModel->getLastname(),
$sentMessage->getBodyText()
);
}
/**
* Return email template id by origin template code
*
* @param string $origTemplateCode
* @return int|null
* @throws NotFoundException
*/
private function getCustomEmailTemplateId(string $origTemplateCode): ?int
{
$templateId = null;
$templateCollection = Bootstrap::getObjectManager()
->create(TemplateCollection::class);
foreach ($templateCollection as $template) {
if ($template->getOrigTemplateCode() == $origTemplateCode) {
$templateId = (int) $template->getId();
}
}
if ($templateId === null) {
throw new NotFoundException(new Phrase(
'Customized %templateCode% email template not found',
['templateCode' => $origTemplateCode]
));
}
return $templateId;
}
/**
* Verify custom notification is correctly when reset admin password
*
* @magentoDataFixture Magento/Email/Model/_files/email_template_reset_password_user_notification.php
* @magentoDataFixture Magento/User/_files/user_with_role.php
*/
public function testNotificationEmailsIfResetPassword()
{
/** @var MutableScopeConfigInterface $config */
$config = Bootstrap::getObjectManager()
->get(MutableScopeConfigInterface::class);
$config->setValue(
'admin/emails/forgot_email_template',
$this->getCustomEmailTemplateId(
'admin_emails_forgot_email_template'
)
);
$userModel = $this->_model->loadByUsername('adminUser');
$notificator = $this->objectManager->get(\Magento\User\Model\Spi\NotificatorInterface::class);
$notificator->sendForgotPassword($userModel);
/** @var TransportBuilderMock $transportBuilderMock */
$transportBuilderMock = $this->objectManager->get(TransportBuilderMock::class);
$sentMessage = $transportBuilderMock->getSentMessage();
$this->assertStringContainsString(
'id='.$userModel->getId(),
quoted_printable_decode($sentMessage->getBodyText())
);
}
}
@@ -0,0 +1,78 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\User\Model;
use Magento\Backend\Model\Auth as AuthModel;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\User\Model\User as UserModel;
use Magento\User\Test\Fixture\User as UserDataFixture;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
*/
class ValidateUserDateFieldsTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* @var AuthModel
*/
protected $authModel;
/**
* @var UserModel
*/
protected $userModel;
/**
* @throws LocalizedException
*/
protected function setUp(): void
{
Bootstrap::getInstance()->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$this->objectManager = Bootstrap::getObjectManager();
$this->fixtures = DataFixtureStorageManager::getStorage();
$this->authModel = $this->objectManager->create(AuthModel::class);
$this->userModel = $this->objectManager->create(UserModel::class);
}
/**
* @throws AuthenticationException
* @throws LocalizedException
*/
#[
DataFixture(UserDataFixture::class, ['role_id' => 1], 'user')
]
public function testLogDate()
{
$user = $this->fixtures->get('user');
$userName = $user->getDataByKey('username');
$this->authModel->login(
$userName,
\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD
);
$this->userModel->loadByUsername($userName);
$this->assertNotNull($this->userModel->getLogdate());
}
}
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Create dummy user
*/
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\User\Model\User::class);
$user->setFirstname(
'Dummy'
)->setLastname(
'Dummy'
)->setEmail(
'dummy@dummy.com'
)->setUsername(
'dummy_username'
)->setPassword(
'dummy_password1'
)->save();
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\User\Model\User::class);
$user->setFirstname(
'CreateDate'
)->setLastname(
'User 2'
)->setEmail(
'dummy2@dummy.com'
)->setUsername(
'user_created_date'
)->setPassword(
'dummy_password2'
)->save();
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\User\Model\User::class);
$user->loadByUsername('user_created_date');
$user->setCreated('2010-01-06 00:00:00');
$user->save();
@@ -0,0 +1,51 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/**
* Create an admin user with an assigned role
*/
$userIds = [];
/** @var $model \Magento\User\Model\User */
$model = $objectManager->create(\Magento\User\Model\User::class);
$model->setFirstname("John")
->setLastname("Doe")
->setUsername('adminUser1')
->setPassword(\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD)
->setEmail('adminUser1@example.com')
->setRoleType('G')
->setResourceId('Magento_Adminhtml::all')
->setPrivileges("")
->setAssertId(0)
->setRoleId(1)
->setPermission('allow');
$model->save();
$userIds[] = $model->getDataByKey('user_id');
/** @var $model \Magento\User\Model\User */
$model = $objectManager->create(\Magento\User\Model\User::class);
$model->setFirstname("John")
->setLastname("Doe")
->setUsername('adminUser2')
->setPassword(\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD)
->setEmail('adminUser2@example.com')
->setRoleType('G')
->setResourceId('Magento_Adminhtml::all')
->setPrivileges("")
->setAssertId(0)
->setRoleId(1)
->setPermission('allow');
$model->save();
$userIds[] = $model->getDataByKey('user_id');
$defaultAdminUserId = 1;
$lockLifetime = 86400;
/** @var $modelLockedUsers \Magento\User\Model\ResourceModel\User */
$modelLockedUsers = $objectManager->create(\Magento\User\Model\ResourceModel\User::class);
$modelLockedUsers->lock($userIds, $defaultAdminUserId, $lockLifetime);
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Authorization\Model\RoleFactory;
use Magento\Authorization\Model\Role;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\User\Model\User;
use Magento\Authorization\Model\RulesFactory;
use Magento\Authorization\Model\Rules;
//Creating a new admin user with a custom role to safely change role settings without affecting the main user's role.
/** @var Role $role */
$role = Bootstrap::getObjectManager()->get(RoleFactory::class)->create();
$role->setName('test_custom_role');
$role->setData('role_name', $role->getName());
$role->setRoleType(\Magento\Authorization\Model\Acl\Role\Group::ROLE_TYPE);
$role->setUserType((string)\Magento\Authorization\Model\UserContextInterface::USER_TYPE_ADMIN);
$role->save();
/** @var Rules $rules */
$rules = Bootstrap::getObjectManager()->get(RulesFactory::class)->create();
$rules->setRoleId($role->getId());
//Granted all permissions.
$rules->setResources([Bootstrap::getObjectManager()->get(\Magento\Framework\Acl\RootResource::class)->getId()]);
$rules->saveRel();
/** @var User $user */
$user = Bootstrap::getObjectManager()->create(User::class);
$user->setFirstname("John")
->setLastname("Doe")
->setUsername('customRoleUser')
->setPassword(\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD)
->setEmail('adminUser@example.com')
->setIsActive(1)
->setRoleId($role->getId());
$user->save();
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Authorization\Model\RoleFactory;
use Magento\Authorization\Model\Role;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\User\Model\UserFactory;
use Magento\User\Model\User;
use Magento\Authorization\Model\RulesFactory;
use Magento\Authorization\Model\Rules;
//Deleting the user and the role.
/** @var \Magento\Framework\ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var User $user */
$user = $objectManager->create(UserFactory::class)->create();
$user->load('customRoleUser', 'username');
if ($user->getId() !== null) {
$user->delete();
}
/** @var Role $role */
$role = Bootstrap::getObjectManager()->get(RoleFactory::class)->create();
$role->load('test_custom_role', 'role_name');
/** @var Rules $rules */
$rules = Bootstrap::getObjectManager()->get(RulesFactory::class)->create();
$rules->load($role->getId(), 'role_id');
if ($rules->getId() !== null) {
$rules->delete();
}
if ($role->getId() !== null) {
$role->delete();
}
@@ -0,0 +1,24 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Create an admin user with an assigned role
*/
/** @var $model \Magento\User\Model\User */
$model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\User\Model\User::class);
$model->setFirstname("John")
->setLastname("Doe")
->setUsername('adminUser')
->setPassword(\Magento\TestFramework\Bootstrap::ADMIN_PASSWORD)
->setEmail('adminUser@example.com')
->setRoleType('G')
->setResourceId('Magento_Backend::all')
->setPrivileges("")
->setAssertId(0)
->setRoleId(1)
->setPermission('allow');
$model->save();
@@ -0,0 +1,16 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\TestFramework\Helper\Bootstrap;
use Magento\User\Model\User;
/** @var $model \Magento\User\Model\User */
$model = Bootstrap::getObjectManager()->create(User::class);
$user = $model->loadByUsername('adminUser');
if ($user->getId()) {
$model->delete();
}