Exemplo n.º 1
0
 protected function sendSignedRequest($type, RecordInterface $record = null)
 {
     $url = new Url($this->getEndpoint());
     $body = $record !== null ? Json::encode($record->getFields()) : null;
     $header = array('Content-Type' => 'application/json', 'Accept' => 'application/json');
     return $this->signedRequest($type, $url, $header, $body);
 }
Exemplo n.º 2
0
 public function testPost()
 {
     $body = 'grant_type=client_credentials&scope=authorization';
     $response = $this->sendRequest('http://127.0.0.1/authorization/token', 'POST', ['User-Agent' => 'Fusio TestCase', 'Authorization' => 'Basic ' . base64_encode('5347307d-d801-4075-9aaa-a21a29a448c5:342cefac55939b31cd0a26733f9a4f061c0829ed87dae7caff50feaa55aff23d')], $body);
     $body = (string) $response->getBody();
     $data = Json::decode($body);
     $this->assertEquals(200, $response->getStatusCode(), $body);
     $expireDate = strtotime('+6 hour');
     $this->arrayHasKey('access_token', $data);
     $this->arrayHasKey('token_type', $data);
     $this->assertEquals('bearer', $data['token_type']);
     $this->arrayHasKey('expires_in', $data);
     $this->assertEquals(date('Y-m-d H:i', $expireDate), date('Y-m-d H:i', $data['expires_in']));
     $this->arrayHasKey('scope', $data);
     $this->assertEquals('authorization', $data['scope']);
     // check whether the token was created
     $row = $this->connection->fetchAssoc('SELECT appId, userId, status, token, scope, expire, date FROM fusio_app_token WHERE token = :token', ['token' => $data['access_token']]);
     $this->assertEquals(2, $row['appId']);
     $this->assertEquals(2, $row['userId']);
     $this->assertEquals(Token::STATUS_ACTIVE, $row['status']);
     $this->assertEquals($data['access_token'], $row['token']);
     $this->assertEquals('authorization', $row['scope']);
     $this->assertEquals(date('Y-m-d H:i', $expireDate), date('Y-m-d H:i', strtotime($row['expire'])));
     $this->assertEquals(date('Y-m-d H:i'), substr($row['date'], 0, 16));
 }
Exemplo n.º 3
0
 public function parse($schema)
 {
     $data = Json::decode($schema);
     $document = new Document($data, $this->resolver, $this->basePath);
     $this->resolver->setRootDocument($document);
     return new Schema($document->getProperty());
 }
Exemplo n.º 4
0
 public function testPost()
 {
     $body = 'grant_type=client_credentials&scope=authorization';
     $response = $this->sendRequest('http://127.0.0.1/backend/token', 'POST', ['User-Agent' => 'Fusio TestCase', 'Authorization' => 'Basic ' . base64_encode('Developer:3632465b3b5d1b8b4b8e56f74600da00cea92baf')], $body);
     $body = (string) $response->getBody();
     $data = Json::decode($body);
     $this->assertEquals(200, $response->getStatusCode(), $body);
     $expireDate = strtotime('+1 hour');
     $this->arrayHasKey('access_token', $data);
     $this->arrayHasKey('token_type', $data);
     $this->assertEquals('bearer', $data['token_type']);
     $this->arrayHasKey('expires_in', $data);
     $this->assertEquals(date('Y-m-d H:i', $expireDate), date('Y-m-d H:i', $data['expires_in']));
     $this->arrayHasKey('scope', $data);
     $this->assertEquals('backend', $data['scope']);
     // check whether the token was created
     $row = $this->connection->fetchAssoc('SELECT appId, userId, status, token, scope, expire, date FROM fusio_app_token WHERE token = :token', ['token' => $data['access_token']]);
     $this->assertEquals(1, $row['appId']);
     $this->assertEquals(4, $row['userId']);
     $this->assertEquals(Token::STATUS_ACTIVE, $row['status']);
     $this->assertEquals($data['access_token'], $row['token']);
     $this->assertEquals('backend', $row['scope']);
     $this->assertEquals(date('Y-m-d H:i', $expireDate), date('Y-m-d H:i', strtotime($row['expire'])));
     $this->assertEquals(date('Y-m-d H:i'), substr($row['date'], 0, 16));
 }
