Reworked Password-Reset flow (#1627)

* Reworked Password-Reset flow
- No more Passwords sent via E-Mail
- Correct redirects.

* Fixed spelling & last redirect

* Small fixes and updated tests for pw-reset-flow

* Fixed tests for pw-reset-flow

* Fixed tests for the Password reset flow

* Fixed typos, resolved Feedback

* Renamed event before password reset

* Renamed event after password reset

* Tweak a few comments, send the reset email instantly

---------

Co-authored-by: Christoph Schläpfer <c.schlaepfer@datact.ch>
Co-authored-by: Belle Aerni <belleaerni@gmail.com>
This commit is contained in:
authored and GitHub committed 2023-09-22 18:15:18 -07:00
1 parent cba659534c
commit 3ee7f29689
8 files changed
+296 -123

No files matched your search

+2 -1
View File
@@ -354,7 +354,8 @@
"ordermodel",
"TINYINT",
"hostings",
"rulesets"
"rulesets",
"pwreset"
],
"ignorePaths": [
+62 -36
View File
@@ -1,4 +1,5 @@
<?php
/**
* Copyright 2022-2023 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
@@ -150,78 +151,103 @@ class Guest extends \Api_Abstract
public function reset_password($data)
{
$this->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;
}
+10 -4
View File
@@ -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('/');
}
}
}
+46
View File
@@ -1,4 +1,5 @@
<?php
/**
* Copyright 2022-2023 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
@@ -680,4 +681,49 @@ class Service implements InjectionAwareInterface
return $this->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());
}
}
}
@@ -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 %}
<section class="container login" role="main">
{% if settings.login_page_show_logo %}
{% set company = guest.system_company %}
<h1 style="text-align: center">
{% if settings.login_page_show_logo %}
<a href="{{ settings.login_page_logo_url|default('/') }}" target="_blank">
<img src="{{ guest.system_company.logo_url }}" alt="{{ guest.system_company.name }}"/>
</a>
{% endif %}
</h1>
{% endif %}
<h2>{{ 'Set new password'|trans }}</h2>
<div class="data-block">
<div class="data-container">
<form class="api-form" action="{{ 'api/guest/client/update_password'|link }}" method="post" data-api-redirect="{{ '/login'|link }}">
<input type="hidden" name="CSRFToken" value="{{ CSRFToken }}"/>
<input type="hidden" id="hash" name="hash" value="{{ hash }}"/>
<fieldset>
<div class="control-group">
<label class="control-label" for="password">{{ 'New password'|trans }}</label>
<div class="controls">
<input id="password" type="password" placeholder="{{ 'New password'|trans }}" name="password" required="required" value>
<div class="help-block"></div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="password2">{{ 'Repeat new password'|trans }}</label>
<div class="controls">
<input id="password2" type="password" placeholder="{{ 'Repeat new password' | trans }}" name="password_confirm" required="required" value>
<div class="help-block"></div>
</div>
</div>
<div class="form-actions">
<button class="btn btn-block btn-large btn-inverse btn-alt" type="submit">{{ 'Set new password'|trans }}</button>
</div>
</fieldset>
</form>
</div>
</div>
{% if settings.show_password_reset_link or settings.show_signup_link %}
<ul class="login-footer">
{% if settings.show_signup_link%}
<li><a href="{{ 'signup'|link }}"><small>{{ 'Sign Up'|trans }}</small></a></li>
{% endif %}
</ul>
<li><a href="{{ 'login'|link }}"><small>{{ 'Login'|trans }}</small></a></li>
{% endif %}
</section>
{% endblock%}
{% block js %}
<script type="text/javascript">
// Set value of hash field to last part of URL
$(document).ready(function() {
var hash = window.location.href.split('/').pop();
$('#hash').val(hash);
});
</script>
{% endblock %}
@@ -37,13 +37,9 @@
<body>
<h1>Password reset</h1>
<p>Hello {{ c.first_name }} {{ c.last_name }},</p>
<p>As you requested, your password for our client area has now been reset.</p>
<p>Your new login details are as follows:</p>
<ul>
<li><strong>Email:</strong> {{ c.email }}</li>
<li><strong>Password:</strong> {{ password }}</li>
</ul>
<p>Once you have logged in, feel free to go to the edit profile page to change your password to be more memorable.</p>
<p>The password to your account has been changed.</p>
<p>If you did not perform this request, please contact your support immediately.</p>
<p>You may <a href="{{'login'|link({'email' : c.email }) }}" target="_blank">login</a> or <a href="{{'client/profile'|link}}" target="_blank">edit your profile.</a>
<p class="signature">{{ guest.system_company.signature }}</p>
@@ -43,9 +43,7 @@
<p>To reset your password, please visit the link below:</p>
<a href="{{'client/reset-password-confirm'|link}}/{{ hash }}" target="_blank">Reset password.</a>
<p>Once visiting the link above, you will be emailed a new password that you may login with.</p>
<p>You may <a href="{{'login'|link({'email' : c.email }) }}" target="_blank">login</a> or <a href="{{'client/profile'|link}}" target="_blank">edit your profile.</a>
<p>You may then <a href="{{'login'|link({'email' : c.email }) }}" target="_blank">login</a> or <a href="{{'client/profile'|link}}" target="_blank">edit your profile.</a>
<p class="signature">{{ guest.system_company.signature }}</p>
</body>
+100 -72
View File
@@ -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);