public function testMicroCollections() { $app = new Phalcon\Mvc\Micro(); $collection = new Phalcon\Mvc\Micro\Collection(); $controller = new PersonasController(); $collection->setHandler($controller); $collection->map('/', 'index', 'index_route'); $collection->map('/edit/{number}', 'edit', 'edit_route'); $app->mount($collection); $app->handle('/'); $this->assertEquals(1, $controller->getEntered()); $this->assertEquals('index_route', $app->getRouter()->getMatchedRoute()->getName()); $app->handle('/edit/100'); $this->assertEquals(101, $controller->getEntered()); $this->assertEquals('edit_route', $app->getRouter()->getMatchedRoute()->getName()); }
* Read the configuration */ $config = (include APP_PATH . "/app/config/config.php"); /** * Read auto-loader */ include APP_PATH . "/app/config/loader.php"; /** * Read services */ include APP_PATH . "/app/config/services.php"; /** * Handle the request */ $app = new \Phalcon\Mvc\Micro($di); $app->getRouter()->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); $app->before(new App\Middleware\OAuthMiddleware()); /** * Mount routes collections */ $collections = (include APP_PATH . '/app/collections/collections.php'); foreach ($collections as $collection) { $app->mount($collection); } $app->handle(); } catch (\Exception $e) { if ($app->config->debug) { echo $e->getMessage() . '<br>'; echo '<pre>' . $e->getTraceAsString() . '</pre>'; } }
return false; } elseif ($authinfo['HubEnabled'] != '1') { $response = new Phalcon\Http\Response(); $response->setStatusCode(401, "Unauthorized"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array('Hub is disabled (Access denied)'))); $response->send(); return false; } // We passed! Peer is authorized! } } }); //Create and bind the DI to the application $app = new \Phalcon\Mvc\Micro(); $app->setEventsManager($eventManager); $router = $app->getRouter(); $router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI); // ============================================================================ // BALANCES (for dmnbalance) // ---------------------------------------------------------------------------- // End-point to retrieve all pubkeys and last updates // HTTP method: // GET // Parameters: // None // ============================================================================ $app->get('/balances', function () use($app, &$mysqli) { global $authinfo; //Create a response $response = new Phalcon\Http\Response(); $request = $app->request;
return true; } // Basic auth, for programmatic responses if ($app->request->getServer('PHP_AUTH_USER')) { $user = new \PhalconRest\Controllers\UsersController(); $user->login($app->request->getServer('PHP_AUTH_USER'), $app->request->getServer('PHP_AUTH_PW')); return true; } // All options requests get a 200, then die if ($app->__get('request')->getMethod() == 'OPTIONS') { $app->response->setStatusCode(200, 'OK')->sendHeaders(); exit; } // Exempted routes, such as login, or public info. Let the route handler // pick it up. switch ($app->getRouter()->getRewriteUri()) { case '/v1/user/login': return true; break; case '/example/route': return true; break; } // If we made it this far, we have no valid auth method, throw a 401. throw new \PhalconRest\Exceptions\HTTPException('Must login or provide credentials.', 401, array('dev' => 'Please provide credentials by either passing in a session token via cookie, or providing password and username via BASIC authentication.', 'internalCode' => 'Unauth:1')); return false; }); /** * Mount all of the collections, which makes the routes active. */ foreach ($di->get('collections') as $collection) {
$logger->warning($e->getMessage()); if (method_exists($e, 'send')) { $e->send(); } $logger->error($e->getTraceAsString()); }); /** * Mount all collections (Makes routes active). * @todo improve this block of code */ foreach ($modulesName as $module) { $routeDefinitions = array('GET' => array(), 'POST' => array(), 'PUT' => array(), 'DELETE' => array()); try { foreach ($di->get('collections_' . $module) as $collection) { $app->mount($collection); $routes = $app->getRouter()->getRoutes(); foreach ($routes as $route) { $pattern = $route->getPattern(); $method = $route->getHttpMethods(); if (array_search($pattern, $routeDefinitions[$method]) !== false) { $msg = 'Route: ' . $method . ' ' . $pattern . '" is already implemented (Duplicated)'; throw new \Modules\Core\Exceptions\RouteException($msg, 500); } $routeDefinitions[$method][] = $pattern; } } } catch (Exception $e) { $logger->warning($e->getMessage()); } } /**
return $json; }); /** * Out application is a Micro application, so we mush explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * @var $app */ $app = new Phalcon\Mvc\Micro(); $app->setDI($di); /** * Before every request, make sure user is authenticated. * Returning true in this function resumes normal routing. * Returning false stops any route from executing. */ $app->before(function () use($app, $di) { $matchedRoute = $app->getRouter()->getMatchedRoute()->getName(); // All options requests get a 200, then die if ($app->__get('request')->getMethod() == 'OPTIONS') { $app->response->setStatusCode(200, 'OK')->sendHeaders(); exit; } if (preg_match("/-allow/", $matchedRoute)) { return true; } // @todo adicionar uma tabela com chaves de acesso basico if ($app->request->getHeader('BasicAuthorization') === 'uHealth1235486tcc') { //validar acesso a recursos basicos if (preg_match("/-authbasic/", $matchedRoute)) { return true; } if (strlen($app->request->getHeader('Token'))) {
/** * Handles the request. */ public function main() { /** * Our application is a Micro application, so we must explicitly define all the routes. * For APIs, this is ideal. This is as opposed to the more robust MVC Application * @var $app */ $app = new \Phalcon\Mvc\Micro(); $app->setDI($this->di); /** * This will require changes to fit your application structure. * It supports Auth, Session auth, and Exempted routes. * It also allows all Options requests, as those tend to not come with * cookies or basic auth credentials and Preflight is not implemented the * same in every browser. */ $app->before(function () use($app) { // Oauth, for programmatic responses if ($app->request->getHeader('X_COMPARE_REST_API_KEY') && $app->request->get('language') && $app->request->get('countryCode')) { $session = new SessionsController(); $result = $session->resource($app->request->getHeader('X_COMPARE_REST_API_KEY')); if ($result) { return true; } else { throw new HTTPException('Invalid access token.', 401, ['dev' => 'Please provide credentials by passing your access token.', 'internalCode' => 'Unauth:1']); } } // If we made it this far, we have no valid auth method, throw a 401. throw new HTTPException('Must provide credentials.', 401, ['dev' => 'Please provide credentials by passing your access token, language and country code.', 'internalCode' => 'Unauth:1']); return false; }); /** * Mount all of the collections, which makes the routes active. */ foreach ($this->di->getShared('collections') as $collection) { $app->mount($collection); } /** * The base route return the list of defined routes for the application. * This is not strictly REST compliant, but it helps to base API documentation off of. * By calling this, you can quickly see a list of all routes and their methods. */ $app->get('/', function () use($app) { $routes = $app->getRouter()->getRoutes(); $routeDefinitions = array('GET' => array(), 'POST' => array(), 'PUT' => array(), 'PATCH' => array(), 'DELETE' => array(), 'HEAD' => array(), 'OPTIONS' => array()); foreach ($routes as $route) { $method = $route->getHttpMethods(); $routeDefinitions[$method][] = $route->getPattern(); } return $routeDefinitions; }); /** * After a route is run, usually when its Controller returns a final value, * the application runs the following function which actually sends the response to the client. * * The default behavior is to send the Controller's returned value to the client as JSON. * However, by parsing the request querystring's 'type' paramter, it is easy to install * different response type handlers. Below is an alternate csv handler. */ $app->after(function () use($app) { // OPTIONS have no body, send the headers, exit if ($app->request->getMethod() == 'OPTIONS') { $app->response->setStatusCode('200', 'OK'); $app->response->send(); return; } // Respond by default as JSON if (!$app->request->get('type') || 'json' == $app->request->get('type') || 'option' == $app->request->get('type')) { // Results returned from the route's controller. All Controllers should return an array $records = $app->getReturnedValue(); $response = new JSONResponse(); $response->useEnvelope(true)->convertSnakeCase(true)->send($records); return; } else { if ('xml' == $app->request->get('type')) { $records = $app->getReturnedValue(); $response = new XMLResponse(); $response->send($records); return; } else { if ('csv' == $app->request->get('type')) { $records = $app->getReturnedValue(); $response = new CSVResponse(); $response->useHeaderRow(true)->send($records); return; } else { throw new HTTPException('Could not return results in specified format', 403, array('dev' => 'Could not understand type specified by type paramter in query string.', 'internalCode' => 'NF1000', 'more' => 'Type may not be implemented. Choose either "json", "xml" or "csv"')); } } } }); /** * The notFound service is the default handler function that runs when no route was matched. * We set a 404 here unless there's a suppress error codes. */ $app->notFound(function () use($app) { throw new HTTPException('Not Found.', 404, array('dev' => 'That route was not found on the server.', 'internalCode' => 'NF1000', 'more' => 'Check route for mispellings.')); }); /** * If the application throws an HTTPException, send it on to the client as json. * Elsewise, just log it. */ set_exception_handler(function ($exception) use($app) { //HTTPException's send method provides the correct response headers and body if (is_a($exception, 'App\\Common\\Lib\\Application\\Exceptions\\HTTPException')) { $exception->send(); } error_log($exception); error_log($exception->getTraceAsString()); }); $app->handle(); }