예제 #1
1
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     if (file_exists($this->getFullFilePath($request))) {
         $responsedata = file_get_contents($this->getFullFilePath($request));
         $mf = new MessageFactory();
         $event->intercept($mf->fromMessage($responsedata));
     }
 }
 public function addAuthHeaders(BeforeEvent $event)
 {
     /*
      * Get Consumer ID and Private Key from auth and then unset it
      */
     $auth = $event->getClient()->getDefaultOption('auth');
     if ($auth === null) {
         throw new \Exception('Http client is missing \'auth\' parameters', 1466965269);
     }
     $consumerId = $auth[0];
     $privateKey = $auth[1];
     $event->getClient()->setDefaultOption('auth', null);
     /*
      * Get Request URL, method, and timestamp to calculate signature
      */
     $requestUrl = $event->getRequest()->getUrl();
     //decode url back to normal to nextCursor issue. automatic url encoding
     $requestUrl = rawurldecode($requestUrl);
     $event->getRequest()->setUrl($requestUrl);
     $requestMethod = $event->getRequest()->getMethod();
     $timestamp = Utils::getMilliseconds();
     $signature = Signature::calculateSignature($consumerId, $privateKey, $requestUrl, $requestMethod, $timestamp);
     /*
      * Add required headers to request
      */
     $headers = ['WM_SVC.NAME' => 'Walmart Marketplace', 'WM_QOS.CORRELATION_ID' => base64_encode(Random::string(16)), 'WM_SEC.TIMESTAMP' => $timestamp, 'WM_SEC.AUTH_SIGNATURE' => $signature, 'WM_CONSUMER.ID' => $consumerId];
     $currentHeaders = $event->getRequest()->getHeaders();
     unset($currentHeaders['Authorization']);
     $updatedHeaders = array_merge($currentHeaders, $headers);
     $event->getRequest()->setHeaders($updatedHeaders);
 }
예제 #3
0
파일: Mock.php 프로젝트: 453111208/bbc
 /**
  * @throws \OutOfBoundsException|\Exception
  */
 public function onBefore(BeforeEvent $event)
 {
     if (!($item = array_shift($this->queue))) {
         throw new \OutOfBoundsException('Mock queue is empty');
     } elseif ($item instanceof RequestException) {
         throw $item;
     }
     // Emulate reading a response body
     $request = $event->getRequest();
     if ($this->readBodies && $request->getBody()) {
         while (!$request->getBody()->eof()) {
             $request->getBody()->read(8096);
         }
     }
     $saveTo = $event->getRequest()->getConfig()->get('save_to');
     if (null !== $saveTo) {
         $body = $item->getBody();
         if (is_resource($saveTo)) {
             fwrite($saveTo, $body);
         } elseif (is_string($saveTo)) {
             file_put_contents($saveTo, $body);
         } elseif ($saveTo instanceof StreamInterface) {
             $saveTo->write($body);
         }
     }
     $event->intercept($item);
 }
 public function sign(BeforeEvent $e)
 {
     $method = $e->getRequest()->getMethod();
     if (preg_match('/post|put|delete/i', $method)) {
         $e->getRequest()->setHeader('X-Insta-Forwarded-For', join('|', array($this->ip_address, hash_hmac('SHA256', $this->ip_address, $this->client_secret))));
     }
     // var_dump($e->getRequest()->getHeaders());
 }
 /**
  * Check if the requested authentication type matches and set the
  * required X-Token and X-Signature headers
  *
  * @param BeforeEvent $event
  */
 public function sign(BeforeEvent $event)
 {
     if ($event->getRequest()->getConfig()['auth'] == 'tevoauth') {
         $request = $event->getRequest();
         $request->setHeader('X-Token', $this->_apiToken);
         $request->setHeader('X-Signature', $this->getSignature($request));
     }
 }
예제 #6
0
 public function auth(BeforeEvent $event, $name)
 {
     $cfg = $event->getRequest()->getConfig()['auth'];
     $request = $event->getRequest();
     if ($cfg == 'basic') {
         call_user_func_array([$this, 'basic' . ucfirst($this->_class) . 'Auth'], [$request]);
     }
 }
