user = $user; $this->model = EmailChangeToken::whereUserId($user->id)->first(); return $this; } public function generate(string $newEmail): EmailChangeToken { if ($this->user === null) { throw new LogicException("User不正"); } // 重複チェック if (!$this->checkDuplication($newEmail)) { throw new GeneralErrorMessageException("すでに登録されているEmailです"); } if ($this->model === null) { $this->model = new EmailChangeToken(); } $this->model->user_id = $this->user->id; $this->model->token = Str::uuid(); $this->model->new_email = $newEmail; $this->setExpires(); $this->model->save(); // メール送信 $email = (new ChangeEmailStart($this->model)) ->setEmail($newEmail); $emailManager = new EmailManager($email); $emailManager->confirm(); return $this->model; } public function verify(string $token) { $model = EmailChangeToken::whereToken($token)->firstOrFail(); $user = $model->user; if ($user === null) { throw new LogicException("User不正"); } // 利用者情報の更新 $user->email = $model->new_email; $user->save(); // KINTONE側の更新 $access = Customer::getAccess(); $customer = $access->find($user->kintone_id); $customer->set(Customer::FIELD_EMAIL, $model->new_email); $access->update($customer); // トークン削除 $model->delete(); return $customer; } /** * 重複チェック * * @param string $newEmail * @return boolean */ private function checkDuplication(string $newEmail): bool { return !User::whereEmail($newEmail)->exists() && !EmailChangeToken::whereNewEmail($newEmail)->expiresIn() ->whereNot(EmailChangeToken::COL_NAME_USER_ID, $this->user->id) ->exists(); } private function setExpires() { if ($this->model === null) { throw new LogicException("Model不正"); } $this->model->expires_at = DateUtil::now()->addHours(24); } }