Ejemplo n.º 1
0
 public function import($data)
 {
     $data = Parser::decode($data, false);
     $result = [];
     if (!$data instanceof stdClass) {
         throw new RuntimeException('Data must be an object');
     }
     $classes = isset($data->actionClass) ? $data->actionClass : null;
     if (!empty($classes) && is_array($classes)) {
         foreach ($classes as $class) {
             $this->insertClass('fusio_action_class', $class, 'Fusio\\Engine\\ActionInterface');
         }
     }
     $classes = isset($data->connectionClass) ? $data->connectionClass : null;
     if (!empty($classes) && is_array($classes)) {
         foreach ($classes as $class) {
             $this->insertClass('fusio_connection_class', $class, 'Fusio\\Engine\\ConnectionInterface');
         }
     }
     foreach ($this->types as $type) {
         if (isset($data->{$type}) && is_array($data->{$type})) {
             foreach ($data->{$type} as $entry) {
                 $result[] = $this->importType($type, $entry);
             }
         }
     }
     return $result;
 }
Ejemplo n.º 2
0
 public function testPost()
 {
     $body = 'grant_type=authorization_code&code=GHMbtJi0ZuAUnp80';
     $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 = Parser::decode($body, true);
     $this->assertEquals(200, $response->getStatusCode(), $body);
     $expireDate = strtotime('+2 day');
     $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(3, $row['appId']);
     $this->assertEquals(3, $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));
 }
Ejemplo n.º 3
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:qf2vX10Ec3wFZHx0K1eL')], $body);
     $body = (string) $response->getBody();
     $data = Parser::decode($body, true);
     $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,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(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,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));
 }
Ejemplo n.º 4
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = $input->getArgument('file');
     if (!is_file($file)) {
         $output->writeln('Invalid schema file');
         return 1;
     }
     $response = $this->apiExecutor->request('POST', 'schema', ['name' => $input->getArgument('name'), 'source' => Parser::decode(file_get_contents($file))]);
     $output->writeln("");
     $output->writeln($response->message);
     $output->writeln("");
 }
Ejemplo n.º 5
0
 public function onPost()
 {
     try {
         $this->connection->beginTransaction();
         $data = Parser::encode($this->getBody());
         $result = $this->systemImportService->import($data);
         $this->connection->commit();
         $this->setBody(['success' => true, 'message' => 'Import successful', 'result' => $result]);
     } catch (\Exception $e) {
         $this->connection->rollback();
         throw $e;
     }
 }
Ejemplo n.º 6
0
 public function install(array $instructions, $basePath = null)
 {
     $data = new stdClass();
     foreach ($instructions as $instruction) {
         if ($instruction instanceof Instruction\Route && $basePath !== null) {
             $instruction->setBasePath($basePath);
         }
         $key = $instruction->getKey();
         $value = $instruction->getPayload();
         if (!isset($data->{$key})) {
             $data->{$key} = [];
         }
         array_push($data->{$key}, $value);
     }
     return $this->importService->import(Parser::encode($data));
 }
Ejemplo n.º 7
0
 protected function getAccessToken($code, $clientId, $clientSecret, $redirectUri)
 {
     if (empty($clientSecret)) {
         throw new RuntimeException('No secret provided');
     }
     $url = new Url('https://graph.facebook.com/v2.5/oauth/access_token');
     $url = $url->withParameters(['client_id' => $clientId, 'redirect_uri' => $redirectUri, 'client_secret' => $clientSecret, 'code' => $code]);
     $response = $this->httpClient->request(new GetRequest($url));
     if ($response->getStatusCode() == 200) {
         $data = Parser::decode($response->getBody());
         if (isset($data->access_token)) {
             return $data->access_token;
         }
     }
     return null;
 }
Ejemplo n.º 8
0
 protected function getAccessToken($code, $clientId, $clientSecret, $redirectUri)
 {
     if (empty($clientSecret)) {
         throw new RuntimeException('No secret provided');
     }
     $url = new Url('https://github.com/login/oauth/access_token');
     $params = ['code' => $code, 'client_id' => $clientId, 'client_secret' => $clientSecret, 'redirect_uri' => $redirectUri];
     $response = $this->httpClient->request(new PostRequest($url, ['Accept' => 'application/json', 'User-Agent' => $this->ua], $params));
     if ($response->getStatusCode() == 200) {
         $data = Parser::decode($response->getBody());
         if (isset($data->access_token)) {
             return $data->access_token;
         }
     }
     return null;
 }
Ejemplo n.º 9
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\Parser::decode($row['source'], true);
         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);
     }
 }
Ejemplo n.º 10
0
 protected function extractSchema(array $row)
 {
     $schema = null;
     if (isset($row['schema'])) {
         // 0.8
         $schema = $row['schema'];
     } elseif (isset($row['type'])) {
         // 1.0
         $schema = $row['type'];
     }
     if (!empty($schema)) {
         if (is_string($schema)) {
             if (strpos($schema, '{') === false) {
                 // check whether we have a reference to a schema
                 if (isset($this->schemas[$schema])) {
                     $schema = $this->schemas[$schema];
                 }
                 // at the moment we cant resolve external files
                 if (substr($schema, 0, 8) == '!include') {
                     throw new InvalidArgumentException('It is not possible to include external files');
                 }
             }
             // check whether we have a json format and prettify
             return Json\Parser::decode($schema, false);
         } elseif (is_array($schema)) {
             return $schema;
         }
     }
     return null;
 }
