/** * Create a new byte service client. * * @param QuestionHelper $questionHelper * @param InputInterface $input * @param OutputInterface $output * @return ByteServiceClient * @throws \UnexpectedValueException when one of the factory techniques * delivers anything but an instance of ByteServiceClient. */ protected function createByteClient(QuestionHelper $questionHelper, InputInterface $input, OutputInterface $output) { if (!$input->getOption('skip-byte-auth')) { $authFile = ByteServiceClient::AUTH_FILE; try { $client = ByteServiceClient::fromAuthFile(); } catch (\Exception $e) { $client = null; } if (isset($client)) { $output->writeln("Using credentials from: <comment>{$authFile}</comment>"); } } if (!isset($client)) { $client = new ByteServiceClient(ByteCredentials::fromQuestionHelper($questionHelper, $input, $output)); } if (!$client instanceof ByteServiceClient) { throw new \UnexpectedValueException('Expected instance of ByteServiceClient!'); } return $client; }
/** * Authenticate the supplied client with the supplied credentials. * * @param Client $client * @param ByteCredentials $credentials * @return Client * @throws \RuntimeException when the client could not authenticate. */ protected function authenticateClient(Client $client, ByteCredentials $credentials) { // Fetch the CSRF middleware token and store it in the cookie jar. $csrfResponse = $client->get('login', ['http_errors' => false]); if (!preg_match('/csrftoken\\=([^\\;]+)\\;/', $csrfResponse->getHeaderLine('Set-Cookie'), $matches)) { throw new \RuntimeException('Did not receive a CSRF token in the cookie headers: ' . $csrfResponse->getHeaderLine('Set-Cookie')); } list(, $token) = $matches; // Log in to byte. $client->post(static::AUTH_ENDPOINT, ['form_params' => ['csrfmiddlewaretoken' => $token, 'username' => $credentials->getUser(), 'password' => $credentials->getPassword()], 'headers' => ['Referer' => static::AUTH_ENDPOINT]]); return $client; }