Exemplo n.º 5
0
 public function request(Url $url, $mode, $host, $name, $header = array())
 {
     if (empty($mode) || ($mode = self::getMode($mode)) === false) {
         throw new Exception('Invalid mode');
     }
     // discover service
     $url = $this->discover($url);
     // headers
     if ($this->oauth !== null) {
         $header = Request::mergeHeader(array('Accept' => 'application/json', 'Authorization' => $this->oauth->getAuthorizationHeader($url, $this->cred->getConsumerKey(), $this->cred->getConsumerSecret(), $this->cred->getToken(), $this->cred->getTokenSecret(), 'HMAC-SHA1', 'POST')), $header);
     } else {
         $header = Request::mergeHeader(array('Accept' => 'application/json'), $header);
     }
     // body
     $body = array('relation.ns' => self::NS, 'relation.mode' => $mode, 'relation.host' => $host, 'relation.name' => $name);
     $request = new PostRequest($url, $header, $body);
     $response = $this->http->request($request);
     if ($response->getCode() == 200) {
         $data = Json::decode($response->getBody());
         if (isset($data['success']) && $data['success'] === true) {
             return true;
         } else {
             $msg = isset($data['text']) ? $data['text'] : 'An error occured';
             throw new Exception($msg);
         }
     } else {
         throw new Exception('Invalid response code ' . $response->getCode());
     }
 }
Exemplo n.º 6
0
 public function generate(Resource $resource)
 {
     $methods = $resource->getMethods();
     $definitions = array();
     $properties = array();
     foreach ($methods as $method) {
         $request = $method->getRequest();
         if ($request instanceof SchemaInterface) {
             list($defs, $props) = $this->getJsonSchema($request);
             $key = strtolower($method->getName()) . 'Request';
             $definitions = array_merge($definitions, $defs);
             if (isset($props['properties'])) {
                 $properties[$key] = $props;
             }
         }
         $response = $this->getSuccessfulResponse($method);
         if ($response instanceof SchemaInterface) {
             list($defs, $props) = $this->getJsonSchema($response);
             $key = strtolower($method->getName()) . 'Response';
             $definitions = array_merge($definitions, $defs);
             if (isset($props['properties'])) {
                 $properties[$key] = $props;
             }
         }
     }
     $result = array('$schema' => JsonSchemaGenerator::SCHEMA, 'id' => $this->targetNamespace, 'type' => 'object', 'definitions' => $definitions, 'properties' => $properties);
     return Json::encode($result, JSON_PRETTY_PRINT);
 }
Exemplo n.º 7
0
Arquivo: Json.php Projeto: seytar/psx
 public function write(RecordInterface $record)
 {
     $visitor = new Visitor\StdClassSerializeVisitor();
     $graph = new GraphTraverser();
     $graph->traverse($record, $visitor);
     return JsonParser::encode($visitor->getObject(), JSON_PRETTY_PRINT);
 }
Exemplo n.º 8
0
 public function getRequest($payload)
 {
     $response = Json::decode($payload);
     if (isset($response['repository']) && isset($response['repository']['name']) && isset($response['repository']['url'])) {
         $project = new Project();
         $project->setName($response['repository']['name']);
         $project->setUrl($response['repository']['url']);
         if (isset($response['commits']) && is_array($response['commits'])) {
             foreach ($response['commits'] as $commit) {
                 try {
                     $revision = new Revision();
                     $revision->setMessage($commit['message']);
                     $revision->setTimestamp($commit['timestamp']);
                     $revision->setUrl($commit['url']);
                     $revision->setAuthor($commit['author']['username']);
                     $project->addCommit($revision);
                 } catch (\Exception $e) {
                 }
             }
         }
         return $project;
     } else {
         throw new Exception('Invalid request');
     }
 }
