Exemple #1
0
 /**
  * Executes a apiServiceRequest using a RESTful call by transforming it into a apiHttpRequest,
  * execute it via apiIO::authenticatedRequest() and returning the json decoded result
  *
  * @param apiServiceRequest $req
  * @return array decoded result
  * @throws apiServiceException on server side error (ie: not authenticated, invalid or
  * malformed post body, invalid url)
  */
 public static function execute(apiServiceRequest $req)
 {
     $result = null;
     $postBody = $req->getPostBody();
     $url = self::createRequestUri($req->getRestBasePath(), $req->getRestPath(), $req->getParameters());
     //var_dump($url);
     $httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody);
     // Add a content-type: application/json header so the server knows how to interpret the post body
     if ($postBody) {
         $contentTypeHeader = array('Content-Type: application/json; charset=UTF-8', 'Content-Length: ' . apiUtils::getStrLen($postBody));
         if ($httpRequest->getHeaders()) {
             $contentTypeHeader = array_merge($httpRequest->getHeaders(), $contentTypeHeader);
         }
         $httpRequest->setHeaders($contentTypeHeader);
     }
     // TODO : ajout didier pour passage adresse IP client
     //        $newHeader = array(
     //            //'X-Forwarded-For: ' . $_SERVER['SERVER_ADDR']
     //            'X-Forwarded-For: 88.176.177.141'
     //        );
     //        if ($httpRequest->getHeaders()) {
     //            $newHeader = array_merge($httpRequest->getHeaders(), $newHeader);
     //        }
     //        $httpRequest->setHeaders($newHeader);
     //
     //        var_dump($httpRequest);
     $httpRequest = apiClient::$io->authenticatedRequest($httpRequest);
     $decodedResponse = self::decodeHttpResponse($httpRequest);
     //FIXME currently everything is wrapped in a data envelope, but hopefully this might change some day
     $ret = isset($decodedResponse['data']) ? $decodedResponse['data'] : $decodedResponse;
     return $ret;
 }
Exemple #2
0
 public function testStrLen()
 {
     $this->assertEquals(0, apiUtils::getStrLen(null));
     $this->assertEquals(0, apiUtils::getStrLen(false));
     $this->assertEquals(0, apiUtils::getStrLen(""));
     $this->assertEquals(1, apiUtils::getStrLen(" "));
     $this->assertEquals(2, apiUtils::getStrLen(" 1"));
     $this->assertEquals(7, apiUtils::getStrLen("0a\\n\n\r\n"));
 }
 /**
  * Creates a signed JWT.
  * @param array $payload
  * @return string The signed JWT.
  */
 private function makeSignedJwt($payload)
 {
     $header = array('typ' => 'JWT', 'alg' => 'RS256');
     $segments = array(apiUtils::urlSafeB64Encode(json_encode($header)), apiUtils::urlSafeB64Encode(json_encode($payload)));
     $signingInput = implode('.', $segments);
     $signer = new apiP12Signer($this->privateKey, $this->privateKeyPassword);
     $signature = $signer->sign($signingInput);
     $segments[] = apiUtils::urlSafeB64Encode($signature);
     return implode(".", $segments);
 }
Exemple #4
0
 private function makeSignedJwt($payload)
 {
     $header = array("typ" => "JWT", "alg" => "RS256");
     $segments = array();
     $segments[] = apiUtils::urlSafeB64Encode(json_encode($header));
     $segments[] = apiUtils::urlSafeB64Encode(json_encode($payload));
     $signing_input = implode(".", $segments);
     $signature = $this->signer->sign($signing_input);
     $segments[] = apiUtils::urlSafeB64Encode($signature);
     return implode(".", $segments);
 }
 public function getDetails($isbn = null)
 {
     if ($isbn != null && apiUtils::isValidISBN($isbn)) {
         $url = MessageFormatter::formatMessage("nl_NL", BookloveApi::baseUrl . BookloveApi::editionInfoEndpoint, array($this->apikey, $isbn));
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         $response = curl_exec($ch);
         curl_close($ch);
         if ($response !== false) {
             return $response;
         }
         return null;
     }
 }