예제 #7
0
 public function auth(BeforeEvent $event, $name)
 {
     $cfg = $event->getRequest()->getConfig()['auth'];
     $request = $event->getRequest();
     if ($cfg == 'basic') {
         //add the token to the query field
         $request->setQuery((string) $request->getQuery() . '&access_token=' . $this->service->getAppId() . '|' . $this->service->getAppSecret());
     }
 }
예제 #8
0
 /**
  * The onBefore event that will add the hmac errors to the request headers
  *
  * @param BeforeEvent $event
  */
 public function onBefore(BeforeEvent $event)
 {
     if ($event !== null && $event->getRequest() !== null) {
         $hmac = (new Manager($this->adapter))->key($this->key)->data($this->data)->time($this->time)->encode()->getHmac();
         $event->getRequest()->setHeader($this->headerNames['hmac'], $hmac->getHmac());
         $event->getRequest()->setHeader($this->headerNames['data'], $hmac->getData());
         $event->getRequest()->setHeader($this->headerNames['time'], $hmac->getTime());
     }
 }
예제 #9
0
 public function onBefore(BeforeEvent $event)
 {
     $body = $event->getRequest()->getBody();
     // Only works when there is a body with a known size.
     if (!$body || !$body->getSize()) {
         return;
     }
     // Wrap the existing request body in an upload decorator.
     $progressBody = new UploadProgressStream($body, $this->uploadProgress, $event->getClient(), $event->getRequest());
     $event->getRequest()->setBody($progressBody);
 }
예제 #10
0
 public function onBefore(BeforeEvent $event)
 {
     if (!$this->loggedIn || !is_null($this->expires) && time() > $this->expires) {
         $details = $this->logIn();
         $this->query = $details['query'];
         $this->headers = $details['headers'];
     }
     $event->getRequest()->getQuery()->merge($this->query);
     $head = $event->getRequest()->getHeaders();
     $event->getRequest()->setHeaders(array_replace($head, $this->headers));
 }
예제 #11
0
 public function Auth(BeforeEvent $event, $name)
 {
     $cfg = $event->getRequest()->getConfig()['auth'];
     if ($cfg == 'basic') {
         $basic = base64_encode($this->service->getAppId() . ':' . $this->service->getAppSecret());
         $event->getRequest()->setHeaders(['Authorization' => 'Basic ' . $basic]);
     } else {
         if ($cfg == 'bearer') {
             $event->getRequest()->setHeaders(['Authorization' => 'Bearer ' . $this->service->getAccessToken()]);
         }
     }
 }
 /**
  * Updates the request with an Authorization header when auth is 'fetched_auth_token'.
  *
  *   use GuzzleHttp\Client;
  *   use Google\Auth\OAuth2;
  *   use Google\Auth\AuthTokenFetcher;
  *
  *   $config = [..<oauth config param>.];
  *   $oauth2 = new OAuth2($config)
  *   $scoped = new AuthTokenFetcher($oauth2,
  *                                  $cache = new Memcache(),
  *                                  [ 'prefix' => 'OAuth2::' ]);
  *   $client = new Client([
  *      'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
  *      'defaults' => ['auth' => 'google_auth']
  *   ]);
  *
  *   $res = $client->('myproject/taskqueues/myqueue');
  */
 public function onBefore(BeforeEvent $event)
 {
     // Requests using "auth"="google_auth" will be authorized.
     $request = $event->getRequest();
     if ($request->getConfig()['auth'] != 'google_auth') {
         return;
     }
     // Use the cached value if its available.
     //
     // TODO: correct caching; update the call to setCachedValue to set the expiry
     // to the value returned with the auth token.
     //
     // TODO: correct caching; enable the cache to be cleared.
     $cached = $this->getCachedValue();
     if (!is_null($cached)) {
         $request->setHeader('Authorization', 'Bearer ' . $cached);
         return;
     }
     // Fetch the auth token.
     $auth_tokens = $this->fetcher->fetchAuthToken();
     if (array_key_exists('access_token', $auth_tokens)) {
         $request->setHeader('Authorization', 'Bearer ' . $auth_tokens['access_token']);
         $this->setCachedValue($auth_tokens['access_token']);
     }
 }