Exemplo n.º 9
0
 public function testHandleNoParameter()
 {
     $response = $this->callEndpoint(array());
     $data = Json::decode((string) $response->getBody());
     $this->assertEquals(false, $data['success']);
     $this->assertEquals('PSX\\Oauth2\\Authorization\\Exception\\InvalidRequestException', $data['title']);
 }
Exemplo n.º 10
0
 public function notify($type, TableInterface $table, RecordInterface $record)
 {
     $message = Json::encode($record->getData());
     $headers = array('amun-table' => $table->getName(), 'amun-type' => $type, 'amun-user-id' => $this->user->id);
     $stomp = new Stomp($this->registry['stomp.broker'], $this->registry['stomp.user'], $this->registry['stomp.pw']);
     $stomp->send($this->registry['stomp.destination'], $message, $headers);
     unset($stomp);
 }
Exemplo n.º 11
0
 /**
  * Returns this signature in the JWS JSON Serialization format
  *
  * @see http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-39#section-3.2
  * @param string $key
  * @return string
  */
 public function getJson($key)
 {
     $signature = array();
     $signature['protected'] = self::base64Encode(Json::encode($this->headers));
     $signature['payload'] = self::base64Encode($this->claim);
     $signature['signature'] = $this->getEncodedSignature($key);
     return Json::encode($signature);
 }
Exemplo n.º 12
0
 public function testGet()
 {
     $url = new Url($this->getEndpoint());
     $response = $this->signedRequest('GET', $url);
     $this->assertEquals(200, $response->getCode());
     $fields = Json::decode($response->getBody());
     $this->assertEquals(true, is_array($fields));
     $this->assertEquals(true, is_array($fields[0]['children']));
 }
Exemplo n.º 13
0
Arquivo: Json.php Projeto: seytar/psx
 public function read(MessageInterface $message)
 {
     $body = (string) $message->getBody();
     if (!empty($body)) {
         return JsonParser::decode($body, false);
     } else {
         return null;
     }
 }
Exemplo n.º 14
0
 public function testWellKnownLocation()
 {
     $url = new Url($this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . '.well-known/host-meta');
     $request = new GetRequest($url);
     $response = $this->http->request($request);
     $this->assertEquals(200, $response->getCode());
     $document = Json::decode($response->getBody());
     $this->checkHostmeta($document);
 }
Exemplo n.º 15
0
 public function testDisplayExceptionNoDebug()
 {
     Environment::getService('config')->set('psx_debug', false);
     $response = $this->sendRequest('http://127.0.0.1/display_error', 'GET', ['Accept' => 'application/json']);
     $body = (string) $response->getBody();
     $data = Json::decode($body);
     $this->assertEquals(null, $response->getStatusCode(), $body);
     $this->assertEquals(false, $data['success']);
     $this->assertEquals('foo', $data['message']);
 }
Exemplo n.º 16
0
 public function testWellKnownLocation()
 {
     $url = new Url($this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . '.well-known/webfinger');
     $url->addParam('resource', $this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'news');
     $request = new GetRequest($url);
     $response = $this->http->request($request);
     $this->assertEquals(200, $response->getCode());
     $document = Json::decode($response->getBody());
     $this->assertArrayHasKey('subject', $document);
     $this->assertEquals($this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'news', $document['subject']);
 }
Exemplo n.º 17
0
 public function handle(Request $request, Parameters $configuration, Context $context)
 {
     // parse json
     $response = $this->templateParser->parse($request, $configuration, $context, $configuration->get('response'));
     if (!empty($response)) {
         $statusCode = $configuration->get('statusCode') ?: 200;
         return new Response($statusCode, [], Json::decode($response, false));
     } else {
         throw new ConfigurationException('No response defined');
     }
 }