Exemple #6
0
 /**
  * Executes a apiServiceRequest using a RESTful call by transforming it into a apiHttpRequest,
  * execute it via apiIO::authenticatedRequest() and returning the json decoded result
  *
  * @param apiServiceRequest $req
  * @return array decoded result
  * @throws apiServiceException on server side error (ie: not authenticated, invalid or
  * malformed post body, invalid url)
  */
 public static function execute(apiServiceRequest $req)
 {
     $result = null;
     $postBody = $req->getPostBody();
     $url = self::createRequestUri($req->getRestBasePath(), $req->getRestPath(), $req->getParameters());
     $httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody);
     // Add a content-type: application/json header so the server knows how to interpret the post body
     if ($postBody) {
         $contentTypeHeader = array('Content-Type: application/json; charset=UTF-8', 'Content-Length: ' . apiUtils::getStrLen($postBody));
         if ($httpRequest->getHeaders()) {
             $contentTypeHeader = array_merge($httpRequest->getHeaders(), $contentTypeHeader);
         }
         $httpRequest->setHeaders($contentTypeHeader);
     }
     $httpRequest = $req->getIo()->authenticatedRequest($httpRequest);
     $decodedResponse = self::decodeHttpResponse($httpRequest);
     //FIXME currently everything is wrapped in a data envelope, but hopefully this might change some day
     $ret = isset($decodedResponse['data']) ? $decodedResponse['data'] : $decodedResponse;
     return $ret;
 }
 /**
  * Executes a apiServiceRequest using a RESTful call by transforming it into
  * an apiHttpRequest, and executed via apiIO::authenticatedRequest().
  *
  * @param apiServiceRequest $req
  * @return array decoded result
  * @throws apiServiceException on server side error (ie: not authenticated, invalid or
  * malformed post body, invalid url)
  */
 public static function execute(apiServiceRequest $req)
 {
     $result = null;
     $postBody = $req->getPostBody();
     $url = self::createRequestUri($req->getRestBasePath(), $req->getRestPath(), $req->getParameters());
     $httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody);
     if ($postBody) {
         $contentTypeHeader = array();
         if (isset($req->contentType) && $req->contentType) {
             $contentTypeHeader['content-type'] = $req->contentType;
         } else {
             $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
             $contentTypeHeader['content-length'] = apiUtils::getStrLen($postBody);
         }
         $httpRequest->setRequestHeaders($contentTypeHeader);
     }
     $httpRequest = apiClient::$io->authenticatedRequest($httpRequest);
     $decodedResponse = self::decodeHttpResponse($httpRequest);
     //FIXME currently everything is wrapped in a data envelope, but hopefully this might change some day
     $ret = isset($decodedResponse['data']) ? $decodedResponse['data'] : $decodedResponse;
     return $ret;
 }
 /**
  * @param array $headers The HTTP request headers
  * to be set and normalized.
  */
 public function setRequestHeaders($headers)
 {
     $headers = apiUtils::normalize($headers);
     if ($this->requestHeaders) {
         $headers = array_merge($this->requestHeaders, $headers);
     }
     $this->requestHeaders = $headers;
 }
 function verifySignedJwtWithCerts($jwt, $certs, $required_audience)
 {
     $segments = explode(".", $jwt);
     if (count($segments) != 3) {
         throw new apiAuthException("Wrong number of segments in token: {$jwt}");
     }
     $signed = $segments[0] . "." . $segments[1];
     $signature = apiUtils::urlSafeB64Decode($segments[2]);
     // Parse envelope.
     $envelope = json_decode(apiUtils::urlSafeB64Decode($segments[0]), true);
     if (!$envelope) {
         throw new apiAuthException("Can't parse token envelope: " . $segments[0]);
     }
     // Parse token
     $json_body = apiUtils::urlSafeB64Decode($segments[1]);
     $payload = json_decode($json_body, true);
     if (!$payload) {
         throw new apiAuthException("Can't parse token payload: " . $segments[1]);
     }
     // Check signature
     $verified = false;
     foreach ($certs as $keyName => $pem) {
         $public_key = new apiPemVerifier($pem);
         if ($public_key->verify($signed, $signature)) {
             $verified = true;
             break;
         }
     }
     if (!$verified) {
         throw new apiAuthException("Invalid token signature: {$jwt}");
     }
     // Check issued-at timestamp
     $iat = 0;
     if (array_key_exists("iat", $payload)) {
         $iat = $payload["iat"];
     }
     if (!$iat) {
         throw new apiAuthException("No issue time in token: {$json_body}");
     }
     $earliest = $iat - self::CLOCK_SKEW_SECS;
     // Check expiration timestamp
     $now = time();
     $exp = 0;
     if (array_key_exists("exp", $payload)) {
         $exp = $payload["exp"];
     }
     if (!$exp) {
         throw new apiAuthException("No expiration time in token: {$json_body}");
     }
     if ($exp >= $now + self::MAX_TOKEN_LIFETIME_SECS) {
         throw new apiAuthException("Expiration time too far in future: {$json_body}");
     }
     $latest = $exp + self::CLOCK_SKEW_SECS;
     if ($now < $earliest) {
         throw new apiAuthException("Token used too early, {$now} < {$earliest}: {$json_body}");
     }
     if ($now > $latest) {
         throw new apiAuthException("Token used too late, {$now} > {$latest}: {$json_body}");
     }
     // TODO(beaton): check issuer field?
     // Check audience
     $aud = $payload["aud"];
     if ($aud != $required_audience) {
         throw new apiAuthException("Wrong recipient, {$aud} != {$required_audience}: {$json_body}");
     }
     // All good.
     return new apiLoginTicket($envelope, $payload);
 }
 private function getResumeUri(apiHttpRequest $httpRequest)
 {
     $result = null;
     $body = $httpRequest->getPostBody();
     if ($body) {
         $httpRequest->setRequestHeaders(array('content-type' => 'application/json; charset=UTF-8', 'content-length' => apiUtils::getStrLen($body), 'x-upload-content-type' => $this->mimeType, 'expect' => ''));
     }
     $response = apiClient::$io->makeRequest($httpRequest);
     $location = $response->getResponseHeader('location');
     $code = $response->getResponseHttpCode();
     if (200 == $code && true == $location) {
         return $location;
     }
     throw new apiException("Failed to start the resumable upload");
 }
