Example #1
0
 /**
  * @dataProvider authenticationDataProvider
  */
 public function testRouteAuthentication($requestMethod, $path, $location, $hasIdentity, $identity, $httpStatus)
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => $requestMethod, 'PATH_INFO' => $path));
     $this->auth->expects($this->once())->method('hasIdentity')->will($this->returnValue($hasIdentity));
     $this->auth->expects($this->once())->method('getIdentity')->will($this->returnValue($identity));
     $app = new \Slim\Slim(array('debug' => false));
     $app->error(function (\Exception $e) use($app) {
         // Example of handling Auth Exceptions
         if ($e instanceof AuthException) {
             $app->response->setStatus($e->getCode());
             $app->response->setBody($e->getMessage());
         }
     });
     $app->get('/', function () {
     });
     $app->get('/member', function () {
     });
     $app->delete('/member/photo/:id', function ($id) {
     });
     $app->get('/admin', function () {
     });
     $app->map('/login', function () {
     })->via('GET', 'POST')->name('login');
     $app->add($this->middleware);
     ob_start();
     $app->run();
     ob_end_clean();
     $this->assertEquals($httpStatus, $app->response->status());
     $this->assertEquals($location, $app->response->header('location'));
 }
 public function testBestFormatWithPriorities()
 {
     \Slim\Environment::mock(array('ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'negotiation.priorities' => array('xml')));
     $s = new \Slim\Slim();
     $s->add(new ContentNegotiation());
     $s->run();
     $env = \Slim\Environment::getInstance();
     $bestFormat = $env['request.best_format'];
     $this->assertNotNull($bestFormat);
     $this->assertEquals('xml', $bestFormat);
 }
 /**
  * @param array $config
  * @return \Slim\Slim
  */
 public function dispatch($config)
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'HEAD', 'PATH_INFO' => '/'));
     $config['debug'] = false;
     // ignore pretty exceptions
     $slim = new \Slim\Slim($config);
     $manager = new \Slim\Middleware\SessionManager($slim);
     $manager->setDbConnection($this->capsule->getConnection());
     $session = new \Slim\Middleware\Session($manager);
     $slim->add($session);
     $slim->run();
     return $slim;
 }
 public function run()
 {
     $app = new \Slim\Slim();
     $this->app = $app;
     GetAllHeadersService::fixMissingFunction();
     $app->add(new \Widgeto\Middleware\Authorization(getallheaders(), array('^\\/$' => 'GET', '^\\/[^.]*.html$' => 'GET', '^\\/rest\\/login\\/$' => 'POST')));
     \dibi::connect(DatabaseConfigService::getConfig());
     \dibi::getSubstitutes()->{''} = getenv("TABLE_PREFIX");
     new \Widgeto\Rest\LoginRest($app);
     new \Widgeto\Rest\LogoutRest($app);
     new \Widgeto\Rest\PageRest($app);
     new \Widgeto\Rest\TemplateRest($app);
     new \Widgeto\Rest\FileRest($app);
     new \Widgeto\Rest\UserRest($app);
     new \Widgeto\Rest\HomeRest($app);
     $app->run();
 }
