protected function getCustomer() { $api = new Api(); Customer::instance()->closeIfNotMember(); // ключ из запроса $keyRequest = Input::get('key'); // наш ключ клиента $keyCustomer = Customer::instance()->key(); // id сессии агбиса $keyAgbis = $api->key(); // при наличии нашего ключа плюс ключа агбиса // это значит что мы держим вполне живую сессию if ($keyCustomer && $keyAgbis) { $customer = Customer::instance()->initByKey(); Reporter::customerTouchKey($keyCustomer, $keyAgbis, $customer->get()->agbis_id); return $customer; } Reporter::customerEmptyKey($keyCustomer, $keyAgbis); // нет своего ключа но есть ключ агбис или ключ запроса (он же ключ агбис) // это значит что свой ключ мы еще не выдали по какой то причине // поэтому работаем по ключу агбиса (из запроса - приоритетнее) Reporter::customerTouchExternalKey($keyRequest, $keyAgbis); $keyAgbis = $keyRequest ? $keyRequest : $keyAgbis; if ($keyAgbis) { try { $user = $api->_cache_customer_info($keyAgbis); $api->memory((object) ['id' => $user['id'], 'key' => $keyAgbis]); // получили человека по агбису, найдем его у нас и создадим свою сессию $customer = Customer::instance()->initByExternalId($user['id']); if ($customer) { $key = $customer->startSession(); Reporter::loginNewKey($customer->get()->agbis_id, $key); return $customer; } // иначе это значит, что в нашей базе пользователя нет // придется его выбросить и пусть авторизуется заново Reporter::customerLostExternalKey($keyAgbis); } catch (ApiException $e) { Reporter::customerFailExternalKey($keyAgbis); } } else { Reporter::customerEmptyExternalKey(); } Customer::instance()->destroySession(); return null; }
/** * авторизация * @return \Response */ public function login() { Validation::prepareInput(['phone']); $phone = \Input::get('phone'); $password = \Input::get('password'); $selfPassword = null; $validator = Validation::validator(['phone', 'password']); if ($validator->fails()) { Reporter::loginFailValidate($validator); return $this->responseError($validator, 'Некорректные данные'); } Reporter::loginStart($phone, $password); // ключ который мы должны в итоге выдать фронтенду $key = null; // находим у себя $customer = Customer::instance()->initByPhone($phone); if ($customer) { Reporter::loginFoundSelf($customer->get()->agbis_id); // авторизуем по своему паролю if ($customer->checkPassword($password)) { Reporter::loginPasswordSelf($customer->get()->agbis_id); // наш пароль $selfPassword = $password; // в агбис будем входить по внешнему паролю $password = $customer->getExternalPassword(); } } // получаем сессию агбиса try { $api = new Api(); $user = $api->Login_con($phone, $password); $api->memory($user); // запомним отдельно в сессии api if (Input::get('remember')) { $cookie = Customer::instance()->getForeverCookie(); } else { $cookie = Customer::instance()->getTemporaryCookie(); } Reporter::loginExternal($user->id, $phone); // для нас - новый человек if (!$customer) { // пробуем найти по id агбиса $customer = Customer::instance()->initByExternalId($user->id); if ($customer) { // если нашли, это значит изменился телефон, обновим всю информацию $customer->updateCustomerByExternal($phone, $password); } else { // создадим нового $customer = Customer::instance()->createCustomerByExternal($user->id, $phone, $password); } } // устанавливаем пароль в соответствии с успешным входом $customer->doChangePasswordSoft($password, $selfPassword); // по итогу, у нас есть "наш" человек // и мы начинам свою сессию $key = $customer->startSession(); Reporter::loginNewKey($customer->get()->id, $key); $invite = new InviteComponent(); $invite->registerInvite($customer->get()); // обновляем дату-время последнего входа $customer->renewRegisterAt(); // и именно наш ключ отдаем клиенту $response = $this->responseSuccess(['key' => $key], 'Успешная авторизация')->withCookie($cookie); return $response; } catch (\Exception $e) { Reporter::loginFailException($e); return $this->responseException($e, 'Ошибка авторизации', null, 401); } }