예제 #13
0
 /**
  * @param BeforeEvent $event
  */
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     $span = $this->guzzleMessageSpanFactory->fromOutgoingRequest($request);
     $this->tracer->trace([$span]);
     $request->addHeaders(['X-B3-SpanId' => (string) $span->getIdentifier(), 'X-B3-TraceId' => (string) $span->getTraceIdentifier(), 'X-B3-ParentSpanId' => (string) $span->getParentIdentifier(), 'X-B3-Flags' => $span->getDebug() ? '1' : '0']);
 }
예제 #14
0
 /**
  * @param BeforeEvent $event
  */
 public function onBefore(BeforeEvent $event)
 {
     if ($this->logger) {
         $request = $event->getRequest();
         $this->logger->info($this->formatMessage($request->getMethod(), $request->getUrl()), ['requestHeaders' => $request->getHeaders(), 'requestBody' => (string) $request->getBody()]);
     }
 }
예제 #15
0
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     if (isset(self::$purgeMethods[$request->getMethod()])) {
         $this->storage->purge($request);
     }
 }
 /**
  * Signs an API request using an authentication flow.
  *
  * @param BeforeEvent $event
  */
 public function sign(BeforeEvent $event)
 {
     $request = $event->getRequest();
     if ($request->getMethod() === 'GET') {
         $this->authenticateGetRequest($request);
     }
 }
 /**
  * Request before-send event handler.
  *
  * Adds the Authorization header if an access token was found.
  *
  * @param BeforeEvent $event Event received
  */
 public function onBefore(BeforeEvent $event)
 {
     $this->checkTokenData();
     if ($this->tokenData->accessToken) {
         $this->accessTokenSigner->sign($event->getRequest(), $this->tokenData->accessToken);
     }
 }
예제 #18
0
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     $this->context->signer()->sign(new Message($request));
     $headers = new MessageHeaders($request);
     $headers->set("Authorization", $headers->get("Signature"));
     $request->removeHeader("Signature");
 }
예제 #19
0
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     if (!($response = $this->cache->fetch($request->__toString()))) {
         return;
     }
     $event->intercept($response);
 }
 /**
  * Add WSSE auth headers
  *
  * @param Event $event
  */
 public function onRequestCreate(\GuzzleHttp\Event\BeforeEvent $event)
 {
     $request = $event->getRequest();
     $nonce = call_user_func($this->noncer);
     $created = date('r');
     $digest = call_user_func($this->digester, $nonce, $created, $this->password);
     $request->addHeaders(array("Authorization" => "WSSE profile=\"UsernameToken\"", "X-WSSE" => "UsernameToken Username=\"{$this->username}\", PasswordDigest=\"{$digest}\", Nonce=\"{$nonce}\", Created=\"{$created}\""));
 }
 /**
  * Updates the request query with the developer key if auth is set to simple.
  *
  *   use Google\Auth\Subscriber\SimpleSubscriber;
  *   use GuzzleHttp\Client;
  *
  *   $my_key = 'is not the same as yours';
  *   $subscriber = new SimpleSubscriber(['key' => $my_key]);
  *
  *   $client = new Client([
  *      'base_url' => 'https://www.googleapis.com/discovery/v1/',
  *      'defaults' => ['auth' => 'simple']
  *   ]);
  *   $client->getEmitter()->attach($subscriber);
  *
  *   $res = $client->get('drive/v2/rest');
  *
  * @param BeforeEvent $event
  */
 public function onBefore(BeforeEvent $event)
 {
     // Requests using "auth"="simple" with the developer key.
     $request = $event->getRequest();
     if ($request->getConfig()['auth'] != 'simple') {
         return;
     }
     $request->getQuery()->overwriteWith($this->config);
 }
예제 #22
0
 public function onRequestBeforeSend(BeforeEvent $event)
 {
     // Skip by default
     if (null === $this->method) {
         return;
     }
     $request = $event->getRequest();
     switch ($this->method) {
         case Client::AUTH_URL_TOKEN:
             $url = $event->getRequest()->getUrl();
             $url .= false === strpos($url, '?') ? '?' : '&';
             $url .= utf8_encode(http_build_query(array('token' => $this->token), '', '&'));
             $event->getRequest()->setUrl($url);
             break;
         default:
             throw new RuntimeException(sprintf('%s not yet implemented', $this->method), $request);
             break;
     }
 }
