MeChangePasswordController.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Controllers;
  3. use Libs\Payload;
  4. use Libs\Validator;
  5. use Models\UserModel;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. class MeChangePasswordController
  8. {
  9. private UserModel $userModel;
  10. public function __construct()
  11. {
  12. $this->userModel = new UserModel();
  13. }
  14. public function __invoke(ServerRequestInterface $request)
  15. {
  16. $userId = (int) ($request->getAttribute('user_id') ?? 0);
  17. if ($userId <= 0) {
  18. return Payload::fail('Unauthorized: Missing authenticated user', [], 'E_VALIDATE', 401);
  19. }
  20. $body = json_decode((string) $request->getBody(), true) ?: [];
  21. $currentPassword = (string) ($body['currentPassword'] ?? '');
  22. $newPassword = (string) ($body['newPassword'] ?? '');
  23. $confirmPassword = (string) ($body['confirmPassword'] ?? '');
  24. $validator = (new Validator([
  25. 'currentPassword' => $currentPassword,
  26. 'newPassword' => $newPassword,
  27. 'confirmPassword' => $confirmPassword,
  28. ]))
  29. ->required('currentPassword')->minLength('currentPassword', 8)->maxLength('currentPassword', 255)
  30. ->required('newPassword')->minLength('newPassword', 8)->maxLength('newPassword', 255)
  31. ->required('confirmPassword')->minLength('confirmPassword', 8)->maxLength('confirmPassword', 255);
  32. if ($validator->fails()) {
  33. return Payload::fail($validator->firstError() ?? 'Invalid payload', [], 'E_VALIDATE', 400);
  34. }
  35. if ($newPassword !== $confirmPassword) {
  36. return Payload::fail('New password and confirmation do not match', [], 'E_VALIDATE', 400);
  37. }
  38. if ($currentPassword === $newPassword) {
  39. return Payload::fail('New password must be different from current password', [], 'E_VALIDATE', 400);
  40. }
  41. $result = $this->userModel->changePassword($userId, $currentPassword, $newPassword);
  42. if ($result === 'not_found') {
  43. return Payload::fail('User not found', [], 'E_NOT_FOUND', 404);
  44. }
  45. if ($result === 'invalid_current_password') {
  46. return Payload::fail('Current password is invalid', [], 'E_VALIDATE', 400);
  47. }
  48. if ($result === 'error') {
  49. return Payload::fail('Failed to update password', [], 'E_GENERIC', 500);
  50. }
  51. return Payload::ok([], 'S_OK', 'Password updated.');
  52. }
  53. }