Example #5
0
function login()
{
    /* variables */
    $username = $_POST['username'];
    $username = strtoupper($username);
    //$password = $_POST['password'];
    $password = crypt($_POST['password'], 'rl');
    $mysqli = connectDB();
    if ($mysqli->connect_errno) {
        echo "ERROR : Connection failed: (" . $mysqli->connect_errno . ")" . $mysqli->connect_error;
    }
    /* check for someone elses session prior to starting page */
    if (isset($_SESSION['username']) && $_SESSION['username'] != $username) {
        if ($_SESSION['loggedIn'] != false) {
            echo 3;
        }
    } else {
        /************************************************************************
         * 					Search for users name and password
         ************************************************************************/
        /* Select user input for search */
        $result = "SELECT login FROM Reuse_User_Credentials WHERE login='******' && pw_hash='{$password}'";
        $product = $mysqli->query($result);
        $numReturned = $product->num_rows;
        /* if no results, there's no record of that username/password match */
        if ($numReturned == 0) {
            echo 0;
            // false back to javascript
        } else {
            $_SESSION['username'] = $username;
            $_SESSION['password'] = $password;
            $_SESSION['loggedIn'] = true;
            echo 1;
            // true back to javascript
            // start slims sessions
            require 'Slim/Slim.php';
            \Slim\Slim::registerAutoloader();
            $app = new \Slim\Slim(array('debug' => true));
            $app->add(new \Slim\Middleware\SessionCookie(array('path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'slim_session', 'secret' => 'personalized', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC)));
        }
        /* close it up */
        $mysqli->close();
    }
}
Example #6
0
 private function runAppPreFlight($action, $actionName, $mw = NULL, $headers = array())
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'OPTIONS', 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => 80, 'ACCEPT' => 'application/json', 'SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/' . $actionName));
     $app = new \Slim\Slim();
     if (isset($mw)) {
         $app->add($mw);
     }
     $app->delete('/:name', function ($name) use($app, $action) {
         if ($app->request->isHead()) {
             $app->status(204);
             return;
         }
         $app->contentType('application/json');
         $app->response->write(json_encode(array("action" => $action, "method" => "DELETE", "name" => $name)));
     });
     foreach ($headers as $key => $value) {
         $app->request->headers()->set($key, $value);
     }
     $app->run();
     return $app;
 }
Example #7
0
<?php

/**
 * Display errors
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);
/**
 * Default timezone
 */
date_default_timezone_set('UTC');
/**
 * Create app
 */
$app = new \Slim\Slim(array("view" => new \Slim\Views\Twig(), 'debug' => true));
$app->add(new \Slim\Middleware\SessionCookie(array('secret' => 'h5/4jc/)$3kfè4()487HD3d')));
// Make a new connection
use Illuminate\Database\Capsule\Manager as Capsule;
if (file_exists(ROOT . 'config' . DS . 'database.config.php')) {
    $capsule = new Capsule();
    $capsule->addConnection(include ROOT . "config" . DS . 'database.config.php');
    $capsule->bootEloquent();
    $capsule->setAsGlobal();
    $app->db = $capsule;
} else {
    die("<pre>Rename 'config/database.config.php.install' to 'config/database.config.php' and configure your connection</pre>");
}
/**
 * Extract settings from db
 */
$settings = Settings::where('id', '=', 1)->first();
Example #8
0
File: start.php Project: nob/joi
| Time to get an instance of Slim fired up. We're passing the $config
| array, which contains a bit more data than necessary, but helps keep
| everything simple.
|
*/
$admin_app = new \Slim\Slim(array_merge($config, array('view' => new Statamic_View())));
$admin_app->config = $config;
/*
|--------------------------------------------------------------------------
| Cookies for the Monster
|--------------------------------------------------------------------------
|
| Get the Slim Cookie middleware running the specified lifetime.
|
*/
$admin_app->add(new \Slim\Middleware\SessionCookie(array('expires' => $config['_cookies.lifetime'])));
/*
|--------------------------------------------------------------------------
| Check for Disabled Control Panel
|--------------------------------------------------------------------------
|
| We need to make sure the control panel is enabled before moving any
| further. You know, security and stuff.
|
*/
$admin_enabled = Config::get('_admin_enabled', true);
if ($admin_enabled !== true && strtolower($admin_enabled) != 'yes') {
    Statamic_View::set_templates(array_reverse(array("denied")));
    Statamic_View::set_layout("layouts/disabled");
    $admin_app->render(null, array('route' => 'disabled', 'app' => $admin_app));
    exit;
Example #9
0
<?php

function __autoload($class_name)
{
    echo $class_name;
    if (file_exists(BASE_PATH . '_app/libraries/' . $class_name . '.php')) {
        include_once BASE_PATH . '_app/libraries/' . $class_name . '.php';
    }
}
require_once BASE_PATH . '_app/function.php';
require_once BASE_PATH . '_app/model.php';
require_once BASE_PATH . '_app/libraries/Yacms.php';
require_once BASE_PATH . '_app/libraries/Tiny.php';
$app = new \Slim\Slim();
$app->config = Yacms::loadConfigs();
foreach ($app->config as $key => $value) {
    $app->config($key, $value);
}
$template_engine = $app->config['template_engine'];
if (file_exists(BASE_PATH . '/_app/libraries/template_engine/' . $template_engine . '.php')) {
    require_once BASE_PATH . '/_app/libraries/template_engine/' . $template_engine . '.php';
}
$app->view(new $template_engine());
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware());
$app->add(new \Slim\Middleware\SessionCookie(array('expires' => $app->config['cookies.lifetime'], 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'session', 'secret' => $app->config['session_secret'], 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC)));
$app->model = new DB();
require_once __DIR__ . '/admin_routes.php';
require_once __DIR__ . '/routes.php';
return $app;
Example #10
0
<?php