Ejemplo n.º 11
0
 /**
  * @param string $method
  * @param string $path
  * @param array|null $body
  * @return mixed
  */
 public function request($method, $path, $body = null, $verbose = false)
 {
     $header = ['User-Agent' => 'Fusio-System v' . Base::getVersion(), 'Authorization' => 'Bearer ' . $this->getAccessToken()];
     $body = $body !== null ? Parser::encode($body) : null;
     $request = new Request(new Url('http://127.0.0.1/backend/' . $path), $method, $header, $body);
     $response = new Response();
     $response->setBody(new TempStream(fopen('php://memory', 'r+')));
     $this->logger->pushHandler($verbose ? new StreamHandler(STDOUT) : new NullHandler());
     $this->dispatch->route($request, $response, null, false);
     $this->logger->popHandler();
     $body = (string) $response->getBody();
     $data = Parser::decode($body, false);
     return $data;
 }
Ejemplo n.º 12
0
 protected function verifyCaptcha($captcha, $secret)
 {
     $request = new Http\PostRequest('https://www.google.com/recaptcha/api/siteverify', [], ['secret' => $secret, 'response' => $captcha, 'remoteip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1']);
     $response = $this->httpClient->request($request);
     if ($response->getStatusCode() == 200) {
         $data = Parser::decode($response->getBody());
         if ($data->success === true) {
             return true;
         }
     }
     throw new StatusCode\BadRequestException('Invalid captcha');
 }
Ejemplo n.º 13
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $class = $input->getArgument('class');
     if (class_exists($class)) {
         $adapter = new $class();
         $helper = $this->getHelper('question');
         if ($adapter instanceof AdapterInterface) {
             // parse definition
             $definition = Parser::decode(file_get_contents($adapter->getDefinition()), false);
             $instructions = $this->parser->parse($definition);
             $rows = array();
             $hasRoutes = false;
             foreach ($instructions as $instruction) {
                 $rows[] = [$instruction->getName(), $instruction->getDescription()];
                 if ($instruction instanceof Instruction\Route) {
                     $hasRoutes = true;
                 }
             }
             // show instructions
             $output->writeLn('Loaded definition ' . $adapter->getDefinition());
             $output->writeLn('');
             $output->writeLn('The adapter will install the following entries into the system.');
             $table = new Table($output);
             $table->setHeaders(['Type', 'Description'])->setRows($rows);
             $table->render($output);
             // confirm
             $question = new ConfirmationQuestion('Do you want to continue (y/n)? ', false);
             if ($helper->ask($input, $output, $question)) {
                 // if the adapter installs new routes ask for a base path
                 if ($hasRoutes) {
                     $output->writeLn('');
                     $output->writeLn('The adapter inserts new routes into the system.');
                     $output->writeLn('Please specify a base path under which the new routes are inserted.');
                     $filter = new PathFilter();
                     $question = new Question('Base path (i.e. /acme/service): ', '/');
                     $question->setValidator(function ($answer) use($filter) {
                         if (!$filter->apply($answer)) {
                             throw new \RuntimeException(sprintf($filter->getErrorMessage(), 'Base path'));
                         }
                         return $answer;
                     });
                     $basePath = $helper->ask($input, $output, $question);
                 } else {
                     $basePath = null;
                 }
                 try {
                     $this->connection->beginTransaction();
                     $this->installer->install($instructions, $basePath);
                     $this->connection->commit();
                     $output->writeln('Registration successful');
                 } catch (\Exception $e) {
                     $this->connection->rollback();
                     $output->writeln('An exception occured during installation of the adapter. No changes are applied to the database.');
                     $output->writeln('');
                     $output->writeln('Message: ' . $e->getMessage());
                     $output->writeln('Trace: ' . $e->getTraceAsString());
                 }
             } else {
                 $output->writeln('Abort');
             }
         } else {
             $output->writeln('Class does not implement the AdapterInterface');
         }
     } else {
         $output->writeln('Provided adapter class does not exist');
     }
 }
Ejemplo n.º 14
0
    /**
     * @dataProvider providerDebugStatus
     */
    public function testPut($debug)
    {
        Environment::getContainer()->get('config')->set('psx_debug', $debug);
        $body = <<<'JSON'
{
    "title": "foo",
    "content": "bar",
    "date": "2015-07-04T13:03:00Z"
}
JSON;
        $response = $this->sendRequest('http://127.0.0.1/foo', 'PUT', array('User-Agent' => 'Fusio TestCase', 'Authorization' => 'Bearer b41344388feed85bc362e518387fdc8c81b896bfe5e794131e1469770571d873'), $body);
        $body = (string) $response->getBody();
        $data = Parser::decode($body);
        $this->assertEquals(405, $response->getStatusCode(), $body);
        $this->assertEquals('GET, POST', $response->getHeader('Allow'), $body);
        $this->assertEquals(false, $data->success, $body);
        $this->assertEquals('Given request method is not supported', substr($data->message, 0, 37), $body);
    }