public static function Route() { $app = new App(); // Reminder: the request is processed from the bottom up, // the response is processed from the top down. $app->add(SlimMiddleware::class); $app->add(Grover::class); $app->run(); }
public function newApp() { // config $debug = false; if (defined("DEBUG")) { $debug = true; } // Make a Slim App $app = new App(['settings' => ['debug' => $debug, 'whoops.editor' => 'sublime']]); $app->add(new WhoopsMiddleware()); $this->app = $app; }
protected function dispatchApplication(array $server, array $pipe = []) { $app = new App(); $app->getContainer()['environment'] = function () use($server) { return new Environment($server); }; $middlewareFactory = new PhpDebugBarMiddlewareFactory(); $middleware = $middlewareFactory(); $app->add($middleware); foreach ($pipe as $pattern => $middleware) { $app->get($pattern, $middleware); } return $app->run(true); }
/** * Register DebugBar service. * * @param App $app * * @return void */ public function register(App $app) { $container = $app->getContainer(); $container['debugbar'] = function ($container) { return new SlimDebugBar($container, $this->settings); }; if (!$this->settings['enabled']) { return; } $app->group('/_debugbar', function () { $this->get('/open', 'Kitchenu\\Debugbar\\Controllers\\OpenHandlerController:handle')->setName('debugbar-openhandler'); $this->get('/assets/stylesheets', 'Kitchenu\\Debugbar\\Controllers\\AssetController:css')->setName('debugbar-assets-css'); $this->get('/assets/javascript', 'Kitchenu\\Debugbar\\Controllers\\AssetController:js')->setName('debugbar-assets-js'); }); $app->add(new Debugbar($container['debugbar'], $container['errorHandler'])); }
public function testMiddlewareIsWorkingAndEditorIsSet() { $app = new App(['settings' => ['debug' => true, 'whoops.editor' => 'sublime']]); $container = $app->getContainer(); $container['environment'] = function () { return Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET']); }; $app->get('/foo', function ($req, $res, $args) { return $res; }); $app->add(new WhoopsMiddleware()); // Invoke app $response = $app->run(); // Get added whoops handlers $handlers = $container['whoops']->getHandlers(); $this->assertEquals(2, count($handlers)); $this->assertEquals('subl://open?url=file://test_path&line=169', $handlers[0]->getEditorHref('test_path', 169)); }
/** * * @param App $slim */ public function run(App $slim) { if (!isset($_SERVER['PHP_AUTH_USER'])) { $this->response_401(); } else { if ($_SERVER['PHP_AUTH_USER'] == $this->user && sha1($_SERVER['PHP_AUTH_PW']) == $this->pass) { // Start session just in case if (!isset($_SESSION)) { session_start(); } $token = $this->TokenGenerator->Generate(session_id()); $validation = $this->TokenHandler->GetToken($token, $_SERVER['REMOTE_ADDR']); if ($validation == false) { if ($this->whitelistRetriever->check_whitelist($_SERVER['REMOTE_ADDR'])) { $validation = $this->TokenHandler->SaveCurrentToken($token, $_SERVER['REMOTE_ADDR'], date('Y-m-d H:i')); } else { $this->response_401(); } } if (!$this->whitelistRetriever->check_whitelist($_SERVER['REMOTE_ADDR'])) { $this->response_401(); } $slim->add(function (Request $request, Response $response, $next) use($token) { if (!$this->whitelistRetriever->check_whitelist($_SERVER['REMOTE_ADDR'])) { $this->response_401(); } // TODO: find a way to give a token. }); // TODO: add around every request and check if the tokens match $slim->get('/security', function () use($token) { header("Security token: " . $token); echo $token; return; }); return; } else { $this->response_401(); } } }
//Add container to handle all exceptions/errors, fail safe and return json $container['errorHandler'] = function ($container) { return function ($request, $response, $exception) use($container) { //Format of exception to return $data = ['message' => $exception->getMessage()]; return $container->get('response')->withStatus(500)->withHeader('Content-Type', 'application/json')->write(json_encode($data)); }; }; //Register authentication container Dependency $container['auth'] = function ($container) { return new BB8\Emoji\Auth($container); }; //Initialize the slim app $app = new App($container); //Add middleware at app level $app->add('BB8\\Emoji\\Middleware:init'); //Index page $app->get('/', 'BB8\\Emoji\\Controllers\\UserController:index'); //Create new user $app->post('/signup', 'BB8\\Emoji\\Controllers\\UserController:create'); //Login Route $app->post('/auth/login', 'BB8\\Emoji\\Controllers\\UserController:login'); //Logout Route $app->get('/auth/logout', 'BB8\\Emoji\\Controllers\\UserController:logout')->add('BB8\\Emoji\\Middleware:authorize'); //List all emojis Route $app->get('/emojis', 'BB8\\Emoji\\Controllers\\EmojiController:index'); //Gets an emoji $app->get('/emojis/{id}', 'BB8\\Emoji\\Controllers\\EmojiController:show'); //Adds a new Emoji $app->post('/emojis', 'BB8\\Emoji\\Controllers\\EmojiController:create')->add('BB8\\Emoji\\Middleware:authorize'); //Updates an Emoji
<?php require_once dirname(dirname(__FILE__)) . '/vendor/autoload.php'; use Slim\App; use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware; $app = new App(['settings' => ['debug' => true, 'whoops.editor' => 'sublime']]); $app->add(new WhoopsMiddleware()); // Throw exception, Named route does not exist for name: hello $app->get('/', function ($request, $response, $args) { return $this->router->pathFor('hello'); }); // $app->get('/hello', function($request, $response, $args) { // $response->write("Hello Slim"); // return $response; // })->setName('hello'); $app->run();
/** * @runInSeparateProcess */ public function testExceptionErrorHandlerDisplaysErrorDetails() { $app = new App(['settings' => ['displayErrorDetails' => true]]); // Prepare request and response objects $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); $app->getContainer()['request'] = $req; $app->getContainer()['response'] = $res; $mw = function ($req, $res, $next) { throw new \Exception('middleware exception'); }; $app->add($mw); $app->get('/foo', function ($req, $res) { return $res; }); $resOut = $app->run(); $this->assertEquals(500, $resOut->getStatusCode()); $this->expectOutputRegex('/.*middleware exception.*/'); }
/** * Set up middleware * * @param ContainerInterface $container Container to prepare * @param SlimApp $app Application object * @param mixed $value Value for bootstrap */ private static function setupMiddleware(ContainerInterface $container, SlimApp $app, $value) { if ($value === null) { return; } $app->add($value); }
<?php require '../vendor/autoload.php'; use Slim\App; use Dotenv\Dotenv; $dotenv = new Dotenv(__DIR__); $dotenv->load(); //***** REMOVE SETTINGS WHEN NOT DEBUGGING ******************** $container = new \Slim\Container(['settings' => ['displayErrorDetails' => true]]); $app = new App($container); require 'dependencies.php'; require 'routes.php'; $app->add($container['logger-middleware']); $app->run();
/** * Add a middleware to the application. * @param mixed $middleware */ public function addMiddleware($middleware) { $this->app->add($middleware); }
<?php if (PHP_SAPI == 'cli-server') { // To help the built-in PHP dev server, check if the request was actually for // something which should probably be served as a static file $file = __DIR__ . preg_replace('#(\\?.*)$#', '', $_SERVER['REQUEST_URI']); if (is_file($file)) { return false; } } require __DIR__ . '/../vendor/autoload.php'; use Slim\App; use App\Loader\Kernel; use Slim\Middleware\DebugBar; use Slim\Routes\DebugBarRoutes; session_start(); // Instantiate the app $settings = (require __DIR__ . '/../config/settings.php'); $app = new App($settings); if ($app->getContainer()->get('settings')['debugbar'] === true) { $debugbar = new DebugBar(null, ['logger' => 'logger']); $app->add($debugbar); $routes = new DebugBarRoutes($app); $routes->registerRoutes(); } $kernel = new Kernel($app, $app->getContainer()); $kernel->registerServices(); $kernel->registerRoutes(); // Run app $app->run();
*/ $token = $tokenAuth->findToken($request); /** * Call authentication logic class */ $auth = new \app\Auth(); /** * Verify if token is valid on database * If token isn't valid, must throw an UnauthorizedExceptionInterface */ $auth->getUserByToken($token); }; /** * Add token authentication middleware */ $app->add(new TokenAuthentication(['path' => '/restrict', 'authenticator' => $authenticator])); /** * Public route example */ $app->get('/', function ($request, $response) { $output = ['msg' => 'It is a public area']; $response->withJson($output, 200, JSON_PRETTY_PRINT); }); /** * Restrict route example * Our token is "usertokensecret" */ $app->get('/restrict', function ($request, $response) { $output = ['msg' => 'It\'s a restrict area. Token authentication works!']; $response->withJson($output, 200, JSON_PRETTY_PRINT); });
require APPLICATION_PATH . "/../vendor/autoload.php"; $dotenv = new Dotenv\Dotenv(APPLICATION_PATH . '/../'); $dotenv->load(); if (!defined('SLIM_MODE')) { $mode = getenv('SLIM_MODE') ? getenv('SLIM_MODE') : 'production'; define('SLIM_MODE', $mode); } /** * init a session */ session_start(); $config = new Config(array(APPLICATION_PATH . '/app/config/global.php', APPLICATION_PATH . '/app/config/' . SLIM_MODE . '.php')); // Create Slim app $app = new App(['settings' => $config->all()]); // middleware setup $app->add(new TrailingSlash(false)); // true adds the trailing slash (false removes it) // Fetch DI Container $container = $app->getContainer(); /* * set up Monolog */ $log = new Logger('GraphStoryCom'); $log->pushHandler(new ErrorLogHandler(ErrorLogHandler::OPERATING_SYSTEM, $container->get('settings')['monolog.level'])); $container['logger'] = $log; /** * set Twig parser options * * @param \Interop\Container\ContainerInterface $c * * @return \Slim\Views\Twig
/** * Integration test IpRestrictMiddleware::_invoke() when the given IP is allowed. */ public function testIpAllow() { // Prepare the Request and the application. $app = new App(); // Setup a demo environment $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '127.0.0.2']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $headers->set('Accept', 'text/html'); $cookies = []; $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); $app->getContainer()['request'] = $req; $app->getContainer()['response'] = $res; // Set the options value. $this->options = ['error_code' => 403, 'exception_message' => 'NOT ALLOWED']; $app->add(new IpRestrictMiddleware($this->ipSet, false, $this->options)); $appMessage = 'I am In'; $app->get('/foo', function ($req, $res) use($appMessage) { $res->write($appMessage); return $res; }); $resOut = $app->run(); $body = (string) $resOut->getBody(); $this->assertEquals($appMessage, $body, 'The client is allowed to access the application.'); }
<?php require_once "vendor/autoload.php"; use App\Lib\Helpers\Config; use App\Lib\Helpers\RouteLoader; use Slim\App; use Slim\Container; $api = new App(new Container(Config::get('app.boot'))); // Here you can add all the middleware $api->add(new RKA\Middleware\IpAddress()); $api->add(new \CorsSlim\CorsSlim()); $routes = RouteLoader::load(); foreach ($routes as $route) { require_once $route; } $api->run();