all(); if (! empty($requestData['token'])) { $data = request()->validate([ 'token' => 'required|string', 'email' => 'sometimes', 'password' => 'sometimes', ]); } else { $data = request()->validate([ 'email' => 'required|email', 'password' => 'required|string', ]); } $token = null; // Path 1: validate an existing bearer token. if (! empty($data['token']) && $this->sanctumAvailable()) { $tokenable = optional(\Laravel\Sanctum\PersonalAccessToken::findToken($data['token']))->tokenable; if ($tokenable) { Auth::login($tokenable); $token = $data['token']; } } // Path 2: email + password → new token. if (! Auth::check() && isset($data['email'], $data['password']) && Auth::attempt($data)) { $user = Auth::user(); if (method_exists($user, 'createToken')) { $token = explode('|', $user->createToken('authtoken')->plainTextToken)[1] ?? null; } } if (! Auth::check()) { return $this->error(__('shop::auth.invalid_credentials')); } $user = Auth::user(); $this->seedSocketAuthCache(); $this->mergeGuestCart($user); return $this->success([ 'message' => __('shop::auth.login_ok'), 'user' => $user, 'token' => $token, ]); } public function me() { $token = request('authtoken') ?? request('token'); if ($token && ! Auth::check() && $this->sanctumAvailable()) { $tokenable = optional(\Laravel\Sanctum\PersonalAccessToken::findToken($token))->tokenable; if ($tokenable) { Auth::login($tokenable); } } if (Auth::check()) { $this->seedSocketAuthCache(); } return $this->success(['user' => Auth::user()]); } /** * Merge this connection's guest cart into the just-authenticated user's cart. */ protected function mergeGuestCart($user): void { try { $guest = CartFacade::guest($this->connection->socketId); CartFacade::mergeGuestIntoUser($guest, $user); } catch (\Throwable) { // A cart merge must never block login. } } /** * Cache {id,type} under socket_ so subsequent need_auth controllers on * this connection can resolve the user without another token round-trip. */ protected function seedSocketAuthCache(): void { $key = 'socket_' . $this->connection->socketId; cache()->forget($key); cache()->remember($key, 60 * 15, fn () => [ 'id' => Auth::id(), 'type' => Auth::user() ? get_class(Auth::user()) : null, ]); } protected function sanctumAvailable(): bool { return class_exists(\Laravel\Sanctum\PersonalAccessToken::class); } }