Exemplo n.º 18
0
 public function handle(RequestInterface $request, ParametersInterface $configuration, ContextInterface $context)
 {
     // parse json
     $parser = $this->templateFactory->newTextParser();
     $response = $parser->parse($request, $context, $configuration->get('patch'));
     // patch
     $patch = new Patch(Json::decode($response, false));
     $body = $patch->patch(Transformer::toStdClass($request->getBody()));
     $body = Transformer::toRecord($body);
     return $this->processor->execute($configuration->get('action'), $request->withBody($body), $context);
 }
Exemplo n.º 19
0
 public function handle(RequestInterface $request, ParametersInterface $configuration, ContextInterface $context)
 {
     // parse json
     $parser = $this->templateFactory->newTextParser();
     $response = $parser->parse($request, $context, $configuration->get('response'));
     if (!empty($response)) {
         $statusCode = $configuration->get('statusCode') ?: 200;
         return $this->response->build($statusCode, [], Json::decode($response, false));
     } else {
         throw new ConfigurationException('No response defined');
     }
 }
Exemplo n.º 20
0
 public function testGet()
 {
     $result = array(array('identity' => 'http://google.com', 'response' => array('handler' => 'openid', 'needPassword' => false)), array('identity' => '*****@*****.**', 'response' => array('handler' => 'system', 'needPassword' => true)), array('identity' => '*****@*****.**', 'response' => array('handler' => 'google', 'needPassword' => false)), array('identity' => '*****@*****.**', 'response' => array('handler' => 'yahoo', 'needPassword' => false)));
     foreach ($result as $row) {
         $url = new Url($this->getEndpoint() . '?identity=' . urlencode($row['identity']));
         $request = new GetRequest($url);
         $response = $this->http->request($request);
         $this->assertEquals(200, $response->getCode());
         $resp = Json::decode($response->getBody());
         unset($resp['icon']);
         $this->assertEquals($resp, $row['response']);
     }
 }
Exemplo n.º 21
0
 /**
  * Returns whether the given identity needs an password or not
  *
  * @httpMethod GET
  * @path /
  * @nickname needPassword
  * @parameter query identity string
  * @responseClass PSX_Data_Message
  */
 public function needPassword()
 {
     $identity = $this->get->identity('string');
     $handles = array_map('trim', explode(',', $this->registry['login.provider']));
     $result = array();
     foreach ($handles as $key) {
         $handler = HandlerFactory::factory($key, $this->container);
         if ($handler instanceof HandlerAbstract && $handler->isValid($identity)) {
             $result = array('handler' => $key, 'icon' => $this->config['psx_url'] . '/img/icons/login/' . $key . '.png', 'needPassword' => $handler->hasPassword());
             break;
         }
     }
     echo Json::encode($result);
 }
Exemplo n.º 22
0
 public function testDelete()
 {
     $data = json_encode(array('id' => 1));
     $response = $this->sendRequest('http://127.0.0.1/api', 'DELETE', ['Content-Type' => 'application/json'], $data);
     $body = Json::decode((string) $response->getBody());
     $this->assertEquals(405, $response->getStatusCode());
     $this->assertArrayHasKey('success', $body);
     $this->assertArrayHasKey('title', $body);
     $this->assertArrayHasKey('message', $body);
     $this->assertArrayHasKey('trace', $body);
     $this->assertArrayHasKey('context', $body);
     $this->assertEquals(false, $body['success']);
     $this->assertEquals('Method is not allowed', substr($body['message'], 0, 21));
 }
Exemplo n.º 23
0
Arquivo: Http.php Projeto: seytar/psx
 public function resolve(Uri $uri, Document $source, RefResolver $resolver)
 {
     if (!$uri->isAbsolute()) {
         $uri = UriResolver::resolve($source->getBaseUri(), $uri);
     }
     $request = new GetRequest($uri, array('Accept' => 'application/schema+json'));
     $response = $this->httpClient->request($request);
     if ($response->getStatusCode() == 200) {
         $schema = (string) $response->getBody();
         $data = Json::decode($schema);
         $document = new Document($data, $resolver, null, $uri);
         return $document;
     } else {
         throw new RuntimeException('Could not load external schema ' . $uri->toString() . ' received ' . $response->getStatusCode());
     }
 }
