LoginProcessor.php 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Webkul\BagistoApi\State;
  3. use ApiPlatform\Metadata\Operation;
  4. use ApiPlatform\State\ProcessorInterface;
  5. use Illuminate\Support\Facades\Event;
  6. use Illuminate\Support\Facades\Hash;
  7. use Illuminate\Support\Str;
  8. use Webkul\BagistoApi\Dto\LoginInput;
  9. use Webkul\BagistoApi\Validators\LoginValidator;
  10. use Webkul\Customer\Models\Customer;
  11. class LoginProcessor implements ProcessorInterface
  12. {
  13. public function __construct(
  14. protected LoginValidator $validator
  15. ) {}
  16. public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
  17. {
  18. if ($data instanceof LoginInput) {
  19. // if ($operation->getName() === 'create') {
  20. $this->validator->validateLoginInput($data);
  21. $customer = Customer::where('email', $data->email)->first();
  22. if (! $customer || ! Hash::check($data->password, $customer->password)) {
  23. return (object) [
  24. 'id' => 0,
  25. '_id' => 0,
  26. 'apiToken' => '',
  27. 'token' => '',
  28. 'success' => false,
  29. 'message' => __('bagistoapi::app.graphql.login.invalid-credentials'),
  30. ];
  31. }
  32. if ($customer->is_suspended) {
  33. return (object) [
  34. 'id' => 0,
  35. '_id' => 0,
  36. 'apiToken' => '',
  37. 'token' => '',
  38. 'success' => false,
  39. 'message' => __('bagistoapi::app.graphql.login.account-suspended'),
  40. ];
  41. }
  42. if (empty($customer->api_token)) {
  43. $customer->api_token = Str::random(80);
  44. $customer->save();
  45. }
  46. // Dispatch event to save device_token - PushNotification package will handle this
  47. $deviceToken = $data->deviceToken ?? null;
  48. if ($deviceToken) {
  49. Event::dispatch('bagistoapi.customer.device-token.save', [
  50. 'customerId' => $customer->id,
  51. 'deviceToken' => $deviceToken,
  52. ]);
  53. }
  54. // Dispatch customer login event for reward points and other listeners
  55. Event::dispatch('customer.after.login', $customer);
  56. $token = $customer->createToken('customer-login')->plainTextToken;
  57. return (object) [
  58. 'id' => $customer->id,
  59. '_id' => $customer->id,
  60. 'apiToken' => $customer->api_token,
  61. 'token' => $token,
  62. 'success' => true,
  63. 'message' => __('bagistoapi::app.graphql.login.successful'),
  64. ];
  65. // }
  66. }
  67. return (object) [
  68. 'id' => 0,
  69. '_id' => 0,
  70. 'apiToken' => '',
  71. 'token' => '',
  72. 'success' => false,
  73. 'message' => __('bagistoapi::app.graphql.login.invalid-request'),
  74. ];
  75. }
  76. }