diff --git a/cspell.json b/cspell.json
index bfe092ecc..8413cd5f5 100644
--- a/cspell.json
+++ b/cspell.json
@@ -354,7 +354,8 @@
"ordermodel",
"TINYINT",
"hostings",
- "rulesets"
+ "rulesets",
+ "pwreset"
],
"ignorePaths": [
diff --git a/src/modules/Client/Api/Guest.php b/src/modules/Client/Api/Guest.php
index 3b2eb7823..3636cee4f 100644
--- a/src/modules/Client/Api/Guest.php
+++ b/src/modules/Client/Api/Guest.php
@@ -1,4 +1,5 @@
di['events_manager']->fire(['event' => 'onBeforePasswordResetClient']);
- $required = [
- 'email' => 'Email required',
- ];
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+
+ // Validate required parameters
+ $this->di['validator']->checkRequiredParamsForArray(['email' => 'Email required'], $data);
+
+ // Sanitize email
$data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']);
$this->di['events_manager']->fire(['event' => 'onBeforeGuestPasswordResetRequest', 'params' => $data]);
+ // Fetch the client by email
$c = $this->di['db']->findOne('Client', 'email = ?', [$data['email']]);
if (!$c instanceof \Model_Client) {
return true;
}
- $hash = hash('sha256', time() . random_bytes(13));
+ // Check if a password reset request exists
+ $reset = $this->di['db']->findOne('ClientPasswordReset', 'client_id = ?', [$c->id]);
- $reset = $this->di['db']->dispense('ClientPasswordReset');
- $reset->client_id = $c->id;
- $reset->ip = $this->ip;
- $reset->hash = $hash;
- $reset->created_at = date('Y-m-d H:i:s');
+ // If no recent reset request exists, create a new one
+ if (!$reset instanceof \Model_ClientPasswordReset) {
+ $hash = hash('sha256', time() . random_bytes(13));
+ $reset = $this->di['db']->dispense('ClientPasswordReset');
+ $reset->client_id = $c->id;
+ $reset->ip = $this->ip;
+ $reset->hash = $hash;
+ $reset->created_at = date('Y-m-d H:i:s');
+ $reset->updated_at = date('Y-m-d H:i:s');
+ $this->di['db']->store($reset);
+ }
+
+ // prepare reset email
+ $email = [
+ 'to_client' => $c->id,
+ 'code' => 'mod_client_password_reset_request',
+ 'hash' => $reset->hash,
+ 'send_now' => true,
+ ];
+
+ $emailService = $this->di['mod_service']('email');
+
+ // Send the email if the reset request has the same created_at and updated_at or if at least 1 full minute has passed since the last request.
+ if ($reset->created_at == $reset->updated_at) {
+ $emailService->sendTemplate($email);
+ } elseif (strtotime($reset->updated_at) - time() + 60 < 0) {
+ $emailService->sendTemplate($email);
+ }
+
+ // update the client password reset time
$reset->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($reset);
- // send email
- $email = [];
- $email['to_client'] = $c->id;
- $email['code'] = 'mod_client_password_reset_request';
- $email['hash'] = $hash;
- $emailService = $this->di['mod_service']('email');
- $emailService->sendTemplate($email);
-
$this->di['logger']->info('Client requested password reset. Sent to email %s', $c->email);
return true;
}
- /**
- * Confirm password reset action.
- *
- * @return bool
- *
- * @throws \Box_Exception
- */
- public function confirm_reset($data)
+
+ public function update_password($data)
{
$required = [
- 'hash' => 'Hash required',
+ 'hash' => 'No Hash provided',
+ 'password' => 'Password required',
+ 'password_confirm' => 'Password confirmation required',
];
- $this->di['events_manager']->fire(['event' => 'onBeforePasswordResetClient']);
- $this->di['validator']->checkRequiredParamsForArray($required, $data);
+ $this->di['events_manager']->fire(['event' => 'onBeforeClientProfilePasswordReset', 'params' => $data['hash']]);
+
+ $validator = $this->di['validator'];
+ $validator->checkRequiredParamsForArray($required, $data);
+
+ if ($data['password'] != $data['password_confirm']) {
+ throw new \Box_Exception('Passwords do not match');
+ }
$reset = $this->di['db']->findOne('ClientPasswordReset', 'hash = ?', [$data['hash']]);
if (!$reset instanceof \Model_ClientPasswordReset) {
- throw new \Box_Exception('The link have expired or you have already confirmed password reset.');
+ throw new \Box_Exception('The link has expired or you have already reset your password.');
}
- $new_pass = $this->di['tools']->generatePassword();
+ if (strtotime($reset->created_at) - time() + 900 < 0) {
+ throw new \Box_Exception('The link has expired or you have already reset your password.');
+ }
$c = $this->di['db']->getExistingModelById('Client', $reset->client_id, 'Client not found');
- $c->pass = $this->di['password']->hashIt($new_pass);
+ $c->pass = $this->di['password']->hashIt($data['password']);
$this->di['db']->store($c);
+ $this->di['logger']->info('Client requested password reset. Sent to email %s', $c->email);
+
// send email
$email = [];
- $email['to_client'] = $reset->client_id;
- $email['code'] = 'mod_client_password_reset_approve';
- $email['password'] = $new_pass;
+ $email['to_client'] = $c->id;
+ $email['code'] = 'mod_client_password_reset_information';
$emailService = $this->di['mod_service']('email');
$emailService->sendTemplate($email);
$this->di['db']->trash($reset);
- $this->di['logger']->info('Client password reset request was approved');
+ $this->di['events_manager']->fire(['event' => 'onAfterClientProfilePasswordReset', 'params' => ['id' => $c->id]]);
return true;
}
diff --git a/src/modules/Client/Controller/Client.php b/src/modules/Client/Controller/Client.php
index 950b706dd..26d7500c6 100644
--- a/src/modules/Client/Controller/Client.php
+++ b/src/modules/Client/Controller/Client.php
@@ -63,15 +63,21 @@ class Client implements \FOSSBilling\InjectionAwareInterface
return $app->render($template);
}
-
public function get_reset_password_confirm(\Box_App $app, $hash)
{
- $api = $this->di['api_guest'];
+ $service = $this->di['mod_service']('client');
$this->di['events_manager']->fire(['event' => 'onBeforePasswordResetClient']);
$data = [
'hash' => $hash,
];
- $api->client_confirm_reset($data);
- $app->redirect('/login');
+ $template = 'mod_client_set_new_password';
+
+ // Call password_reset_valid function and if true, then render the template, otherwise redirect to the index page
+ $result = $service->password_reset_valid($data);
+ if ($result !== false) {
+ return $app->render($template);
+ } else {
+ $app->redirect('/');
+ }
}
}
diff --git a/src/modules/Client/Service.php b/src/modules/Client/Service.php
index 913f6f892..b65c28c46 100644
--- a/src/modules/Client/Service.php
+++ b/src/modules/Client/Service.php
@@ -1,4 +1,5 @@
di['table_export_csv']('client', 'clients.csv', $headers);
}
+ /**
+ * Confirm password reset action.
+ *
+ * @return bool|int
+ *
+ * @throws \Box_Exception
+ */
+ public function password_reset_valid($data)
+ {
+ $required = [
+ 'hash' => 'Hash required',
+ ];
+ $this->di['events_manager']->fire(['event' => 'onBeforePasswordResetClient']);
+ $this->di['validator']->checkRequiredParamsForArray($required, $data);
+
+ $reset = $this->di['db']->findOne('ClientPasswordReset', 'hash = ?', [$data['hash']]);
+ if (!$reset instanceof \Model_ClientPasswordReset) {
+ throw new \Box_Exception('The link has expired or you have already reset your password.');
+ }
+
+ $c = $this->di['db']->findOne('Client', 'id = ?', [$reset->client_id]);
+ // Return the client ID if the reset request is valid (from within the last 15 minutes), otherwise return false
+ if (strtotime($reset->created_at) - time() + 900 < 0) {
+ return false;
+ } else {
+ return $c->id;
+ }
+ }
+
+ /*
+ * Prunes the `client_password_reset` table of reset requests older than 15 minutes
+ *
+ * @return void
+ */
+ public static function onBeforeAdminCronRun(\Box_Event $event)
+ {
+ $di = $event->getDi();
+ $sql = 'DELETE FROM client_password_reset WHERE UNIX_TIMESTAMP() - 900 > UNIX_TIMESTAMP(created_at);';
+ try {
+ $db = $di['db'];
+ $db->exec($sql);
+ } catch (\Exception $e) {
+ error_log($e->getMessage());
+ }
+ }
}
diff --git a/src/modules/Client/html_client/mod_client_set_new_password.html.twig b/src/modules/Client/html_client/mod_client_set_new_password.html.twig
new file mode 100644
index 000000000..b4d2b696e
--- /dev/null
+++ b/src/modules/Client/html_client/mod_client_set_new_password.html.twig
@@ -0,0 +1,72 @@
+{% extends "layout_public.html.twig" %}
+
+{% block meta_title %}{{ 'Set new Password'|trans }}{% endblock %}
+
+{% block body_class %}page-set-password{% endblock %}
+{% block body %}
+
+
+ {% if settings.login_page_show_logo %}
+
+
+{% endif %}
+
+
+ {% endif %}
+
{{ 'Set new password'|trans }}
+
+
Hello {{ c.first_name }} {{ c.last_name }},
-As you requested, your password for our client area has now been reset.
-Your new login details are as follows:
-Once you have logged in, feel free to go to the edit profile page to change your password to be more memorable.
+The password to your account has been changed.
+If you did not perform this request, please contact your support immediately.
+You may login or edit your profile.
{{ guest.system_company.signature }}
diff --git a/src/modules/Client/html_email/mod_client_password_reset_request.html.twig b/src/modules/Client/html_email/mod_client_password_reset_request.html.twig index 0c6a58197..86c021d59 100644 --- a/src/modules/Client/html_email/mod_client_password_reset_request.html.twig +++ b/src/modules/Client/html_email/mod_client_password_reset_request.html.twig @@ -43,9 +43,7 @@To reset your password, please visit the link below:
Reset password. -Once visiting the link above, you will be emailed a new password that you may login with.
- -You may login or edit your profile. +
You may then login or edit your profile.
{{ guest.system_company.signature }}
diff --git a/tests/modules/Client/Api/GuestTest.php b/tests/modules/Client/Api/GuestTest.php index 10d6359bf..8af426963 100644 --- a/tests/modules/Client/Api/GuestTest.php +++ b/tests/modules/Client/Api/GuestTest.php @@ -4,7 +4,8 @@ namespace Box\Mod\Client\Api; -class GuestTest extends \BBTestCase { +class GuestTest extends \BBTestCase +{ public function testgetDi() { @@ -55,7 +56,9 @@ class GuestTest extends \BBTestCase { $di = new \Pimple\Container(); - $di['mod_config'] = $di->protect(function ($name) use($configArr) { return $configArr; }); + $di['mod_config'] = $di->protect(function ($name) use ($configArr) { + return $configArr; + }); $di['validator'] = $validatorMock; $di['tools'] = $toolsMock; @@ -99,7 +102,9 @@ class GuestTest extends \BBTestCase { $validatorMock->expects($this->atLeastOnce())->method('checkRequiredParamsForArray'); $di = new \Pimple\Container(); - $di['mod_config'] = $di->protect(function ($name) use($configArr) { return $configArr; }); + $di['mod_config'] = $di->protect(function ($name) use ($configArr) { + return $configArr; + }); $di['validator'] = $validatorMock; $toolsMock = $this->getMockBuilder('\FOSSBilling\Tools')->getMock(); @@ -130,7 +135,9 @@ class GuestTest extends \BBTestCase { $client = new \Box\Mod\Client\Api\Guest(); $di = new \Pimple\Container(); - $di['mod_config'] = $di->protect(function ($name) use($configArr) { return $configArr; }); + $di['mod_config'] = $di->protect(function ($name) use ($configArr) { + return $configArr; + }); $client->setDi($di); $this->expectException(\Box_Exception::class); @@ -155,7 +162,9 @@ class GuestTest extends \BBTestCase { $client = new \Box\Mod\Client\Api\Guest(); $di = new \Pimple\Container(); - $di['mod_config'] = $di->protect(function ($name) use($configArr) { return $configArr; }); + $di['mod_config'] = $di->protect(function ($name) use ($configArr) { + return $configArr; + }); $di['validator'] = $validatorMock; $client->setDi($di); @@ -184,8 +193,7 @@ class GuestTest extends \BBTestCase { ->will($this->returnValue(array())); $eventMock = $this->getMockBuilder('\Box_EventManager')->getMock(); - $eventMock->expects($this->atLeastOnce())-> - method('fire'); + $eventMock->expects($this->atLeastOnce())->method('fire'); $sessionMock = $this->getMockBuilder('\FOSSBilling\Session') ->disableOriginalConstructor() @@ -218,40 +226,42 @@ class GuestTest extends \BBTestCase { $this->assertIsArray($results); } - public function testreset_password() + public function testResetPasswordNewFlow() { - $data['email'] = 'Joghn@exmapl.com'; - + $data['email'] = 'John@exmaple.com'; + $eventMock = $this->getMockBuilder('\Box_EventManager')->getMock(); - $eventMock->expects($this->atLeastOnce())-> - method('fire'); - + $eventMock->expects($this->atLeastOnce())->method('fire'); + $modelClient = new \Model_Client(); $modelClient->loadBean(new \DummyBean()); - + $modelPasswordReset = new \Model_ClientPasswordReset(); $modelPasswordReset->loadBean(new \DummyBean()); - + $dbMock = $this->getMockBuilder('\Box_Database')->getMock(); - $dbMock->expects($this->atLeastOnce()) - ->method('findOne')->will($this->returnValue($modelClient)); - $dbMock->expects($this->atLeastOnce()) + + // Specify that 'findOne' will be called exactly twice + $dbMock->expects($this->exactly(2))->method('findOne') + ->willReturnOnConsecutiveCalls($modelClient, null); + + $dbMock->expects($this->once()) ->method('dispense')->will($this->returnValue($modelPasswordReset)); + $dbMock->expects($this->atLeastOnce()) ->method('store')->will($this->returnValue(1)); - - $emailServiceMock = $serviceMock = $this->getMockBuilder('\Box\Mod\Email\Service')->getMock(); - $emailServiceMock->expects($this->atLeastOnce())-> - method('sendTemplate'); - - $validatorMock = $this->getMockBuilder('\FOSSBilling\Validate')->disableOriginalConstructor()->getMock(); - $validatorMock->expects($this->atLeastOnce()) - ->method('checkRequiredParamsForArray') - ->will($this->returnValue(null)); - + + $emailServiceMock = $this->getMockBuilder('\Box\Mod\Email\Service')->getMock(); + $emailServiceMock->expects($this->atLeastOnce())->method('sendTemplate'); + $toolsMock = $this->getMockBuilder('\FOSSBilling\Tools')->getMock(); - $toolsMock->expects($this->atLeastOnce())->method('validateAndSanitizeEmail'); - + $toolsMock->expects($this->once()) + ->method('validateAndSanitizeEmail')->will($this->returnValue($data['email'])); + + $validatorMock = $this->getMockBuilder('\FOSSBilling\Validate')->disableOriginalConstructor()->getMock(); + $validatorMock->expects($this->once()) + ->method('checkRequiredParamsForArray')->will($this->returnValue(null)); + $di = new \Pimple\Container(); $di['db'] = $dbMock; $di['events_manager'] = $eventMock; @@ -259,21 +269,23 @@ class GuestTest extends \BBTestCase { $di['logger'] = new \Box_Log(); $di['tools'] = $toolsMock; $di['validator'] = $validatorMock; - + $client = new \Box\Mod\Client\Api\Guest(); $client->setDi($di); - + $result = $client->reset_password($data); $this->assertTrue($result); } + + + public function testreset_passwordEmailNotFound() { $data['email'] = 'joghn@example.eu'; $eventMock = $this->getMockBuilder('\Box_EventManager')->getMock(); - $eventMock->expects($this->atLeastOnce())-> - method('fire'); + $eventMock->expects($this->atLeastOnce())->method('fire'); $dbMock = $this->getMockBuilder('\Box_Database')->getMock(); $dbMock->expects($this->atLeastOnce()) @@ -300,103 +312,119 @@ class GuestTest extends \BBTestCase { $this->assertTrue($result); } - public function testconfirm_reset() + public function testUpdatePassword() { $data = array( - 'hash' => 'hashedString' + 'hash' => 'hashedString', + 'password' => 'newPassword', + 'password_confirm' => 'newPassword' ); + + // Mocks for dependent services and classes + $dbMock = $this->getMockBuilder('\Box_Database')->getMock(); + $modelClient = new \Model_Client(); $modelClient->loadBean(new \DummyBean()); $modelPasswordReset = new \Model_ClientPasswordReset(); $modelPasswordReset->loadBean(new \DummyBean()); + $modelPasswordReset->created_at = date('Y-m-d H:i:s', time() - 300); // Set timestamp to 5 minutes ago - $dbMock = $this->getMockBuilder('\Box_Database')->getMock(); - $dbMock->expects($this->atLeastOnce()) + $dbMock->expects($this->once()) ->method('findOne')->will($this->returnValue($modelPasswordReset)); - $dbMock->expects($this->atLeastOnce()) + $dbMock->expects($this->once()) ->method('getExistingModelById')->will($this->returnValue($modelClient)); - $dbMock->expects($this->atLeastOnce()) - ->method('store')->will($this->returnValue(1)); + $dbMock->expects($this->once()) + ->method('store'); - $dbMock->expects($this->atLeastOnce()) + $dbMock->expects($this->once()) ->method('trash'); $eventMock = $this->getMockBuilder('\Box_EventManager')->getMock(); - $eventMock->expects($this->atLeastOnce())-> - method('fire'); - - $emailServiceMock = $serviceMock = $this->getMockBuilder('\Box\Mod\Email\Service')->getMock(); - $emailServiceMock->expects($this->atLeastOnce())-> - method('sendTemplate'); + $eventMock->expects($this->exactly(2)) + ->method('fire'); $passwordMock = $this->getMockBuilder('\Box_Password')->getMock(); - $passwordMock->expects($this->atLeastOnce()) + $passwordMock->expects($this->once()) ->method('hashIt'); + $validatorMock = $this->getMockBuilder('\FOSSBilling\Validate')->disableOriginalConstructor()->getMock(); + $validatorMock->expects($this->once()) + ->method('checkRequiredParamsForArray') + ->will($this->returnValue(null)); + + $emailServiceMock = $this->getMockBuilder('\Box\Mod\Email\Service')->getMock(); + $emailServiceMock->expects($this->once()) + ->method('sendTemplate'); + $di = new \Pimple\Container(); $di['db'] = $dbMock; $di['events_manager'] = $eventMock; - $di['logger'] = new \Box_Log(); - $di['mod_service'] = $di->protect(function ($name) use($emailServiceMock) {return $emailServiceMock;}); $di['password'] = $passwordMock; - $validatorMock = $this->getMockBuilder('\FOSSBilling\Validate')->disableOriginalConstructor()->getMock(); - $validatorMock->expects($this->atLeastOnce()) - ->method('checkRequiredParamsForArray') - ->will($this->returnValue(null)); $di['validator'] = $validatorMock; - - $toolsMock = $this->getMockBuilder('\FOSSBilling\Tools')->getMock(); - $toolsMock->expects($this->atLeastOnce())->method('generatePassword'); - $di['tools'] = $toolsMock; + $di['logger'] = new \Box_Log(); + $di['mod_service'] = $di->protect(function ($name) use ($emailServiceMock) { + return $emailServiceMock; + }); $client = new \Box\Mod\Client\Api\Guest(); $client->setDi($di); - $result = $client->confirm_reset($data); + $result = $client->update_password($data); $this->assertTrue($result); } - public function testconfirm_resetResetNotFound() + public function testUpdatePasswordResetNotFound() { $data = array( - 'hash' => 'hashedString' + 'hash' => 'hashedString', + 'password' => 'newPassword', + 'password_confirm' => 'newPassword' ); + // Mock for the database service $dbMock = $this->getMockBuilder('\Box_Database')->getMock(); - $dbMock->expects($this->atLeastOnce()) + $dbMock->expects($this->once()) ->method('findOne')->will($this->returnValue(null)); + // Mock for the events manager $eventMock = $this->getMockBuilder('\Box_EventManager')->getMock(); - $eventMock->expects($this->atLeastOnce())-> - method('fire'); + $eventMock->expects($this->once()) + ->method('fire'); + // Mock for the validator + $validatorMock = $this->getMockBuilder('\FOSSBilling\Validate')->disableOriginalConstructor()->getMock(); + $validatorMock->expects($this->once()) + ->method('checkRequiredParamsForArray') + ->will($this->returnValue(null)); + + // Dependency injection container setup $di = new \Pimple\Container(); $di['db'] = $dbMock; $di['events_manager'] = $eventMock; - $validatorMock = $this->getMockBuilder('\FOSSBilling\Validate')->disableOriginalConstructor()->getMock(); - $validatorMock->expects($this->atLeastOnce()) - ->method('checkRequiredParamsForArray') - ->will($this->returnValue(null)); $di['validator'] = $validatorMock; $client = new \Box\Mod\Client\Api\Guest(); $client->setDi($di); + // Expect a Box_Exception to be thrown with a specific message $this->expectException(\Box_Exception::class); - $this->expectExceptionMessage('The link have expired or you have already confirmed password reset.'); - $client->confirm_reset($data); + $this->expectExceptionMessage('The link has expired or you have already reset your password.'); + $client->update_password($data); } + public function testrequired() { $configArr = array(); $di = new \Pimple\Container(); - $di['mod_config'] = $di->protect(function ($name) use($configArr) { return $configArr; }); + $di['mod_config'] = $di->protect(function ($name) use ($configArr) { + return $configArr; + }); $client = new \Box\Mod\Client\Api\Guest(); $client->setDi($di);