UserChangePasswordController.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\UserModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Validator as val;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. class UserChangePasswordController
  9. {
  10. private UserModel $model;
  11. public function __construct()
  12. {
  13. $this->model = new UserModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $userId = (int)($request->getAttribute('api_user_id') ?? 0);
  18. if ($userId <= 0) {
  19. return ResponseLib::sendFail('Unauthorized', [], 'E_VALIDATE')->withStatus(401);
  20. }
  21. $body = json_decode((string)$request->getBody(), true) ?? [];
  22. try {
  23. val::key('current_password', val::stringType()->notEmpty())
  24. ->key('new_password', val::stringType()->notEmpty()->length(8, null))
  25. ->assert($body);
  26. } catch (ValidationException $e) {
  27. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  28. }
  29. $current = $body['current_password'];
  30. $new = $body['new_password'];
  31. if ($current === $new) {
  32. return ResponseLib::sendFail('New password must be different from current password', [], 'E_VALIDATE')->withStatus(400);
  33. }
  34. $ok = $this->model->changePassword($userId, $current, $new);
  35. if (!$ok) {
  36. return ResponseLib::sendFail('Invalid current password or update failed', [], 'E_VALIDATE')->withStatus(400);
  37. }
  38. return ResponseLib::sendOk(['user_id' => $userId], 'S_UPDATED');
  39. }
  40. }