Exemplo n.º 24
0
 public function resolve(Uri $uri, Document $source, RefResolver $resolver)
 {
     $name = ltrim($uri->getPath(), '/');
     $row = $this->connection->fetchAssoc('SELECT name, source FROM fusio_schema WHERE name LIKE :name', array('name' => $name));
     if (!empty($row)) {
         $data = Json::decode($row['source']);
         if (is_array($data)) {
             $document = new Document($data, $resolver, null, $uri);
             return $document;
         } else {
             throw new RuntimeException(sprintf('Schema %s must be an object', $row['name']));
         }
     } else {
         throw new RuntimeException('Invalid schema reference ' . $name);
     }
 }
Exemplo n.º 25
0
 public function testExecute()
 {
     $memory = new Output\Memory();
     $output = new Output\Composite(array($memory, new Output\Logger(Environment::getService('logger'))));
     Environment::getContainer()->set('command_output', $output);
     $response = $this->sendRequest('http://127.0.0.1/command?command=' . urlencode('PSX\\Command\\Foo\\Command\\FooCommand'), 'POST', ['Content-Type' => 'application/json', 'Accept' => 'application/json'], '{"foo": "bar"}');
     $data = Json::decode((string) $response->getBody());
     $messages = $memory->getMessages();
     $this->assertArrayHasKey('output', $data);
     $this->assertEquals(2, count($messages));
     $lines = explode("\n", trim($data['output']));
     foreach ($lines as $key => $line) {
         $this->assertArrayHasKey($key, $messages);
         $this->assertContains(trim($messages[$key]), $line);
     }
 }
Exemplo n.º 26
0
Arquivo: File.php Projeto: seytar/psx
 public function resolve(Uri $uri, Document $source, RefResolver $resolver)
 {
     if ($source->isRemote()) {
         throw new RuntimeException('Can not resolve file scheme from remote source');
     }
     $path = str_replace('/', DIRECTORY_SEPARATOR, ltrim($uri->getPath(), '/'));
     $path = $source->getBasePath() !== null ? $source->getBasePath() . DIRECTORY_SEPARATOR . $path : $path;
     if (is_file($path)) {
         $basePath = pathinfo($path, PATHINFO_DIRNAME);
         $schema = file_get_contents($path);
         $data = Json::decode($schema);
         $document = new Document($data, $resolver, $basePath, $uri);
         return $document;
     } else {
         throw new RuntimeException('Could not load external schema ' . $path);
     }
 }
Exemplo n.º 27
0
 public function parse($file)
 {
     $definition = Json::decode(file_get_contents($file), false);
     $instructions = array();
     if (!empty($definition)) {
         // get action class
         if (isset($definition->actionClass) && is_array($definition->actionClass)) {
             foreach ($definition->actionClass as $actionClass) {
                 $instructions[] = new Instruction\ActionClass($actionClass);
             }
         }
         // get connection class
         if (isset($definition->connectionClass) && is_array($definition->connectionClass)) {
             foreach ($definition->connectionClass as $connectionClass) {
                 $instructions[] = new Instruction\ConnectionClass($connectionClass);
             }
         }
         // get connection
         if (isset($definition->connection) && is_array($definition->connection)) {
             foreach ($definition->connection as $connection) {
                 $instructions[] = new Instruction\Connection($connection);
             }
         }
         // get schema
         if (isset($definition->schema) && is_array($definition->schema)) {
             foreach ($definition->schema as $schema) {
                 $instructions[] = new Instruction\Schema($schema);
             }
         }
         // get action
         if (isset($definition->action) && is_array($definition->action)) {
             foreach ($definition->action as $action) {
                 $instructions[] = new Instruction\Action($action);
             }
         }
         // get routes
         if (isset($definition->routes) && is_array($definition->routes)) {
             foreach ($definition->routes as $route) {
                 $instructions[] = new Instruction\Route($route);
             }
         }
     }
     return $instructions;
 }
