Skip to content

Commit

Permalink
Merge pull request #20 from bayonetio/technical-review-fixes
Browse files Browse the repository at this point in the history
Technical review fixes
  • Loading branch information
ilugobayo authored Feb 11, 2021
2 parents c75f905 + 04919bd commit bba1092
Show file tree
Hide file tree
Showing 10 changed files with 86 additions and 53 deletions.
4 changes: 1 addition & 3 deletions Controller/Adminhtml/BayonetBlocklist/ListAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ public function execute()
$resultRedirect = $this->resultRedirectFactory->create();
$customerModel = $this->customerFactory->create();
$blocklistId = $this->getRequest()->getParam('blocklist_id');
$customerId = $this->getRequest()->getParam('customer_id');
$customer = $customerModel->load($customerId);
$customerEmail = $customer->getEmail();
$customerEmail = $this->getRequest()->getParam('email');
$whitelistCurrent = $this->getRequest()->getParam('whitelistValue');
$blocklistCurrent = $this->getRequest()->getParam('blocklistValue');
$listToManage = $this->getRequest()->getParam('list');
Expand Down
16 changes: 16 additions & 0 deletions Helper/DirectQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,20 @@ public function getBayonetIds()

return $result;
}

/**
* Gets the IDs of the rows in the Blocklist table associated to an email
*
* @param string $email
* @return array
*/
public function getBlocklistIds($email)
{
$connection = $this->resourceConnection->getConnection();
$tableName = $connection->getTableName('bayonet_antifraud_blocklist');
$query = $connection->select('distinct')->from($tableName, 'blocklist_id')->where('email = ?', $email);
$result = $connection->fetchCol($query);

return $result;
}
}
54 changes: 40 additions & 14 deletions Model/Config/Backend/KeyValidation.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ public function __construct(
*/
public function beforeSave()
{
$invalidBayonet = [ 12, 13, 15 ];
$invalidJS = [ 12, 15, 16];
$apiKey = $this->getValue();
$label = $this->translateKeyLabel($this->getData('field_config/label'));
$fieldId = $this->getData('field_config/id');
Expand All @@ -61,18 +63,30 @@ public function beforeSave()
$requestBody['auth']['api_key'] = $apiKey;
$response = $this->requestHelper->consulting($requestBody);

// if the response from the API was successful but the code is not
// the one expected, then the API key is not valid and an excepction
// is thrown, otherwise, the process of saving continues.
if (isset($response->reason_code) && (int)$response->reason_code !== 101) {
// if the response from the API was successful and the code is
// the one expected the process of saving continues, otherwise,
// the API key is not valid and an excepction is thrown,
// otherwise, the process of saving continues.
if (isset($response->reason_code) && (int)$response->reason_code === 101) {
$this->setValue(($this->getValue()));
parent::beforeSave();
} elseif (isset($response->reason_code) && (int)$response->reason_code === 12) {
throw new \Magento\Framework\Exception\ValidatorException(__(
'Invalid value for the %1. Please check your key and try again',
$label
));
} elseif (isset($response->reason_code) && (int)$response->reason_code === 101) {
$this->setValue(($this->getValue()));
parent::beforeSave();
} elseif (!isset($response->reason_code)) {
} elseif (isset($response->reason_code) && (int)$response->reason_code === 13) {
throw new \Magento\Framework\Exception\ValidatorException(__(
"%1: Source IP is not valid, please add your IP to the whitelist in Bayonet's console",
$label
));
} elseif (isset($response->reason_code) && (int)$response->reason_code === 15) {
throw new \Magento\Framework\Exception\ValidatorException(__(
"%1: The key you entered has expired, please generate a new key from Bayonet's console",
$label
));
} elseif (!isset($response->reason_code) || (isset($response->reason_code) &&
!in_array((int)$response->reason_code, $invalidBayonet))) {
throw new \Magento\Framework\Exception\ValidatorException(__(
'An error ocurred while validating the %1. Please try again',
$label
Expand All @@ -82,19 +96,31 @@ public function beforeSave()
$requestBody['auth']['jsKey'] = $apiKey;
$response = $this->requestHelper->deviceFingerprint($requestBody);

if (isset($response->reasonCode) && (int)$response->reasonCode !== 51) {
if (isset($response->reasonCode) && (int)$response->reasonCode === 51) {
$this->setValue(($this->getValue()));
parent::beforeSave();
} elseif (isset($response->reasonCode) && (int)$response->reasonCode === 12) {
throw new \Magento\Framework\Exception\ValidatorException(__(
'Invalid value for the %1. Please check your key and try again',
$label
));
} elseif (isset($response->reasonCode) && (int)$response->reasonCode === 51) {
$this->setValue(($this->getValue()));
parent::beforeSave();
} elseif (!isset($response->reasonCode)) {
} elseif (isset($response->reasonCode) && (int)$response->reasonCode === 15) {
throw new \Magento\Framework\Exception\ValidatorException(__(
"%1: The key you entered has expired, please generate a new key from Bayonet's console",
$label
));
} elseif (isset($response->reasonCode) && (int)$response->reasonCode === 16) {
throw new \Magento\Framework\Exception\ValidatorException(__(
"%1: Store domain is not registered, please add your store domain to the whitelist in Bayonet's console",
$label
));
} elseif (!isset($response->reasonCode) || (isset($response->reasonCode) &&
!in_array((int)$response->reasonCode, $invalidJS))) {
throw new \Magento\Framework\Exception\ValidatorException(__(
'An error ocurred while validating the %1. Please try again',
$label
)); }
));
}
}
} elseif (!empty($apiKey) && '**********' === $apiKey) { // when the merchant doesn't modify an existing key
$currentApiKey = $this->getHelper->getConfigValue($fieldId);
Expand Down
22 changes: 10 additions & 12 deletions Observer/OrderPlaced.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public function execute(\Magento\Framework\Event\Observer $observer)
'api_mode' => $apiMode
];

if ($response) {
if (isset($response)) {
$orderData['bayonet_tracking_id'] = (int)$response->reason_code === 0 ?
$response->bayonet_tracking_id :
null;
Expand All @@ -102,7 +102,7 @@ public function execute(\Magento\Framework\Event\Observer $observer)
$bayonetOrder->save();

if (isset($response->decision) && $response->decision === 'decline') {
$this->addBlocklistRows($requestBody['consumer_internal_id'], $requestBody['email']);
$this->addBlocklistRows($requestBody['email']);
throw new \Magento\Framework\Exception\ValidatorException(__(
"There was an error processing your order. Please try again later"
));
Expand All @@ -114,10 +114,10 @@ public function execute(\Magento\Framework\Event\Observer $observer)
$bayonetOrder->save();
}

if (isset($response) && (int)$requestBody['consumer_internal_id']) {
$this->addBlocklistRows($requestBody['consumer_internal_id'], $requestBody['email']);
if (isset($response)) {
$this->addBlocklistRows($requestBody['email']);
}
} catch (Exception $e) {
} catch (\Exception $e) {
return;
}
}
Expand Down Expand Up @@ -149,21 +149,19 @@ protected function getTriggeredRules($response)
}

/**
* Adds a customer to the Bayonet's blocklist table in the database.
* Adds a customer's email to the Bayonet's blocklist table in the database.
* It performs a validation before trying to add them, this to make
* sure the customer is not present in the table yet
* sure the email is not present in the table already
*
* @param string $customerId
* @param string $email
*/
protected function addBlocklistRows($customerId, $email)
protected function addBlocklistRows($email)
{
$bayonetBlocklist = $this->bayonetBlocklistFactory->create();
$blocklistRow = $bayonetBlocklist->load($customerId, 'customer_id');
$blocklistIds = $this->directQuery->getBlocklistIds($email);

if (empty($blocklistRow->getData())) {
if (empty($blocklistIds)) {
$blocklistData = [
'customer_id' => $customerId,
'email' => $email,
'api_mode' => 0
];
Expand Down
6 changes: 0 additions & 6 deletions Setup/InstallSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,6 @@ public function install(SchemaSetupInterface $setup, ModuleContextInterface $con
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Bayonet Blocklist ID'
)->addColumn(
'customer_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['unsigned' => true, 'nullable' => false],
'Customer ID'
)->addColumn(
'email',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
Expand Down
8 changes: 4 additions & 4 deletions Ui/Component/Listing/Column/BlocklistAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function prepareDataSource(array $dataSource)
static::CMS_URL_PATH_BLOCKLIST,
[
'blocklist_id' => $item['blocklist_id'],
'customer_id' => $item['customer_id'],
'email' => $item['email'],
'blocklistValue' => $item['blocklist'],
'whitelistValue' => $item['whitelist'],
'list' => $listToManage,
Expand All @@ -68,11 +68,11 @@ public function prepareDataSource(array $dataSource)
),
'label' => $actionLabel,
'confirm' => [
'title' => __('Customer with ID %1', $item['customer_id']),
'title' => __('Email address %1', $item['email']),
'message' => __(
'Are you sure you want to %1 customer with ID %2?',
'Are you sure you want to %1 the email %2?',
strtolower($actionLabel),
$item['customer_id']
$item['email']
)
],
'post' => true
Expand Down
7 changes: 5 additions & 2 deletions i18n/en_US.csv
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ Added,Added
"This API version is invalid, please try again","This API version is invalid, please try again"
"Cannot enable the module with no pair of API keys saved. Please save a pair of API keys first","Cannot enable the module with no pair of API keys saved. Please save a pair of API keys first"
"Invalid value for the %1. Please check your key and try again","Invalid value for the %1. Please check your key and try again"
"%1: The key you entered has expired, please generate a new key from Bayonet's console","%1: The key you entered has expired, please generate a new key from Bayonet's console"
"%1: Source IP is not valid, please add your IP to the whitelist in Bayonet's console","%1: Source IP is not valid, please add your IP to the whitelist in Bayonet's console"
"%1: Store domain is not registered, please add your store domain to the whitelist in Bayonet's console","%1: Store domain is not registered, please add your store domain to the whitelist in Bayonet's console"
"An error ocurred while validating the %1. Please try again","An error ocurred while validating the %1. Please try again"
"Cannot save an empty live (production) API key when the live (production) mode is enabled","Cannot save an empty live (production) API key when the live (production) mode is enabled"
"Bayonet Sandbox (test) Key","Bayonet Sandbox (test) Key"
Expand All @@ -29,8 +32,8 @@ Added,Added
"Add to Blocklist","Add to Blocklist"
"Remove from Whitelist","Remove from Whitelist"
"Add to Whitelist","Add to Whitelist"
"Customer with ID %1","Customer with ID %1"
"Are you sure you want to %1 customer with ID %2?","Are you sure you want to %1 customer with ID %2?"
"Email address %1","Email address %1"
"Are you sure you want to %1 the email %2?","Are you sure you want to %1 the email %2?"
"View","View"
"Information for Bayonet Anti-Fraud","Information for Bayonet Anti-Fraud"
"Order ID:","Order ID:"
Expand Down
7 changes: 5 additions & 2 deletions i18n/es_ES.csv
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ Added,Agregado
"This API version is invalid, please try again","Esta version del API es invalida, por favor intentalo de nuevo"
"Cannot enable the module with no pair of API keys saved. Please save a pair of API keys first","No se puede habilitar el módulo sin ningun par de llaves de API guardadas. Por favor guarda un par de llaves de API primero"
"Invalid value for the %1. Please check your key and try again","Valor inválido para la %1. Por favor revisa tu llave e intentalo de nuevo"
"%1: The key you entered has expired, please generate a new key from Bayonet's console","%1: La llave que ingresaste ha expirado, por favor genera una nueva llave desde la consola de Bayonet"
"%1: Source IP is not valid, please add your IP to the whitelist in Bayonet's console","%1: La IP de origen no es válida, por favor agrega tu IP a la whitelist en la consola de Bayonet"
"%1: Store domain is not registered, please add your store domain to the whitelist in Bayonet's console","%1: El dominio de la tienda no está registrado, por favor agrega el dominio de tu tienda a la whitelist en la consola de Bayonet"
"An error ocurred while validating the %1. Please try again","Un error ocurrió al validar la %1. Por favor intentalo de nuevo"
"Cannot save an empty live (production) API key when the live (production) mode is enabled","No se puede guardar una llave live (producción) de API vacía cuando el modo live (producción) está habilitado"
"Bayonet Sandbox (test) Key","Llave Sandbox (prueba) de Bayonet"
Expand All @@ -29,8 +32,8 @@ Added,Agregado
"Add to Blocklist","Agregar a la Lista de Bloqueo"
"Remove from Whitelist","Remover de la Lista de Aceptación"
"Add to Whitelist","Agregar a Lista de Aceptación"
"Customer with ID %1","Cliente con ID %1"
"Are you sure you want to %1 customer with ID %2?","Estás seguro de que quieres %1 el cliente con ID %2?"
"Email address %1","Correo electrónico %1"
"Are you sure you want to %1 the email %2?","Estás seguro de que quieres %1 el correo electrónico %2?"
"View","Ver"
"Information for Bayonet Anti-Fraud","Información para Bayonet Anti-Fraud"
"ID of Order:","ID de orden:"
Expand Down
7 changes: 5 additions & 2 deletions i18n/es_MX.csv
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ Added,Agregado
"This API version is invalid, please try again","Esta version del API es invalida, por favor intentalo de nuevo"
"Cannot enable the module with no pair of API keys saved. Please save a pair of API keys first","No se puede habilitar el módulo sin ningun par de llaves de API guardadas. Por favor guarda un par de llaves de API primero"
"Invalid value for the %1. Please check your key and try again","Valor inválido para la %1. Por favor revisa tu llave e intentalo de nuevo"
"%1: The key you entered has expired, please generate a new key from Bayonet's console","%1: La llave que ingresaste ha expirado, por favor genera una nueva llave desde la consola de Bayonet"
"%1: Source IP is not valid, please add your IP to the whitelist in Bayonet's console","%1: La IP de origen no es válida, por favor agrega tu IP a la whitelist en la consola de Bayonet"
"%1: Store domain is not registered, please add your store domain to the whitelist in Bayonet's console","%1: El dominio de la tienda no está registrado, por favor agrega el dominio de tu tienda a la whitelist en la consola de Bayonet"
"An error ocurred while validating the %1. Please try again","Un error ocurrió al validar la %1. Por favor intentalo de nuevo"
"Cannot save an empty live (production) API key when the live (production) mode is enabled","No se puede guardar una llave live (producción) de API vacía cuando el modo live (producción) está habilitado"
"Bayonet Sandbox (test) Key","Llave Sandbox (prueba) de Bayonet"
Expand All @@ -29,8 +32,8 @@ Added,Agregado
"Add to Blocklist","Agregar a la Lista de Bloqueo"
"Remove from Whitelist","Remover de la Lista de Aceptación"
"Add to Whitelist","Agregar a Lista de Aceptación"
"Customer with ID %1","Cliente con ID %1"
"Are you sure you want to %1 customer with ID %2?","Estás seguro de que quieres %1 el cliente con ID %2?"
"Email address %1","Correo electrónico %1"
"Are you sure you want to %1 the email %2?","Estás seguro de que quieres %1 el correo electrónico %2?"
"View","Ver"
"Information for Bayonet Anti-Fraud","Información para Bayonet Anti-Fraud"
"ID of Order:","ID de orden:"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,6 @@
</item>
</argument>
</column>
<column name="customer_id">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">ID of Customer</item>
</item>
</argument>
</column>
<column name="email">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
Expand Down

0 comments on commit bba1092

Please sign in to comment.