UserChangePasswordController.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\UserModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class UserChangePasswordController
  7. {
  8. public function __invoke(ServerRequestInterface $request)
  9. {
  10. $userId = (int)($request->getAttribute('api_user_id') ?? 0);
  11. if ($userId <= 0) {
  12. return ResponseLib::sendFail('Unauthorized', [], 'E_VALIDATE')->withStatus(401);
  13. }
  14. $body = json_decode((string)$request->getBody(), true) ?? [];
  15. $current = $body['current_password'] ?? '';
  16. $new = $body['new_password'] ?? '';
  17. if ($current === '' || $new === '' || strlen($new) < 8) {
  18. return ResponseLib::sendFail('Validation failed: invalid passwords', [], 'E_VALIDATE')->withStatus(400);
  19. }
  20. if ($current === $new) {
  21. return ResponseLib::sendFail('New password must be different from current password', [], 'E_VALIDATE')->withStatus(400);
  22. }
  23. $model = new UserModel();
  24. $ok = $model->changePassword($userId, $current, $new);
  25. if (!$ok) {
  26. return ResponseLib::sendFail('Invalid current password or update failed', [], 'E_VALIDATE')->withStatus(400);
  27. }
  28. return ResponseLib::sendOk(['user_id' => $userId], 'S_UPDATED');
  29. }
  30. }