Skip to content

Commit

Permalink
[MBO-1249] Catch empty employee email exception (#625)
Browse files Browse the repository at this point in the history
* Catch empty employee email exception

* Display a message when apiUser cannot be created

* Update src/Api/Security/AdminAuthenticationProvider.php

Co-authored-by: Vincent Garcia <[email protected]>

* Update src/Traits/Hooks/UseDisplayDashboardTop.php

Co-authored-by: Vincent Garcia <[email protected]>

* Add reset URL

* Add data to Sentry log

* Change reset link

* Delete lock file if employee exists

* Design the failed user alert

* Fix service instantiation

* Fix text and error handler injection

* Translation catalogue update for version fix/MBO-1249/catch-employee-email-exception 2023-09-12-09_53_54 (#627)

Co-authored-by: Github Actions - Module translation tool <>

* New Crowdin updates (#628)

---------

Co-authored-by: Vincent Garcia <[email protected]>
  • Loading branch information
sowbiba and intraordinaire authored Sep 14, 2023
1 parent f5e1e56 commit 4fa8184
Show file tree
Hide file tree
Showing 35 changed files with 491 additions and 267 deletions.
2 changes: 1 addition & 1 deletion ps_mbo.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public function uninstall()
$this->getAdminAuthenticationProvider()->deletePossibleApiUser();
$this->getAdminAuthenticationProvider()->clearCache();

$lockFiles = ['registerShop', 'updateShop'];
$lockFiles = ['registerShop', 'updateShop', 'createApiUser'];
foreach ($lockFiles as $lockFile) {
if (file_exists($this->moduleCacheDir . $lockFile . '.lock')) {
unlink($this->moduleCacheDir . $lockFile . '.lock');
Expand Down
81 changes: 77 additions & 4 deletions src/Api/Security/AdminAuthenticationProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
use Doctrine\DBAL\Connection;
use Employee;
use EmployeeSession;
use Exception;
use Firebase\JWT\JWT;
use PrestaShop\Module\Mbo\Handler\ErrorHandler\ErrorHandler;
use PrestaShop\Module\Mbo\Handler\ErrorHandler\ErrorHandlerInterface;
use PrestaShop\Module\Mbo\Helpers\Config;
use PrestaShop\PrestaShop\Core\Crypto\Hashing;
use PrestaShop\PrestaShop\Core\Domain\Employee\Exception\EmployeeException;
Expand All @@ -37,6 +40,8 @@

class AdminAuthenticationProvider
{
private const DEFAULT_EMPLOYEE_ID = 42;

/**
* @var Connection
*/
Expand All @@ -62,6 +67,11 @@ class AdminAuthenticationProvider
*/
private $cacheProvider;

/**
* @var ErrorHandlerInterface
*/
private $errorHandler;

public function __construct(
Connection $connection,
Context $context,
Expand All @@ -76,11 +86,18 @@ public function __construct(
$this->cacheProvider = $cacheProvider;
}

public function createApiUser(): Employee
public function createApiUser(): ?Employee
{
$moduleCacheDir = sprintf('%s/var/modules/ps_mbo/', rtrim(_PS_ROOT_DIR_, '/'));
$lockFile = $moduleCacheDir . 'createApiUser.lock';

$employee = $this->getApiUser();

if (null !== $employee) {
if (file_exists($lockFile)) {
unlink($lockFile);
}

return $employee;
}

Expand All @@ -95,8 +112,27 @@ public function createApiUser(): Employee
$employee->active = true;
$employee->passwd = $this->hashing->hash(uniqid('', true));

if (!$employee->add()) {
throw new EmployeeException('Failed to add PsMBO API user');
try {
if (!$employee->add()) {
throw new EmployeeException('Failed to add PsMBO API user');
}

if (file_exists($lockFile)) {
unlink($lockFile);
}
} catch (Exception $e) {
// Create the lock file
if (!file_exists($lockFile)) {
if (!is_dir($moduleCacheDir)) {
mkdir($moduleCacheDir, 0777, true);
}
$f = fopen($lockFile, 'w+');
fclose($f);
}

$this->logFailedEmployeeException($e);

return null;
}

return $employee;
Expand Down Expand Up @@ -130,7 +166,7 @@ public function getApiUser(): ?Employee
/**
* @throws EmployeeException
*/
public function ensureApiUserExistence(): Employee
public function ensureApiUserExistence(): ?Employee
{
$apiUser = $this->getApiUser();

Expand Down Expand Up @@ -192,6 +228,11 @@ public function getAdminToken(): string
$apiUser = $this->ensureApiUserExistence();
$idTab = Tab::getIdFromClassName('apiPsMbo');

// An error on user creation, use a default user (?) and don't cache it
if (!$apiUser) {
return $this->getDefaultUserToken();
}

$token = Tools::getAdminToken('apiPsMbo' . (int) $idTab . (int) $apiUser->id);

$this->cacheProvider->save($cacheKey, $token, 0); // Lifetime infinite, will be purged when MBO is uninstalled
Expand All @@ -214,6 +255,11 @@ public function getMboJWT(): string

$jwtToken = JWT::encode(['shop_url' => $shopUrl, 'shop_uuid' => $shopUuid], $mboUserToken, 'HS256');

// Don't put in cache if we have the default user token
if ($this->getDefaultUserToken() === $mboUserToken) {
return $jwtToken;
}

$this->cacheProvider->save($cacheKey, $jwtToken, 0); // Lifetime infinite, will be purged when MBO is uninstalled

return $this->cacheProvider->fetch($cacheKey);
Expand All @@ -234,4 +280,31 @@ private function getJwtTokenCacheKey(): string
{
return sprintf('mbo_jwt_token_%s', Config::getShopMboUuid());
}

private function getDefaultUserToken(): string
{
$idTab = Tab::getIdFromClassName('apiPsMbo');

return Tools::getAdminToken('apiPsMbo' . (int) $idTab . self::DEFAULT_EMPLOYEE_ID);
}

private function logFailedEmployeeException(Exception $e): void
{
$this->getErrorHandler()->handle($e, null, false, [
'shop_mbo_uuid' => Config::getShopMboUuid(),
'shop_mbo_admin_mail' => Config::getShopMboAdminMail(),
'shop_url' => Config::getShopUrl(),
'multishop' => \Shop::isFeatureActive(),
'number_of_shops' => \Shop::getTotalShops(false, null),
]);
}

private function getErrorHandler(): ErrorHandler
{
if (null === $this->errorHandler) {
$this->errorHandler = new ErrorHandler();
}

return $this->errorHandler;
}
}
2 changes: 1 addition & 1 deletion src/Traits/Hooks/UseActionAdminControllerSetMedia.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function hookActionAdminControllerSetMedia(): void
if (Tools::getValue('controller') === "AdminPsMboModule") {
$this->context->controller->addJs($this->getPathUri() . 'views/js/upload_module_with_cdc.js?v=' . $this->version);
}

if (empty($this->adminControllerMediaMethods)) {
return;
}
Expand Down
35 changes: 34 additions & 1 deletion src/Traits/Hooks/UseDisplayDashboardTop.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use Exception;
use Hook;
use PrestaShop\Module\Mbo\Tab\TabInterface;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use ToolsCore as Tools;

Expand Down Expand Up @@ -82,13 +83,24 @@ public function bootUseDisplayDashboardTop(): void
*/
public function hookDisplayDashboardTop(): string
{
// Check if this page has already been processed by the hook to avoid duplciate content
// Check if this page has already been processed by the hook to avoid duplicate content
if ($this->alreadyProcessedPage) {
return '';
}
$this->alreadyProcessedPage = true;

$values = Tools::getAllValues();
$moduleCacheDir = sprintf('%s/var/modules/ps_mbo/', rtrim(_PS_ROOT_DIR_, '/'));
$createApiUserLockFile = $moduleCacheDir . 'createApiUser.lock';

if (
isset($values['controller']) &&
($values['controller'] === 'AdminPsMboModule') &&
file_exists($createApiUserLockFile)
) {
return $this->displayFailedApiUser();
}

//Check if we are on configuration page & if the module needs to have a push on this page
if (
isset($values['controller']) &&
Expand Down Expand Up @@ -151,6 +163,27 @@ protected function displayPushOnConfigurationPage(string $moduleName): string
return $this->fetch('module:ps_mbo/views/templates/hook/push-configuration.tpl');
}

private function displayFailedApiUser()
{
try {
/** @var \Twig\Environment $twig */
$twig = $this->get('twig');

/**
* @var Router $router
*/
$router = $this->get('router');

return $twig->render(
'@Modules/ps_mbo/views/templates/hook/twig/failed-api-user.html.twig', [
'module_manager_link' => $router->generate('admin_module_manage'),
]
);
} catch (\Exception $e) {
return '';
}
}

/**
* Compute & include data with recommended modules when needed
*
Expand Down
15 changes: 12 additions & 3 deletions translations/de-DE/ModulesMboGlobal.de-DE.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
<trans-unit id="3b89e163ae0b446bd02e13de8dcf70d3" approved="yes">
<source><![CDATA[For even more security on your website forms, consult our Security & Access modules category on the]]></source>
<target state="final"><![CDATA[Weitere Module zur Datensicherheit finden Sie bei PrestaShop Addons im Bereich "Sicherheit und Berechtigungen":]]></target>
<note>Line: 131</note>
<note>Line: 143</note>
</trans-unit>
<trans-unit id="3aaeb3f0458cf2580c5f75fefdb86ab6" approved="yes">
<source>PrestaShop Addons Marketplace</source>
<target state="final">PrestaShop Addons Marktplatz</target>
<note>Line: 147</note>
<note>Line: 159</note>
</trans-unit>
<trans-unit id="71f716ae5452ef886e40d36f14afed87" approved="yes">
<source>Discover more modules to improve your shop on</source>
<target state="final">Entdecken Sie weitere Module zur Verbesserung Ihres Shops auf</target>
<note>Line: 145</note>
<note>Line: 157</note>
</trans-unit>
</body>
</file>
Expand All @@ -38,4 +38,13 @@
</trans-unit>
</body>
</file>
<file original="views/templates/hook/twig/failed-api-user.html.twig" source-language="en" target-language="de" datatype="plaintext">
<body>
<trans-unit id="a4eb3ae1fceef46fa21eb216a5316651">
<source>Your module needs to be reset. The PrestaShop Marketplace in your back office is no longer working properly. Please try resetting the module in your %link%. If the problem persists, feel free to contact the support.</source>
<target state="translated">Your module needs to be reset. The PrestaShop Marketplace in your back office is no longer working properly. Please try resetting the module in your %link%. If the problem persists, feel free to contact the support.</target>
<note>Line: 22</note>
</trans-unit>
</body>
</file>
</xliff>
6 changes: 3 additions & 3 deletions translations/de-DE/ModulesMboLinks.de-DE.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,17 @@
<trans-unit id="9d86b7d3c7427a887c6e182f75deb3e0" approved="yes">
<source><![CDATA[https://addons.prestashop.com/en/429-website-security-access?utm_source=back-office&utm_medium=native-contactform&utm_campaign=back-office-EN&utm_content=security]]></source>
<target state="final"><![CDATA[https://addons.prestashop.com/de/429-sicherheit-berechtigungen?utm_source=back-office&utm_medium=native-contactform&utm_campaign=back-office-DE&utm_content=security]]></target>
<note>Line: 132</note>
<note>Line: 144</note>
</trans-unit>
<trans-unit id="198214f6abf95fc35f5f0fb3b70946a3" approved="yes">
<source><![CDATA[https://addons.prestashop.com/en/517-blocks-tabs-banners?utm_source=back-office&utm_medium=modules&utm_campaign=back-office-EN]]></source>
<target state="final"><![CDATA[https://addons.prestashop.com/?utm_source=back-office&utm_medium=modules&utm_campaign=back-office-DE]]></target>
<note>Line: 139</note>
<note>Line: 151</note>
</trans-unit>
<trans-unit id="f9baae88cd2cd24d7c8b13fd1906aab6" approved="yes">
<source><![CDATA[https://addons.prestashop.com/?utm_source=back-office&utm_medium=modules&utm_campaign=back-office-EN]]></source>
<target state="final"><![CDATA[https://addons.prestashop.com/?utm_source=back-office&utm_medium=modules&utm_campaign=back-office-DE]]></target>
<note>Line: 146</note>
<note>Line: 158</note>
</trans-unit>
</body>
</file>
Expand Down
Loading

0 comments on commit 4fa8184

Please sign in to comment.