Exemplo n.º 28
0
 /**
  * Method wich tries to request an jrd document from the given url. Used 
  * also in the webfinger class therefore it is here static
  *
  * @return PSX\Hostmeta\Document
  */
 public static function requestJrd(Http $http, Url $url)
 {
     $request = new GetRequest($url, array('Accept' => 'application/jrd+json', 'User-Agent' => __CLASS__ . ' ' . Base::VERSION));
     $request->setFollowLocation(true);
     $response = $http->request($request);
     if ($response->getStatusCode() == 200) {
         $contentType = $response->getHeader('Content-Type');
         if (strpos($contentType, 'application/jrd+json') !== false || strpos($contentType, 'application/json') !== false) {
             $jrd = new Jrd();
             $jrd->import(Json::decode($response->getBody()));
             return $jrd;
         } else {
             if (strpos($contentType, 'application/xrd+xml') !== false || strpos($contentType, 'application/xml') !== false) {
                 $xrd = new Xrd();
                 $xrd->import(simplexml_load_string((string) $response->getBody()));
                 return $xrd;
             } else {
                 throw new Exception('Received unknown content type');
             }
         }
     } else {
         throw new Exception('Invalid response code ' . $response->getStatusCode() . ' from ' . strval($url));
     }
 }
Exemplo n.º 29
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $table = $this->tableManager->getTable('Phpsx\\Website\\Table\\Release');
     $url = sprintf('%s/repos/%s/%s/releases', $this->config['git_api'], $this->config['git_owner'], $this->config['git_repo']);
     $request = new GetRequest($url, ['Accept' => 'application/vnd.github.v3+json', 'User-Agent' => 'PSX-Website-Updater (https://github.com/k42b3)']);
     $response = $this->http->request($request);
     if ($response->getStatusCode() == 200) {
         $count = 0;
         $releases = Json::decode((string) $response->getBody());
         foreach ($releases as $release) {
             if ($release['draft'] === false) {
                 $row = $table->getOneById($release['id']);
                 if (!$row instanceof RecordInterface) {
                     $asset = $this->getAsset($release);
                     $table->create(['id' => $release['id'], 'tagName' => $release['tag_name'], 'htmlUrl' => $release['html_url'], 'publishedAt' => new DateTime($release['published_at']), 'authorName' => $release['author']['login'], 'authorUri' => $release['author']['html_url'], 'body' => $release['body'], 'assetName' => isset($asset['name']) ? $asset['name'] : null, 'assetUrl' => isset($asset['browser_download_url']) ? $asset['browser_download_url'] : null, 'assetSize' => isset($asset['size']) ? $asset['size'] : null, 'assetMime' => isset($asset['content_type']) ? $asset['content_type'] : null]);
                     $count++;
                 }
             }
         }
         $output->writeln(sprintf('Inserted %s release/s', $count));
     } else {
         $output->writeln(sprintf('Received an status code %s', $response->getStatusCode()));
     }
 }
Exemplo n.º 30
0
 public function testGet()
 {
     $url = new Url($this->getEndpoint());
     $url->addParam('format', 'jas');
     $response = $this->signedRequest('GET', $url);
     $this->assertEquals(200, $response->getCode());
     // check result
     $result = Json::decode($response->getBody());
     $this->assertArrayHasKey('itemsPerPage', $result, $response->getBody());
     $this->assertArrayHasKey('startIndex', $result, $response->getBody());
     $this->assertArrayHasKey('items', $result, $response->getBody());
     $this->assertEquals(true, count($result['items']) > 0);
     foreach ($result['items'] as $activity) {
         $this->assertArrayHasKey('actor', $activity);
         $this->assertArrayHasKey('object', $activity);
         $this->assertArrayHasKey('verb', $activity);
     }
     // try to create activitystream object
     $reader = new Reader\Json();
     $result = $reader->read($response);
     $collection = new Collection();
     $collection->import($result);
     $this->assertInstanceOf('PSX\\ActivityStream\\Collection', $collection);
 }