| @@ -2,8 +2,10 @@ | ||
| 2 | 2 | |
| 3 | 3 | namespace FluentCart\App\Services; |
| 4 | 4 | |
| 5 | 5 | use FluentCart\App\Models\Customer; |
| 6 | +use FluentCart\Api\Resource\CustomerResource; | |
| 7 | +use FluentCart\App\Services\CustomerIdentity\EmailVerificationService; | |
| 6 | 8 | |
| 7 | 9 | class AuthService |
| 8 | 10 | { |
| 9 | 11 | |
| @@ -10,18 +12,41 @@ | ||
| 10 | 12 | public static function createUserFromCustomer(Customer $customer, $sendUserEmail = true, $userRole = '') |
| 11 | 13 | { |
| 12 | 14 | $userName = self::createUserNameFromStrings($customer->email, [$customer->first_name, $customer->last_name]); |
| 13 | 15 | |
| 14 | - return self::registerNewUser( | |
| 15 | - $userName, | |
| 16 | - $customer->email, | |
| 17 | - '', | |
| 18 | - [ | |
| 16 | + // With verification not required, link the account to its customer before | |
| 17 | + // other registration listeners run. The update never takes a customer | |
| 18 | + // another account owns, nor one whose stored email changed meanwhile; | |
| 19 | + // an unlinked one is linked on the first portal visit. | |
| 20 | + $link = function ($userId) use ($customer) { | |
| 21 | + $user = get_userdata($userId); | |
| 22 | + if ($user && EmailVerificationService::isSame($user->user_email, $customer->email)) { | |
| 23 | + $linked = Customer::query()->where('id', $customer->id)->unclaimed() | |
| 24 | + ->whereRaw('LOWER(TRIM(email)) = ?', [EmailVerificationService::normalize($user->user_email)]) | |
| 25 | + ->update(['user_id' => (int) $userId]); | |
| 26 | + if ($linked) { | |
| 27 | + $customer->refresh(); | |
| 28 | + } | |
| 29 | + CustomerResource::resetCurrentCustomerRuntimeCache(); | |
| 30 | + } | |
| 31 | + }; | |
| 32 | + | |
| 33 | + $linkCustomer = !EmailVerificationService::isEnabled(); | |
| 34 | + if ($linkCustomer) { | |
| 35 | + add_action('user_register', $link, PHP_INT_MIN, 1); | |
| 36 | + } | |
| 37 | + | |
| 38 | + try { | |
| 39 | + return self::registerNewUser($userName, $customer->email, '', [ | |
| 19 | 40 | 'first_name' => $customer->first_name, |
| 20 | 41 | 'last_name' => $customer->last_name, |
| 21 | 42 | 'role' => $userRole |
| 22 | - ] | |
| 23 | - ); | |
| 43 | + ]); | |
| 44 | + } finally { | |
| 45 | + if ($linkCustomer) { | |
| 46 | + remove_action('user_register', $link, PHP_INT_MIN); | |
| 47 | + } | |
| 48 | + } | |
| 24 | 49 | } |
| 25 | 50 | |
| 26 | 51 | public static function registerNewUser($user_login, $user_email, $user_pass = '', $extraData = []) |
| 27 | 52 | { |