require 'vendor/autoload.php';
//set timezone
date_default_timezone_set('America/Denver');
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$app = new \Slim\Slim(array('view' => new \Slim\Views\Twig()));
$app->add(new \Slim\Middleware\SessionCookie());
$view = $app->view();
$view->parserOptions = array('debug' => true);
$view->parserExtensions = array(new \Slim\Views\TwigExtension());
$app->get('/', function () use($app) {
    $app->render('about.twig');
    //starts by looking through templates folder
})->name('home');
$app->get('/contact', function () use($app) {
    $app->render('contact.twig');
    //starts by looking through templates folder
})->name('contact');
$app->post('/contact', function () use($app) {
    $name = $app->request->post('name');
    $email = $app->request->post('email');
    $msg = $app->request->post('msg');
    if (!empty($name) && !empty($email) && !empty($msg)) {
        $cleanName = filter_var($name, FILTER_SANITIZE_STRING);
        $cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
        $cleanMsg = filter_var($msg, FILTER_SANITIZE_STRING);
    } else {
        //message the user that there's a problem
        $app->flash('fail', 'All fields are required.');
<?php

require_once '../vendor/autoload.php';
require_once '../src/RatingsDAO.php';
require_once '../src/JsonResponse.php';
// Prepare app
$app = new \Slim\Slim();
$corsOptions = array("origin" => "*", "maxAge" => 1728000);
$app->add(new \CorsSlim\CorsSlim($corsOptions));
$app->add(new JsonResponse());
$app->notFound(function () use($app) {
    $app->log->error('Not Found', array('path' => $app->request()->getPath()));
    $app->halt(404, json_encode(array('status' => 404, 'message' => 'not found')));
});
// Create monolog logger and store logger in container as singleton
$app->container->singleton('log', function () {
    $log = new \Monolog\Logger('ss-rating');
    $log->pushHandler(new \Monolog\Handler\StreamHandler('../logs/app.log', \Monolog\Logger::DEBUG));
    return $log;
});
function getAllRatings()
{
    $app = \Slim\Slim::getInstance();
    try {
        $app->response->write(json_encode(RatingsDAO::getAll(), JSON_FORCE_OBJECT));
        return json_encode($app->response->getBody());
    } catch (Exception $e) {
        $app->response->setStatus(404);
        $app->response->setBody(getErrorMessage($e));
        return json_encode($app->response->getBody());
    }
Example #12
0
    {
        $this->layout = $layout;
    }
    public function render($template, $data = NULL)
    {
        if ($this->layout) {
            $_html = parent::render($template);
            $this->set('_html', $_html);
            $template = $this->layout;
            $this->layout = null;
        }
        return parent::render($template);
    }
}
$app = new \Slim\Slim(array('view' => new Isucon5View(), 'db' => array('host' => getenv('ISUCON5_DB_HOST') ?: 'localhost', 'port' => (int) getenv('ISUCON5_DB_PORT') ?: 3306, 'username' => getenv('ISUCON5_DB_USER') ?: 'root', 'password' => getenv('ISUCON5_DB_PASSWORD'), 'database' => getenv('ISUCON5_DB_NAME') ?: 'isucon5q'), 'cookies.encrypt' => true));
$app->add(new \Slim\Middleware\SessionCookie(array('secret' => getenv('ISUCON5_SESSION_SECRET') ?: 'beermoris', 'expires' => 0)));
function abort_authentication_error()
{
    global $app;
    $_SESSION['user_id'] = null;
    $app->view->setLayout(null);
    $app->halt(401, $app->view->fetch('login.php', array('message' => 'ログインに失敗しました')));
}
function abort_permission_denied()
{
    global $app;
    $app->halt(403, $app->view->fetch('error.php', array('message' => '友人のみしかアクセスできません')));
}
function abort_content_not_found()
{
    global $app;
Example #13
0
<?php

error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
require 'vendor/autoload.php';
$db = new PDO('sqlite:db.sqlite3');
$app = new \Slim\Slim();
$app->view(new \JsonApiView());
$app->add(new \JsonApiMiddleware());
define('secret', 'secret');
$app->add(new \Slim\Middleware\JwtAuthentication(array('secure' => false, 'path' => '/api/members', 'secret' => constant('secret'))));
$app->config('debug', false);
$app->get('/', function () use($app) {
    $app->render(200, array('msg' => 'Welcome to Jom Web Johor!'));
});
$app->get('/jwj', function () use($app) {
    $key = constant('secret');
    $token = array("facebook" => "https://facebook.com/groups/jomwebjohor", "github" => "https://github.com/jomwebjohor");
    $jwt = JWT::encode($token, $key);
    $app->render(200, array('token' => $jwt));
});
$app->get('/api', function () use($app) {
    $app->render(200, array('msg' => 'Welcome to my json API!'));
});
$app->get('/api/members', function () use($app, $db) {
    // Return all members
    $members = $db->query("SELECT * FROM members;")->fetchAll(PDO::FETCH_CLASS);
    if ($members) {
        $app->response->setStatus(200);
        $app->response->headers->set('Content-Type', 'application/json');
        $app->response->setBody(json_encode($members));
    } else {
Example #14
0
|
| The first thing we will do is create a new Slim application instance
| which serves as the "glue" for all the components of RedSlim.
|
*/
\Slim\Slim::registerAutoloader();
// Instantiate application
$app = new \Slim\Slim(require_once ROOT . 'app/config/app.php');
//Nombre del sitio:
$app->setName('Site-Template');
// For native PHP session
session_cache_limiter(false);
session_start();
// For encrypted cookie session
//*/
$app->add(new \Slim\Middleware\SessionCookie(array('expires' => '20 minutes', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'app_session_name', 'secret' => md5('site-template'), 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC)));
//*/
/*
|--------------------------------------------------------------------------
| Autenticacion de usuarios
|--------------------------------------------------------------------------
|
| Funcion $authentitace
| Recibe:  $app, $role
|   $app:  SLIM $app
|   $role: El role o nivel del usuario
|
*/
$authenticate = function ($app, $role) {
    return function () use($app, $role) {
        $env = $app->environment();
});
# 404 handler inside app()
$app->notFound(function () use($app) {
    $app->twig->display('error.php');
});
# Exception handler inside app()
$app->error(function (\Exception $e) use($app) {
    $app->twig->display('error.php');
});
# auth
if (!isset($_GET['client-id'])) {
    # Basic Authentication /vassarapi
    # use an authenticator() ? github/tuupola/slim-basic-auth
    $user_array = array("user-acct2" => "user-acct2", "user-acct1" => "user-acct1");
    $users = array("users" => $user_array);
    $app->add(new \Slim\Middleware\HttpBasicAuthentication(["path" => "/vassarapi", "realm" => "Protected", "authenticator" => new ArrayAuthenticator($users)]));
} else {
    if (!sigValidate::validSignature(consumer::$clientId, $_GET['client-signature'], $_GET['timestamp'])) {
        throw new Exception('invalid login attempt');
    }
}
#
# for each valid endpoint
foreach ($_SESSION['j']['endpoints'] as $endpoint) {
    # for each valid request type inside that endpoint ['get', 'post', 'put', 'delete']
    foreach ($endpoint['http'] as $http) {
        # does consumer have authority on this service?
        foreach (consumer::$clientScope as $clientScope) {
            foreach ($clientScope['control'] as $clientScopeControl) {
                # match in clients scope list and current endpoint/req type; route the request in app()
                if ($clientScope['endpoint'] === $endpoint['uri'] && $clientScopeControl['method'] === $_SERVER['REQUEST_METHOD']) {
Example #16
0
require 'app/config.php';
// Autoload
require 'vendor/autoload.php';
// RedBeanPHP alias fix
class R extends RedBeanPHP\Facade
{
}
// RedBeanPHP setup
R::setup('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
R::freeze(DB_FREEZE);
// Slim app instance
$app = new \Slim\Slim(['view' => new EnhancedView()]);
// Slim Config
$app->config(['templates.path' => 'app/views', 'debug' => APP_DEBUG]);
// Add support for JSON posts
$app->add(new \Slim\Middleware\ContentTypes());
// JSON view function
function APIrequest()
{
    $app = \Slim\Slim::getInstance();
    $app->view(new \JsonView());
    $app->view->clear();
}
// Set webroot for portable
$app->hook('slim.before', function () use($app) {
    $app->wroot = $app->request->getUrl() . $app->request->getRootUri();
    $app->view()->appendData(['wroot' => $app->wroot]);
});
// Load routes
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname(__FILE__) . '/routes/'));
foreach ($iterator as $file) {
Example #17
0
$output = "[%datetime%] [%level_name%] [%extra%] : %message% %context%\n";
$formatter = new Monolog\Formatter\LineFormatter($output);
$streamToFile->setFormatter($formatter);
$streamToFile->pushProcessor(function ($record) use($config) {
    if ($config['enviroment'] == 'development') {
        $record['extra']['connection'] = 'testing';
    } else {
        $record['extra']['connection'] = 'default';
    }
    return $record;
});
$handlers[] = $streamToFile;
$logger_writer = new \Flynsarmy\SlimMonolog\Log\MonologWriter(array('handlers' => $handlers, 'processors' => array(new Monolog\Processor\UidProcessor(), new Monolog\Processor\WebProcessor($_SERVER))));
$app = new \Slim\Slim(array('mode' => $config['enviroment'], 'log.level' => \Slim\Log::DEBUG, 'log.enabled' => true, 'log.writer' => $logger_writer, 'templates.path' => '../templates'));
$app->config('databases', $config['databases']);
$app->add(new \BitPrepared\Slim\Middleware\EloquentMiddleware());
$corsOptions = array("origin" => "*");
$app->add(new \CorsSlim\CorsSlim($corsOptions));
$app->hook('slim.before.router', function () use($app) {
    $req = $app->request;
    $allGetVars = $req->get();
    $allPostVars = $req->post();
    $allPutVars = $req->put();
    $vars = array_merge($allGetVars, $allPostVars);
    $vars = array_merge($vars, $allPutVars);
    $srcParam = json_encode($vars);
    $srcUri = $req->getRootUri();
    $srcUrl = $req->getResourceUri();
    //$app->log->info(@Kint::dump( $srcUrl ));
    $app->log->debug('REQUEST : ' . var_export($_REQUEST, true));
    // Sono stati messi nel log dal logger
Example #18
0
File: init.php Project: buisoft/wob
<?php

session_cache_limiter(false);
session_start();
ob_start();
ini_set('display_errors', 'On');
define('INC_ROOT', dirname(__DIR__));
require INC_ROOT . '/vendor/autoload.php';
$app = new Slim\Slim(['mode' => file_get_contents(INC_ROOT . '/app/config/env/mode.php'), 'view' => new Slim\Views\Twig(), 'templates.path' => INC_ROOT . '/views/']);
$app->add(new BuiSoft\Middleware\BeforeMiddleware());
$app->configureMode($app->config('mode'), function () use($app) {
    $app->config = Noodlehaus\Config::load(INC_ROOT . "/app/config/env/{$app->mode}.php");
});
require INC_ROOT . '/app/config/database.php';
require INC_ROOT . '/app/filters/authentication.php';
require INC_ROOT . '/app/config/api.php';
require INC_ROOT . '/app/config/routes.php';
require INC_ROOT . '/app/config/queue.php';
require INC_ROOT . '/app/config/session.php';
require INC_ROOT . '/app/config/cache.php';
require INC_ROOT . '/app/config/languages.php';
require INC_ROOT . '/app/config/app.php';
$view = $app->view();
$view->parserOptions = ['debug' => $app->config->get('twig.debug')];
$view->parserExtensions = [new Slim\Views\TwigExtension()];
Example #19
0
    public function call()
    {
        $app = $this->app;
        // Get request path and media type
        // Run inner middleware and application
        $this->next->call();
        $reqMediaType = $app->request->getMediaType();
        $reqIsAPI = (bool) preg_match('|^/api/.*$|', $app->request->getPath());
        if ($reqMediaType === 'application/json' || $reqIsAPI) {
            $app->response->headers->set('Content-Type', 'application/json');
            $app->response->headers->set('Access-Control-Allow-Methods', '*');
            $app->response->headers->set('Access-Control-Allow-Origin', '*');
        } else {
            $app->response->headers->set('Content-Type', 'text/html');
        }
    }
}
/* General functions */
// Create new Plates instance and map template folders
$templates = new League\Plates\Engine('templates');
$templates->addFolder('partials', 'templates/partials');
// Initalize Slim instance
$app = new \Slim\Slim(array('debug' => defined('GENERAL_DEBUG') && GENERAL_DEBUG === true ? true : false));
$app->add(new \APIheaderMiddleware());
// Set routes
$app->get('/', 'dashboard');
$app->get('/api', 'routeGetOverview');
$app->get('/api/warranties', 'routeGetWarranties');
$app->get('/api/warranties/:id', 'routeGetWarranty');
// Run application
$app->run();
Example #20
0
<?php

/**
 * Copyright (C) 2015 FeatherBB
 * based on code by (C) 2008-2015 FluxBB
 * and Rickard Andersson (C) 2002-2008 PunBB
 * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
 */
// Start a session for flash messages
session_cache_limiter(false);
session_start();
error_reporting(E_ALL);
// Let's report everything for development
ini_set('display_errors', 1);
// Load Slim Framework
require 'vendor/autoload.php';
// Instantiate Slim and add CSRF
$feather = new \Slim\Slim();
$feather->add(new \FeatherBB\Middleware\Csrf());
$feather_settings = array('config_file' => 'featherbb/config.php', 'cache_dir' => 'cache/', 'debug' => 'all');
// 3 levels : false, info (only execution time and number of queries), and all (display info + queries)
$feather->add(new \FeatherBB\Middleware\Auth());
$feather->add(new \FeatherBB\Middleware\Core($feather_settings));
// Load the routes
require 'featherbb/routes.php';
// Run it, baby!
$feather->run();
Example #21
0
 /**
  * Test add middleware
  *
  * This asserts that middleware are queued and called
  * in sequence. This also asserts that the environment
  * variables are passed by reference.
  */
 public function testAddMiddleware()
 {
     $this->expectOutputString('FooHello');
     $s = new \Slim\Slim();
     $s->add(new CustomMiddleware());
     //<-- See top of this file for class definition
     $s->get('/bar', function () {
         echo 'Foo';
     });
     $s->run();
     $this->assertEquals('Hello', $s->response()->header('X-Slim-Test'));
 }
 /**
  * Test parses request body based on media-type only, disregarding
  * any extra content-type header parameters
  */
 public function testParsesRequestBodyWithMediaType()
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4', 'CONTENT_LENGTH' => 13, 'slim.input' => '{"foo":"bar"}'));
     $s = new \Slim\Slim();
     $s->add(new \Slim\Middleware\ContentTypes());
     $s->run();
     $body = $s->request()->getBody();
     $this->assertTrue(is_array($body));
     $this->assertEquals('bar', $body['foo']);
 }
Example #23
0
    }
    if ($hours == 1) {
        $hours = $hours . " hour";
    } else {
        $hours = $hours . " hours";
    }
    return $hours . ", " . $min;
}
/**
 * Helper function for default statustime.
 */
function default_status_time()
{
    return new DateTime('1970-01-01', new DateTimeZone('UTC'));
}
$app->add(new \Slim\Middleware\SessionCookie(array('expires' => '60 minutes', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'postmortem', 'secret' => 'PMS_R_US', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC)));
$app->add(new AssetVersionMiddleware());
/*
 * Now include all routes and libraries for features before actually running the app
 */
foreach ($config['feature'] as $feature) {
    if ($feature['enabled'] == "on") {
        $app->log->debug("Including Feature {$feature['name']}");
        include 'features/' . $feature['name'] . '/lib.php';
        include 'features/' . $feature['name'] . '/routes.php';
    }
}
// set admin info on the environment array
// so it's available to our request handlers
$env = $app->environment;
$env['admin'] = MorgueAuth::get_auth_data();
Example #24
0
File: index.php Project: Zilus/cms
include_once '../lib/database.class.php';
require '../lib/Slim/Slim.php';
$database = new Database();
//auth
$sql = "SELECT * FROM settings WHERE settings_desc=:settings_desc";
$database->query($sql);
$database->bind(':settings_desc', "apiKey");
$row = $database->single();
$user = $row['settings_value'];
$passwd = $row['settings_extra'];
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
// Authorization: Basic OXR1Y3VTTXUwSjpiTEc3NUJ2bVpM
$app->add(new \Slim\Middleware\HttpBasicAuthentication(["users" => [$user => $passwd], "error" => function ($arguments) use($app) {
    $response["status"] = "error";
    $response["message"] = $arguments["message"];
    $app->response->write(json_encode($response, JSON_UNESCAPED_SLASHES));
}]));
$app->get('/users', 'getUsers');
$app->get('/user/:user_id', 'getUsersId');
$app->put('/update/:user_id', 'updateUser');
$app->post('/insert', 'insertUser');
$app->delete('/delete/:user_id', 'deleteUser');
/* api Keys */
function validateKey($apiKey)
{
    /* function hash_password($password, $salt) {
    		$hash = hash_hmac("md5", $salt, $password);
    		for ($i = 0; $i < 1000; $i++) {
    			$hash = hash_hmac("md5", $hash, $password);
    		}
Example #25
0
<?php

use Illuminate\Encryption\Encrypter;
require_once 'vendor/autoload.php';
/**
 * Illuminate/encryption
 *
 * Requires: symfony/security-core
 *
 * @source https://github.com/illuminate/encryption
 */
$app = new \Slim\Slim();
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware());
/*
 * This key is used by the Illuminate encrypter service and should be set
 * to a random, 16-character string, otherwise these encrypted strings
 * will not be safe. Please do this before deploying an application!
 */
$key = '1hs8heis)2(-*3d.';
$app->get('/', function () use($key) {
    $encrypter = new Encrypter($key);
    // Encrypt Hello World string
    $encryptedHelloWorld = $encrypter->encrypt('Hello World');
    echo "Here is the encrypted string: <hr>" . $encryptedHelloWorld . "<br><br><br>";
    // Decrypt encrypted string
    $decryptedHelloWorld = $encrypter->decrypt($encryptedHelloWorld);
    echo "Here is the decrypted string: <hr>" . $decryptedHelloWorld . "<br><br>";
});
$app->run();
Example #26
0
    } else {
        $year = date('Y', $config['app.begin_dev']) . '-' . date('Y');
    }
    $config['app.year'] = $year;
    return $config;
});
// SwiftMailer
$app->container->set('mailer', function () {
    $transport = Swift_SmtpTransport::newInstance('smtp.googlemail.com', 465, 'ssl')->setUsername('jesus')->setPassword('godisalie');
    $mailer = Swift_Mailer::newInstance($transport);
    return $mailer;
});
// Exceptions
$whoops = new \Whoops\Run();
$whoops->pushHandler(new Whoops\Handler\PrettyPageHandler());
$whoops->register();
// Database
$app->container->singleton('db', function () use($app) {
    $database = $app->config['database'];
    $pdo = new \PDO('mysql:host=' . $database['host'] . ';' . 'dbname=' . $database['dbname'] . ';', $database['user'], $database['pwd']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec('SET CHARACTER SET utf8');
    return $pdo;
});
// Middlewares
$app->add(new Bugisoft\Middleware\CsrfMiddleware());
// CSRF
$view = $app->view();
$view->setTemplatesDirectory('../app/views');
$view->parserExtensions = array(new \Slim\Views\TwigExtension(), new Twig_Extension_Debug());
require 'routes.php';
Example #27
0
 /**
  * Test exception when adding circular middleware queues
  *
  * This asserts that the same middleware can NOT be queued twice (usually by accident).
  * Circular middleware stack causes a troublesome to debug PHP Fatal error:
  *
  * > Fatal error: Maximum function nesting level of '100' reached. aborting!
  */
 public function testFailureWhenAddingCircularMiddleware()
 {
     $this->setExpectedException('\\RuntimeException');
     $middleware = new CustomMiddleware();
     $s = new \Slim\Slim();
     $s->add($middleware);
     $s->add(new CustomMiddleware());
     $s->add($middleware);
     $s->run();
 }
Example #28
0
<?php

chdir(__DIR__ . '/../../../');
ini_set('session.use_cookies', 0);
require 'vendor/autoload.php';
\Caco\MiniAR::setDefaultPdo($pdo = new \PDO('sqlite:database/app.sqlite3'));
$pdo->exec('PRAGMA foreign_keys = ON');
$app = new \Slim\Slim();
$app->view(new \Caco\Slim\JsonView());
$app->add($auth = new \Caco\Slim\Auth\Basic());
$auth->setRealm('Caco Cloud');
$app->group('/password', function () use($app) {
    $app->get('/:key/:id', '\\Caco\\Password\\REST:one')->conditions(['id' => '\\d+']);
    $app->get('/:key', '\\Caco\\Password\\REST:all');
    $app->post('/:key', '\\Caco\\Password\\REST:add');
    $app->delete('/:key/:id', '\\Caco\\Password\\REST:delete')->conditions(['id' => '\\d+']);
    $app->put('/:key/:id', '\\Caco\\Password\\REST:edit')->conditions(['id' => '\\d+']);
});
$app->group('/bookmark', function () use($app) {
    $app->get('/:id', '\\Caco\\Bookmark\\REST:one')->conditions(['id' => '\\d+']);
    $app->get('', '\\Caco\\Bookmark\\REST:all');
    $app->post('', '\\Caco\\Bookmark\\REST:add');
    $app->delete('/:id', '\\Caco\\Bookmark\\REST:delete')->conditions(['id' => '\\d+']);
    $app->put('/:id', '\\Caco\\Bookmark\\REST:edit')->conditions(['id' => '\\d+']);
});
$app->group('/config', function () use($app) {
    $app->get('/:key', '\\Caco\\Config\\REST:one');
    $app->get('', '\\Caco\\Config\\REST:all');
    $app->post('', '\\Caco\\Config\\REST:add');
    $app->delete('/:key', '\\Caco\\Config\\REST:delete');
    $app->put('/:key', '\\Caco\\Config\\REST:edit');
Example #29
0
<?php

include 'ChromePhp.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../models/productMgr.php';
require_once __DIR__ . '/../models/blogMgr.php';
require_once __DIR__ . '/../models/mailer.php';
$oProductMgr = new ProductMgr();
$oBlogMgr = new BlogMgr();
$oApp = new \Slim\Slim(array('templates.path' => __DIR__ . '/../views'));
date_default_timezone_set('Canada/Saskatchewan');
$oApp->add(new \Slim\Middleware\SessionCookie(array('expires' => '60 minutes', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'slim_session', 'secret' => 'CHANGE_ME', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC)));
/***
 * Home page
***/
$oApp->get('/', function () use($oApp, $oProductMgr) {
    $oApp->render('home.phtml', array('title' => '', 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => 'Action', 'productsInGenre' => $oProductMgr->getProductsByGenre('Action'), 'featuredProducts' => $oProductMgr->getFeaturedProducts()));
});
$oApp->get('/home/:genre', function ($sGenre) use($oApp, $oProductMgr) {
    $oApp->render('home.phtml', array('title' => $sGenre, 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => $sGenre, 'productsInGenre' => $oProductMgr->getProductsByGenre($sGenre), 'featuredProducts' => $oProductMgr->getFeaturedProducts()));
});
// called when user search for items
$oApp->post('/search', function () use($oApp, $oProductMgr) {
    $sKeywords = $oApp->request()->post('keywords');
    $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords));
});
$oApp->get('/search', function () use($oApp, $oProductMgr) {
    $sKeywords = $oApp->request->params('keywords');
    //ChromePhp::info($sKeywords);
    //die();
    $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords));
Example #30
0
    $dbpass = "******";
    $dbname = "test";
    $dbh = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}
/**
 * Instantiate a Slim application
 * Enabling debug for testing. 
 */
//$app = new \Slim\Slim();
$app = new \Slim\Slim(array('debug' => true));
/**
 * Enabling HTTP basic authentication
 */
$app->add(new \Slim\Middleware\HttpBasicAuthentication(["secure" => false, "users" => ["test" => "test"]]));
/**
 * Homepage for root directory
 * Will later include the documentation of the REST Api
 */
$app->get('/', function () {
    echo "Hello";
});
/**
 * Route to get a list of temperature entries
 */
$app->get('/temperature', 'getLastTemperature');
/**
 * Route to get one specific temperature entry
 */
$app->get('/temperature/:id', 'getTemperature');