Exemplo n.º 1
0
 public function testMicroBeforeHandlers()
 {
     $trace = array();
     $app = new Phalcon\Mvc\Micro();
     $app->before(function () use(&$trace) {
         $trace[] = 1;
         return false;
     });
     $app->before(function () use(&$trace) {
         $trace[] = 1;
         return false;
     });
     $app->map('/blog', function () use(&$trace) {
         $trace[] = 1;
     });
     $app->handle('/blog');
     $this->assertEquals(count($trace), 1);
 }
Exemplo n.º 2
0
     * 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>';
    }
}
Exemplo n.º 3
0
$app->before(function () use($app, $di) {
    // Browser requests, user was stored in session on login, replace into DI
    if ($di->getShared('session')->get('user') != false) {
        $di->setShared('user', function () use($di) {
            return $di->getShared('session')->get('user');
        });
        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;
});
Exemplo n.º 4
0
$app->before(function () use($app, $di) {
    $config = $app->config;
    // getting access token is permitted ;)
    if (strpos($app->request->getURI(), '/access_token') !== FALSE || strpos($app->request->getURI(), '/authorize') !== FALSE || $app->request->isOptions()) {
        return $di->getShared('rateLimits', ['access_token', $app->request->getClientAddress(), $app]);
    }
    $accessTokenRepository = new \Phalcon2Rest\Components\Oauth2\Repositories\AccessTokenRepository();
    // instance of AccessTokenRepositoryInterface
    $publicKeyPath = 'file://' . __DIR__ . '/../' . $config->oauth['public'];
    try {
        $server = new \League\OAuth2\Server\ResourceServer($accessTokenRepository, $publicKeyPath);
        $auth = new \League\OAuth2\Server\Middleware\ResourceServerMiddleware($server);
        $auth(new \Phalcon2Rest\Components\Oauth2\Request($app->request), new \Phalcon2Rest\Components\Oauth2\Response($app->response), function () {
        });
        if (isset($_SERVER['oauth_access_token_id']) && isset($_SERVER['oauth_client_id']) && isset($_SERVER['oauth_user_id']) && isset($_SERVER['oauth_scopes'])) {
            // TODO: save somewhere the user_id and scopes for future validations, e.g. /users/1/edit
            // TODO: should be accessible only if the user_id is 1 or the scope is giving permissions, e.g. admin
            if (strlen($_SERVER['oauth_client_id']) > 0) {
                return $di->getShared('rateLimits', ['api_common', 'client' . $_SERVER['oauth_client_id'], $app]);
            } else {
                return $di->getShared('rateLimits', ['api_common', 'user' . $_SERVER['oauth_user_id'], $app]);
            }
        }
    } catch (\League\OAuth2\Server\Exception\OAuthServerException $e) {
    }
    $rateLimit = $di->getShared('rateLimits', ['api_unauthorized', $app->request->getClientAddress(), $app]);
    if ($rateLimit === false) {
        return false;
    }
    throw new \Phalcon2Rest\Exceptions\HttpException('Unauthorized', 401, false, ['dev' => 'The bearer token is missing or is invalid', 'internalCode' => 'P1008', 'more' => '']);
});
Exemplo n.º 5
0
/**
 * Our 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:
 * Returning true in this function resumes normal routing.
 * Returning false stops any route from executing.
 */
$app->before(function () use($app, $di) {
    // set standard CORS headers before routing just incase no valid route is found
    $config = $di->get('config');
    $app->response->setHeader('Access-Control-Allow-Origin', $config['application']['corsOrigin']);
    return true;
});
/**
 * Mount all of the collections, which makes the routes active.
 */
foreach ($di->get('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();
Exemplo n.º 6
0
<?php

$app = new Phalcon\Mvc\Micro();
//Executed before every route executed
//Return false cancels the route execution
$app->before(function () use($app) {
    if ($app['session']->get('auth') == false) {
        return false;
    }
    return true;
});
$app->map('/api/robots', function () {
    return array('status' => 'OK');
});
$app->after(function () use($app) {
    //This is executed after the route is executed
    echo json_encode($app->getReturnedValue());
});
$app->finish(function () use($app) {
    //This is executed when the request has been served
});
Exemplo n.º 7
0
$app->before(function () use($app, $di) {
    if ($app->request->getMethod() == 'OPTIONS') {
        return true;
    }
    switch ($app->getRouter()->getRewriteUri()) {
        case '/v1/users/login/':
        case '/v1/users/login_jwt/':
        case '/v1/users/register/':
        case '/v1/reports/summary':
        case '/v1/reports/staff':
        case '/v1/reports/details':
        case '/example/route':
            return true;
            break;
    }
    // Basic auth, for programmatic responses
    $headers = apache_request_headers();
    if (isset($headers['X_API_KEY'])) {
        $user = new \PhalconRest\Controllers\UserController();
        if (!$user->loginWithPrivateKey($headers['X_API_KEY'])) {
            throw new \PhalconRest\Exceptions\HTTPException("Invalid/Expired API Key", 403);
        } else {
            return true;
        }
    }
    if (isset($headers['Authorization']) && !empty($headers['Authorization'])) {
        $arr = explode(" ", $headers['Authorization']);
        if (count($arr) > 1) {
            $value = $arr[1];
            $jws = SimpleJWS::load($value, true);
            return true;
            //			if (!$jws->isExpired()) {
            //				return true;
            //			} else
            //				throw new \PhalconRest\Exceptions\HTTPException("Invalid/Expired Token Key", 403);
        } else {
            throw new \PhalconRest\Exceptions\HTTPException("No Key Set", 403);
        }
    }
    // 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'));
});
Exemplo n.º 8
0
 * 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'))) {
            if ($app->getDi()->get('entityManager')->getRepository('Domain\\User\\Entity\\Login')->findOneBy(['token' => $app->request->getHeader('Token'), 'status' => 'active'])) {
                return true;
            }
        }
    }
    $app->response->setStatusCode(401, 'OK')->sendHeaders();
    $app->response = new \Api\Responses\JSONResponse();
    $app->response->useEnvelope(true)->convertSnakeCase(false)->send(['messages' => ['Você não tem permissão para acessar esse recurso']]);
    return false;
});
/**
 * Mount all of the collections, which makes the routes active.
Exemplo n.º 9
0
});
/**
 * Default routes
 */
