Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

110 řádky
2.8KB

  1. <?php
  2. namespace App\Logic;
  3. use App\Email\Guests\ChangeEmailStart;
  4. use App\Exceptions\GeneralErrorMessageException;
  5. use App\Features\InstanceAble;
  6. use App\Kintone\Models\Customer;
  7. use App\Models\EmailChangeToken;
  8. use App\Models\Feature\UserId;
  9. use App\Models\User;
  10. use App\Util\DateUtil;
  11. use Illuminate\Support\Str;
  12. use LogicException;
  13. class EmailChangeManager
  14. {
  15. use InstanceAble, UserId;
  16. private ?User $user = null;
  17. private ?EmailChangeToken $model = null;
  18. public function setUser(User $user): static
  19. {
  20. $this->user = $user;
  21. $this->model = EmailChangeToken::whereUserId($user->id)->first();
  22. return $this;
  23. }
  24. public function generate(string $newEmail): EmailChangeToken
  25. {
  26. if ($this->user === null) {
  27. throw new LogicException("User不正");
  28. }
  29. // 重複チェック
  30. if (!$this->checkDuplication($newEmail)) {
  31. throw new GeneralErrorMessageException("すでに登録されているEmailです");
  32. }
  33. if ($this->model === null) {
  34. $this->model = new EmailChangeToken();
  35. }
  36. $this->model->user_id = $this->user->id;
  37. $this->model->token = Str::uuid();
  38. $this->model->new_email = $newEmail;
  39. $this->setExpires();
  40. $this->model->save();
  41. // メール送信
  42. $email = (new ChangeEmailStart($this->model))
  43. ->setEmail($newEmail);
  44. $emailManager = new EmailManager($email);
  45. $emailManager->confirm();
  46. return $this->model;
  47. }
  48. public function verify(string $token)
  49. {
  50. $model = EmailChangeToken::whereToken($token)->firstOrFail();
  51. $user = $model->user;
  52. if ($user === null) {
  53. throw new LogicException("User不正");
  54. }
  55. // 利用者情報の更新
  56. $user->email = $model->new_email;
  57. $user->save();
  58. // KINTONE側の更新
  59. $access = Customer::getAccess();
  60. $customer = $access->find($user->kintone_id);
  61. $customer->set(Customer::FIELD_EMAIL, $model->new_email);
  62. $access->update($customer);
  63. // トークン削除
  64. $model->delete();
  65. return $customer;
  66. }
  67. /**
  68. * 重複チェック
  69. *
  70. * @param string $newEmail
  71. * @return boolean
  72. */
  73. private function checkDuplication(string $newEmail): bool
  74. {
  75. return !User::whereEmail($newEmail)->exists() &&
  76. !EmailChangeToken::whereNewEmail($newEmail)->expiresIn()
  77. ->whereNot(EmailChangeToken::COL_NAME_USER_ID, $this->user->id)
  78. ->exists();
  79. }
  80. private function setExpires()
  81. {
  82. if ($this->model === null) {
  83. throw new LogicException("Model不正");
  84. }
  85. $this->model->expires_at = DateUtil::now()->addHours(24);
  86. }
  87. }