Skip to content

Commit

Permalink
Merge pull request #406 from magento-performance/cabpi-227-admin-ui-c…
Browse files Browse the repository at this point in the history
…hanges

CABPI-227: Admin UI changes
  • Loading branch information
andimov authored Mar 30, 2022
2 parents c134871 + aeaf5c0 commit 390f843
Show file tree
Hide file tree
Showing 38 changed files with 1,503 additions and 37 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

declare(strict_types=1);

namespace Magento\AdminAdobeIms\Block\Adminhtml\System\Config\Form\Field;

use Magento\Backend\Block\Template\Context;
use Magento\Framework\View\Helper\SecureHtmlRenderer;
use Magento\AdminAdobeIms\Service\ImsConfig;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;

class Disabled extends Field
{
/** @var ImsConfig */
private ImsConfig $imsConfig;

/**
* @param Context $context
* @param SecureHtmlRenderer $secureRenderer
* @param ImsConfig $imsConfig
* @param array $data
*/
public function __construct(
Context $context,
SecureHtmlRenderer $secureRenderer,
ImsConfig $imsConfig,
array $data = []
) {
parent::__construct($context, $data, $secureRenderer);
$this->imsConfig = $imsConfig;
}

/**
* Return an empty string for the render if our module is enabled
*
* @param AbstractElement $element
* @return string
*/
public function render(AbstractElement $element): string
{
if ($this->imsConfig->enabled() === false) {
return parent::render($element);
}
return '';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php
// phpcs:ignoreFile
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

namespace Magento\AdminAdobeIms\Controller\Adminhtml\User;

use Magento\Backend\Model\Auth\Session;
use Magento\User\Block\User\Edit\Tab\Main as UserEdit;
use Magento\User\Controller\Adminhtml\User as UserController;
use Magento\User\Model\User;

/**
* @SuppressWarnings(PHPMD.AllPurposeAction)
*/
class Delete extends UserController
{
/**
* @return void
*/
public function execute()
{
/** @var User */
$currentUser = $this->_objectManager->get(Session::class)->getUser();
$userId = (int)$this->getRequest()->getPost('user_id');

if ($userId) {
if ((int)$currentUser->getId() === $userId) {
$this->messageManager->addError(__('You cannot delete your own account.'));
$this->_redirect('adminhtml/*/edit', ['user_id' => $userId]);
return;
}
try {
$currentUserPassword = (string)$this->getRequest()->getPost(UserEdit::CURRENT_USER_PASSWORD_FIELD);
$currentUser->performIdentityCheck($currentUserPassword);
/** @var User $model */
$model = $this->_userFactory->create();
$model->setId($userId);
$model->delete();
$this->messageManager->addSuccess(__('You deleted the user.'));
$this->_redirect('adminhtml/*/');
return;
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
$this->_redirect('adminhtml/*/edit', ['user_id' => $this->getRequest()->getParam('user_id')]);
return;
}
}
$this->messageManager->addError(__('We can\'t find a user to delete.'));
$this->_redirect('adminhtml/*/');
}
}
147 changes: 147 additions & 0 deletions app/code/Magento/AdminAdobeIms/Controller/Adminhtml/User/Save.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
<?php
// phpcs:ignoreFile
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

namespace Magento\AdminAdobeIms\Controller\Adminhtml\User;

use Magento\Backend\Model\Auth\Session;
use Magento\Backend\Model\Locale\Manager;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\State\UserLockedException;
use Magento\Framework\Validator\Exception;
use Magento\Framework\Validator\Locale;
use Magento\Security\Model\AdminSessionsManager;
use Magento\Security\Model\SecurityCookie;
use Magento\User\Controller\Adminhtml\User as UserController;
use Magento\User\Model\Spi\NotificationExceptionInterface;
use Magento\User\Block\User\Edit\Tab\Main;
use Magento\User\Model\User;

/**
* Save admin user.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Save extends UserController implements HttpPostActionInterface
{
/**
* @var SecurityCookie
*/
private $securityCookie;

/**
* Get security cookie
*
* @return SecurityCookie
* @deprecated 100.1.0
*/
private function getSecurityCookie()
{
if (!($this->securityCookie instanceof SecurityCookie)) {
return \Magento\Framework\App\ObjectManager::getInstance()->get(SecurityCookie::class);
} else {
return $this->securityCookie;
}
}

/**
* @inheritDoc
* @return ResultInterface|ResponseInterface
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function execute()
{
$userId = (int)$this->getRequest()->getParam('user_id');
$data = $this->getRequest()->getPostValue();
if (array_key_exists('form_key', $data)) {
unset($data['form_key']);
}
if (!$data) {
$this->_redirect('adminhtml/*/');
return;
}

/** @var $model User */
$model = $this->_userFactory->create()->load($userId);
if ($userId && $model->isObjectNew()) {
$this->messageManager->addError(__('This user no longer exists.'));
$this->_redirect('adminhtml/*/');
return;
}
$model->setData($this->_getAdminUserData($data));
$userRoles = $this->getRequest()->getParam('roles', []);
if (count($userRoles)) {
$model->setRoleId($userRoles[0]);
}

/** @var $currentUser User */
$currentUser = $this->_objectManager->get(Session::class)->getUser();
if ($userId == $currentUser->getId()
&& $this->_objectManager->get(Locale::class)
->isValid($data['interface_locale'])
) {
$this->_objectManager->get(
Manager::class
)->switchBackendInterfaceLocale(
$data['interface_locale']
);
}

/** Before updating admin user data, ensure that password of current admin user is entered and is correct */
try {
$currentUser->performIdentityCheck($data[Main::CURRENT_USER_PASSWORD_FIELD] ?? '');
$model->save();

$this->messageManager->addSuccess(__('You saved the user.'));
$this->_getSession()->setUserData(false);
$this->_redirect('adminhtml/*/');

$model->sendNotificationEmailsIfRequired();
} catch (UserLockedException $e) {
$this->_auth->logout();
$this->getSecurityCookie()->setLogoutReasonCookie(
AdminSessionsManager::LOGOUT_REASON_USER_LOCKED
);
$this->_redirect('*');
} catch (NotificationExceptionInterface $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
} catch (AuthenticationException $e) {
$this->messageManager->addError(
__('The password entered for the current user is invalid. Verify the password and try again.')
);
$this->redirectToEdit($model, $data);
} catch (Exception $e) {
$messages = $e->getMessages();
$this->messageManager->addMessages($messages);
$this->redirectToEdit($model, $data);
} catch (LocalizedException $e) {
if ($e->getMessage()) {
$this->messageManager->addError($e->getMessage());
}
$this->redirectToEdit($model, $data);
}
}