예제 #23
0
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     try {
         $response = $this->makeRequest($request);
         $event->intercept($response);
     } catch (HttpMockException $error) {
         $this->fail($error, $event);
     }
 }
 /**
  * Add the Authorization header to requests.
  *
  * @param BeforeEvent $event Event received
  */
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     if ($request->getConfig()->get('auth') == 'oauth2') {
         $token = $this->getAccessToken();
         if ($token !== null) {
             $request->setHeader('Authorization', 'Bearer ' . $token->getToken());
         }
     }
 }
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     if (isset(self::$purgeMethods[$request->getMethod()])) {
         $this->storage->purge($request->getUrl());
         if ('PURGE' === $request->getMethod()) {
             $event->intercept(new Response(204));
         }
     }
 }
예제 #26
0
 /**
  * Guzzle event used to set the key parameter.
  *
  * @codeCoverageIgnore
  *
  * @param BeforeEvent $event
  */
 private function getBeforeEvent(BeforeEvent $event)
 {
     $request = $event->getRequest();
     if ('api.embed.ly' === $request->getHost()) {
         $requestQuery = $request->getQuery();
         $requestQuery->setEncodingType(false);
         $requestQuery->set('key', $this->apiKey);
         $request->setQuery($requestQuery);
     }
 }
예제 #27
0
 public function onBefore(BeforeEvent $event)
 {
     $request = $event->getRequest();
     $config = $request->getConfig();
     // So that we do not attach subscribers multiple times.
     if (isset($config['applied_message_integrity'])) {
         return;
     }
     $config['applied_message_integrity'] = true;
     $request->getEmitter()->attach($config['stream'] ? $this->streaming : $this->full);
 }
예제 #28
0
 /**
  * This method is invoked before every HTTP request is sent to the API. When this happens, it
  * checks to see whether a token is set and valid, and then sets the ``X-Auth-Token`` header
  * for the HTTP request before letting it continue on its merry way.
  *
  * @param BeforeEvent $event
  *
  * @return mixed|void
  */
 public function checkTokenIsValid(BeforeEvent $event)
 {
     $request = $event->getRequest();
     if ($this->shouldIgnore($request)) {
         return;
     }
     if (!$this->token || $this->token->hasExpired()) {
         $this->authenticate();
     }
     $request->setHeader('X-Auth-Token', $this->token->getId());
 }
 /**
  * Event callback for the 'before' event
  */
 public function onBeforeSendRequest(BeforeEvent $event)
 {
     // If the database prefix is being used by SimpleTest to run the tests in a copied
     // database then set the user-agent header to the database prefix so that any
     // calls to other Drupal pages will run the SimpleTest prefixed database. The
     // user-agent is used to ensure that multiple testing sessions running at the
     // same time won't interfere with each other as they would if the database
     // prefix were stored statically in a file or database variable.
     if ($test_prefix = drupal_valid_test_ua()) {
         $event->getRequest()->setHeader('User-Agent', drupal_generate_test_ua($test_prefix));
     }
 }
예제 #30
-1
 public function onBefore(BeforeEvent $event, $name)
 {
     if (is_null($this->method)) {
         return;
     }
     $request = $event->getRequest();
     switch ($this->method) {
         case Client::AUTH_HTTP_PASSWORD:
             $request->setHeader('Authorization', sprintf('Basic %s', base64_encode($this->tokenOrLogin . ':' . $this->password)));
             break;
         case Client::AUTH_HTTP_TOKEN:
             $request->setHeader('Authorization', sprintf('token %s', $this->tokenOrLogin));
             break;
         case Client::AUTH_URL_CLIENT_ID:
             $url = $request->getUrl();
             $parameters = ['client_id' => $this->tokenOrLogin, 'client_secret' => $this->password];
             $url .= false === strpos($url, '?') ? '?' : '&';
             $url .= utf8_encode(http_build_query($parameters, '', '&'));
             $request->setUrl($url);
             break;
         case Client::AUTH_URL_TOKEN:
             $url = $request->getUrl();
             $url .= false === strpos($url, '?') ? '?' : '&';
             $url .= utf8_encode(http_build_query(['access_token' => $this->tokenOrLogin], '', '&'));
             $request->getUrl($url);
             break;
         default:
             throw new RuntimeException(sprintf('%s is not yet implemented.', $this->method));
             break;
     }
 }