$app->get("/", function () use($app, $mongo) {
    $mdb = $mongo->selectDB(MDB_DB_NAME);
    $books = $mdb->selectCollection(MDB_COLLECTION);
    $json = array("version" => VERSION, "mongodb" => 'ok', "collection" => $books->getName(), "db" => "ok", "routes" => array());
    foreach ($app->router->getRoutes() as $route) {
        $json["routes"][] = $route->getPattern();
    }
    echo "<pre>";
    echo json_encode($json, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES);
    echo "</pre>";
});
$app->notFound(function () use($app) {
    $app->response->setStatusCode(404, "Not Found")->sendHeaders();
    echo 'La url solicitada no existe!';
});
//Before middleware
$app->before(function () use($app, $logger) {
    $logger->log("{$app->request->getScheme()} {$app->request->getHttpHost()} {$app->request->getMethod()} {$app->request->get("_url")}");
});
/**
 * Route handlers
 */
require "handlers/import.php";
require "handlers/books.php";
include "handlers/library_service.php";
//Handle request
$app->handle();
Exemplo n.º 10
0
 public function testMicroStopMiddlewareClasses()
 {
     Phalcon\DI::reset();
     $app = new Phalcon\Mvc\Micro();
     $app->map('/api/site', function () {
         return true;
     });
     $middleware = new MyMiddlewareStop();
     $app->before($middleware);
     $app->before($middleware);
     $app->after($middleware);
     $app->after($middleware);
     $app->finish($middleware);
     $app->finish($middleware);
     $app->handle('/api/site');
     $this->assertEquals($middleware->getNumber(), 3);
 }
Exemplo n.º 11
0
<?php

ini_set('display_errors', 1);
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../config/services.php';
$app = new \Phalcon\Mvc\Micro($di);
require __DIR__ . '/../config/routes.php';
$app->before(new \CaioFRAlmeida\SoccerCompanyEvent\Middleware\IsAutenticado());
$app->handle();
Exemplo n.º 12
0
 *
 * @var $app
 */
$app = new Phalcon\Mvc\Micro();
$app->setDI($di);
/**
 * Before every request:
 * Returning true in this function resumes normal routing.
 * Returning false stops any route from executing.
 */
/**
 * set standard CORS headers before routing just incase no valid route is found
 */
$app->before(function () use($app, $di) {
    $config = $di->get('config');
    $app->response->setHeader('Access-Control-Allow-Origin', $config['application']['corsOrigin']);
    return true;
});
/**
 * Mount all of the collections, which makes the routes active.
 */
foreach ($di->get('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();
Exemplo n.º 13
0
 /**
  * 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();
 }
Exemplo n.º 14
0
define('RECAPTCHA_PUBLIC', $config->captcha->pub);
define('RECAPTCHA_PRIVATE', $config->captcha->priv);
$loader = new \Phalcon\Loader();
$loader->registerDirs(array(ROOTDIR . '/app/models/', ROOTDIR . '/app/vendor/'))->register();
require_once ROOTDIR . '/app/vendor/recaptcha-php/recaptchalib.php';
require_once ROOTDIR . '/app/config/di.php';
$app = new Phalcon\Mvc\Micro($di);
$app->url->setBaseUri($app->config->app->base_uri);
$app->before(function () use($app) {
    $route = $app->router->getMatchedRoute()->getName();
    $not_restricted = array('login', 'error');
    if ($app->session->has("logged_in") !== true && !in_array($route, $not_restricted)) {
        $app->response->redirect("login")->sendHeaders();
        return false;
    } elseif ($route == 'login' && $app->session->has("logged_in")) {
        $app->response->redirect()->sendHeaders();
        return false;
    }
    if ($app->request->isSecureRequest() !== true) {
        $app->response->redirect('https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'], true)->sendHeaders();
        return false;
    }
});
require_once ROOTDIR . '/app/config/routes.php';
try {
    $app->handle();
} catch (Exception $e) {
    if ($app->config->app->debug == 0) {
        $app->response->redirect("error")->sendHeaders();
    } else {
        $s = get_class($e) . ": " . $e->getMessage() . "<br>" . " File=" . $e->getFile() . "<br>" . " Line=" . $e->getLine() . "<br>" . $e->getTraceAsString();