/**
* Redirect to Edit form.
*
* @param User $model
* @param array $data
* @return void
*/
private function redirectToEdit(User $model, array $data)
{
$this->_getSession()->setUserData($data);
$arguments = $model->getId() ? ['user_id' => $model->getId()] : [];
$arguments = array_merge($arguments, ['_current' => true, 'active_tab' => '']);
$this->_redirect('adminhtml/*/edit', $arguments);
}
}
49 changes: 43 additions & 6 deletions app/code/Magento/AdminAdobeIms/Model/ImsConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ class ImsConnection
* @var ImsConfig
*/
private ImsConfig $imsConfig;

/**
* @var Json
*/
private Json $json;

/**
* @var GetToken
*/
Expand Down Expand Up @@ -114,12 +116,12 @@ private function getAuthorizationLocation(string $authUrl): string
private function validateResponse(Curl $curl): void
{
if (isset($curl->getHeaders()['location'])) {
if (
preg_match(
'/error=([a-z_]+)/i',
$curl->getHeaders()['location'],
$error
) && isset($error[0], $error[1])
if (preg_match(
'/error=([a-z_]+)/i',
$curl->getHeaders()['location'],
$error
)
&& isset($error[0], $error[1])
) {
throw new InvalidArgumentException(
__('Could not connect to Adobe IMS Service: %1.', $error[1])
Expand All @@ -135,6 +137,39 @@ private function validateResponse(Curl $curl): void
}

/**
* Verify if access_token is valid
*
* @param string $code
* @return bool
* @throws AuthorizationException
*/
public function verifyToken(string $code): bool
{
$curl = $this->curlFactory->create();

$curl->addHeader('Content-Type', 'application/x-www-form-urlencoded');
$curl->addHeader('cache-control', 'no-cache');
$curl->addHeader('Authorization', 'Bearer ' . $code);

$curl->post(
$this->imsConfig->getVerifyUrl($code),
[]
);

if ($curl->getBody() === '') {
throw new AuthorizationException(
__('Could not verify the access_token')
);
}

$body = $this->json->unserialize($curl->getBody());

return isset($body['valid']) && $body['valid'] === true;
}

/**
* Get token response
*
* @param string $code
* @return TokenResponseInterface
* @throws AdobeImsTokenAuthorizationException
Expand All @@ -151,6 +186,8 @@ public function getTokenResponse(string $code): TokenResponseInterface
}

/**
* Get profile url
*
* @param string $code
* @return array|bool|float|int|mixed|string|null
* @throws AuthorizationException
Expand Down
10 changes: 6 additions & 4 deletions app/code/Magento/AdminAdobeIms/Model/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ protected function _construct()
}

/**
* Load user by email
*
* @param string $email
* @return array
*/
Expand All @@ -50,7 +52,7 @@ public function loginByUsername($username): User
}

/**
* Authenticate user name and save loaded record
* Authenticate username and save loaded record
*
* @param string $username
* @return bool
Expand All @@ -67,7 +69,7 @@ public function authenticateByUsername(string $username): bool
['username' => $username, 'user' => $this]
);
$this->loadByUsername($username);
$sensitive = $config ? $username == $this->getUserName() : true;
$sensitive = !$config || $username === $this->getUserName();
if ($sensitive && $this->getId()) {
$result = $this->verifyIdentityWithoutPassword();
}
Expand All @@ -87,7 +89,7 @@ public function authenticateByUsername(string $username): bool
* Check if the current user account is active.
*
* @return bool
* @throws \Magento\Framework\Exception\AuthenticationException
* @throws AuthenticationException
*/
public function verifyIdentityWithoutPassword(): bool
{
Expand All @@ -105,4 +107,4 @@ public function verifyIdentityWithoutPassword(): bool

return true;
}
}
}
Loading

0 comments on commit 390f843

Please sign in to comment.