Add change-password endpoint to user security routes
- Introduced `/account/security/change-password` route to handle password updates. - Enforced user login and required parameters (`current_password`, `new_password`) for validation. - Added password validation logic, including constraints on old and new password similarities. - Integrated logging and detailed error handling for invalid sessions, passwords, and operations. - Updated user model to support secure password changes.
This commit is contained in:
@@ -80,5 +80,45 @@ class userSecurityRoute
|
||||
'user_security_validate_password' => 'Validate the password of the user',
|
||||
]
|
||||
);
|
||||
|
||||
$this->post('/account/security/change-password', function () {
|
||||
// Require the user to be logged in
|
||||
global $response;
|
||||
self::requirePermission('user_security_change_password');
|
||||
$user = (new authentication())->get_user();
|
||||
if (!$user) {
|
||||
(new logs_o())->add('user_security', 'global', 0, 0, 'USER_SECURITY_CHANGE_PASSWORD', 'User not logged in');
|
||||
$response->error('Invalid session', 400);
|
||||
}
|
||||
// Require the current_password and new_password parameters
|
||||
self::requireParameters(['current_password', 'new_password']);
|
||||
// Validate the old password
|
||||
$current_password = (string)self::getParameter('current_password');
|
||||
self::requireMinLength('current_password', 4);
|
||||
self::requireMaxLength('current_password', 255);
|
||||
self::requireType($current_password, self::type_string());
|
||||
if (!$user->passwordMatches($current_password)) {
|
||||
(new logs_o())->add('user_security', 'global', 0, $user->id, 'USER_SECURITY_CHANGE_PASSWORD', 'Invalid old password');
|
||||
$response->error('Invalid old password', 400);
|
||||
}
|
||||
// Validate the new password
|
||||
$new_password = (string)self::getParameter('new_password');
|
||||
self::requireMinLength('new_password', 4);
|
||||
self::requireMaxLength('new_password', 255);
|
||||
self::requireType($new_password, self::type_string());
|
||||
if ($current_password === $new_password) {
|
||||
(new logs_o())->add('user_security', 'global', 0, $user->id, 'USER_SECURITY_CHANGE_PASSWORD', 'New password cannot be the same as the old password');
|
||||
$response->error('New password cannot be the same as the old password', 400);
|
||||
} else {
|
||||
// Change the password
|
||||
$user->setPassword($new_password);
|
||||
(new logs_o())->add('user_security', 'global', 0, $user->id, 'USER_SECURITY_CHANGE_PASSWORD', 'Password changed');
|
||||
$response->success(['message' => 'Password changed']);
|
||||
}
|
||||
},
|
||||
[
|
||||
'user_security_change_password' => 'Change the password of the user',
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user