Exemple #11
0
        $app->response->headers->set('Content-Type', 'application/json');
        $app->response->setBody($details);
    } else {
        $response = $bookLoveApi->findBooksByTitle($q);
        if ($response != null) {
            $responseArray = json_decode($response, true);
            if ($responseArray['resultcode'] == 'SUCCESS') {
                $app->response->setBody($response);
            }
        } else {
            $app->response->setStatus(404);
        }
    }
});
$app->get('/v1/book/:query', function ($q) use($app, $bookLoveApi) {
    if (apiUtils::isValidISBN($q)) {
        $nurCode = NurApi::getByISBN($q);
        $details = $bookLoveApi->getDetails($q);
        if ($details != null) {
            $arrDetails = json_decode($details, true);
            if ($arrDetails['resultcode'] == "SUCCESS" && $nurCode != null) {
                $description = NurApi::getDescription($nurCode);
                $arrDetails['nur'] = array('code' => intval($nurCode), 'description' => $description);
            }
            $details = json_encode($arrDetails);
        }
        $app->response->headers->set('Content-Type', 'application/json');
        $app->response->setBody($details);
    } else {
        $app->response->setStatus(400);
    }
 private function getResumeUri(apiServiceRequest $req)
 {
     $result = null;
     $postBody = $req->getPostBody();
     $url = apiREST::createRequestUri($req->getRestBasePath(), $req->getRestPath(), $req->getParameters());
     $httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody);
     if ($postBody) {
         $httpRequest->setRequestHeaders(array('content-type' => 'application/json; charset=UTF-8', 'content-length' => apiUtils::getStrLen($postBody), 'x-upload-content-type' => $this->mimeType, 'expect' => ''));
     }
     $response = apiClient::$io->authenticatedRequest($httpRequest);
     $location = $response->getResponseHeader('location');
     $code = $response->getResponseHttpCode();
     if (200 == $code && true == $location) {
         return $location;
     }
     throw new apiException("Failed to start the resumable upload");
 }
 /**
  * @param $name
  * @param $arguments
  * @return apiHttpRequest|array
  * @throws apiException
  */
 public function __call($name, $arguments)
 {
     if (!isset($this->methods[$name])) {
         throw new apiException("Unknown function: {$this->serviceName}->{$this->resourceName}->{$name}()");
     }
     $method = $this->methods[$name];
     $parameters = $arguments[0];
     // postBody is a special case since it's not defined in the discovery document as parameter, but we abuse the param entry for storing it
     $postBody = null;
     if (isset($parameters['postBody'])) {
         if (is_object($parameters['postBody'])) {
             $this->stripNull($parameters['postBody']);
         }
         // Some APIs require the postBody to be set under the data key.
         if (is_array($parameters['postBody']) && 'latitude' == $this->serviceName) {
             if (!isset($parameters['postBody']['data'])) {
                 $rawBody = $parameters['postBody'];
                 unset($parameters['postBody']);
                 $parameters['postBody']['data'] = $rawBody;
             }
         }
         $postBody = is_array($parameters['postBody']) || is_object($parameters['postBody']) ? json_encode($parameters['postBody']) : $parameters['postBody'];
         unset($parameters['postBody']);
         if (isset($parameters['optParams'])) {
             $optParams = $parameters['optParams'];
             unset($parameters['optParams']);
             $parameters = array_merge($parameters, $optParams);
         }
     }
     if (!isset($method['parameters'])) {
         $method['parameters'] = array();
     }
     $method['parameters'] = array_merge($method['parameters'], $this->stackParameters);
     foreach ($parameters as $key => $val) {
         if ($key != 'postBody' && !isset($method['parameters'][$key])) {
             throw new apiException("({$name}) unknown parameter: '{$key}'");
         }
     }
     if (isset($method['parameters'])) {
         foreach ($method['parameters'] as $paramName => $paramSpec) {
             if (isset($paramSpec['required']) && $paramSpec['required'] && !isset($parameters[$paramName])) {
                 throw new apiException("({$name}) missing required param: '{$paramName}'");
             }
             if (isset($parameters[$paramName])) {
                 $value = $parameters[$paramName];
                 $parameters[$paramName] = $paramSpec;
                 $parameters[$paramName]['value'] = $value;
                 unset($parameters[$paramName]['required']);
             } else {
                 unset($parameters[$paramName]);
             }
         }
     }
     // Discovery v1.0 puts the canonical method id under the 'id' field.
     if (!isset($method['id'])) {
         $method['id'] = $method['rpcMethod'];
     }
     // Discovery v1.0 puts the canonical path under the 'path' field.
     if (!isset($method['path'])) {
         $method['path'] = $method['restPath'];
     }
     $restBasePath = $this->service->restBasePath;
     // Process Media Request
     $contentType = false;
     if (isset($method['mediaUpload'])) {
         $media = apiMediaFileUpload::process($postBody, $parameters);
         if ($media) {
             $contentType = isset($media['content-type']) ? $media['content-type'] : null;
             $postBody = isset($media['postBody']) ? $media['postBody'] : null;
             $restBasePath = $method['mediaUpload']['protocols']['simple']['path'];
             $method['path'] = '';
         }
     }
     $url = apiREST::createRequestUri($restBasePath, $method['path'], $parameters);
     $httpRequest = new apiHttpRequest($url, $method['httpMethod'], null, $postBody);
     if ($postBody) {
         $contentTypeHeader = array();
         if (isset($contentType) && $contentType) {
             $contentTypeHeader['content-type'] = $contentType;
         } else {
             $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
             $contentTypeHeader['content-length'] = apiUtils::getStrLen($postBody);
         }
         $httpRequest->setRequestHeaders($contentTypeHeader);
     }
     $httpRequest = apiClient::$auth->sign($httpRequest);
     if (apiClient::$useBatch) {
         return $httpRequest;
     }
     // Terminate immediatly if this is a resumable request.
     if (isset($parameters['uploadType']['value']) && 'resumable' == $parameters['uploadType']['value']) {
         return $httpRequest;
     }
     return apiREST::execute($httpRequest);
 }