Example #1
0
function authorize()
{
    return function () {
        $app = new \Slim\Slim();
        if (empty($_SESSION['user'])) {
            $app->halt(401, 'You shall not pass!');
        }
    };
}
Example #2
0
<?php

require 'vendor/autoload.php';
include 'conf/orm.php';
$app = new \Slim\Slim();
$app->response->headers->set('Content-Type', 'application/json');
//ユーザ情報API
$app->post('/api/user', function () use($app) {
    $data = json_decode($app->request->getBody(), true);
    //バリデーション
    if ($data['idfv'] === "" || strlen($data['idfv']) !== 36 || $data['timestamp'] === "") {
        $app->halt(400);
    }
    try {
        $user = ORM::for_table('user')->find_one($data['idfv']);
    } catch (Exception $e) {
        $app->halt(500, $e->getMessage());
    }
    if ($user) {
        $app->halt(400);
    }
    try {
        $user = ORM::for_table('user')->create();
        $user->set($data);
        $user->save();
    } catch (Exception $e) {
        $app->halt(500, $e->getMessage());
    }
    $app->halt(200);
});
$app->put('/api/user', function () use($app) {
 /**
  * Test halt does not leave output buffers open
  */
 public function testHaltDoesNotLeaveOutputBuffersOpen()
 {
     $level_start = ob_get_level();
     $s = new \Slim\Slim();
     $s->get('/bar', function () use($s) {
         $s->halt(500, '');
     });
     $s->run();
     $this->assertEquals($level_start, ob_get_level());
 }
Example #4
0
        $app->render('app.html');
    });
    $app->post('procparams', function () use($app) {
        $entry = json_decode($app->request()->getBody());
        echo getInputParams($entry);
    });
    $app->get('api', function () use($app) {
        $app->render('../../api/api.json');
    });
    $app->post('api', function () use($app) {
        $json = $app->request()->getBody();
        $data = json_decode($json);
        // TODO: CHECK INPUT FOR VALIDITY
        // GENERATE SQL CODE FOR PROCEDURES
        $mysqli = getConnection_mysqli();
        // Set the procedures according to the existing API when an error occurs
        if (!createProcedures($mysqli, $data)) {
            if (file_exists("../api/api.json")) {
                $api = json_decode(file_get_contents("../api/api.json"));
                createProcedures($mysqli, $api);
            }
            $app->halt(400, "Stored procedure command failed: (" . $mysqli->errno . ") " . $mysqli->error);
        }
        // Make a backup
        if (file_exists("../api/api.json")) {
            copy("../api/api.json", "../api/api_" . date("ymd_His") . ".json");
        }
        file_put_contents("../api/api.json", json_encode($data, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES));
    });
});
$app->run();
<?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 #6
0
//使用 \Slim\Middleware\SessionCookie 中间件把会话数据储存到经过加密和散列的 HTTP cookies中
$app->add(new \Slim\Middleware\SessionCookie(array('expires' => '20 minutes', 'path' => '/', 'domain' => DOMAIN, 'secure' => false, 'httponly' => true, 'name' => 'data_session', 'secret' => 'CHANGE_ME', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC)));
//权限判断
$app->hook('slim.before.dispatch', function () use($app) {
    $req = $app->request();
    // 将POST的UTCC的放行,在逻辑中检查是否合理
    if (strpos($_SERVER['REQUEST_URI'], 'utcc') > 0) {
        return true;
    }
    if (strpos($_SERVER['REQUEST_URI'], 'test') !== FALSE) {
        return true;
    }
    if (isset($_SESSION['username']) && $_SESSION['username'] == $req->params('username') && isset($_SESSION['token']) && $_SESSION['token'] == $req->params('token') && isset($_SESSION['url']) && in_array(substr($req->getPath(), strlen(API_PREFIX)), $_SESSION['url'])) {
        return true;
    }
    //wrong parameter error
    $err_res = json_encode(['meta' => ['status' => 401, 'msg' => 'you are not permitted to access this interface. wrong parameter']]);
    $app->halt(401, $err_res);
});
//单例mysql
$db_config = (require_once CODE_BASE . 'configs/mysql.php');
$app->container->singleton('db_ku6_report', function () use($db_config) {
    return new Mysql($db_config['ku6_report']);
});
$app->container->singleton('db_new_utcc', function () use($db_config) {
    return new Mysql($db_config['new_utcc']);
});
require_once "hl_index.php";
require_once "trend_index.php";
require_once "utcc_index.php";
$app->run();
Example #7
0
             $query = 'SELECT category, element, url FROM FileContent WHERE lan = ?';
             $sql_file = $db->prepare($query);
             $sql_file->bindParam(1, $lan);
             $sql_file->execute();
             $sql_file->setFetchMode(PDO::FETCH_OBJ);
             /*$query = 'SELECT lan, language FROM Language WHERE toggle != 0 AND toggle IS NOT NULL';
               $sql_lan = $db->prepare($query);
               $sql_lan->execute();
               $sql_lan->setFetchMode(PDO::FETCH_OBJ);*/
             //$language = $sql_lan->fetchAll();
             $textcontent = $sql_text->fetchAll();
             $filecontent = $sql_file->fetchAll();
         } catch (Exception $e) {
             setupMySql($db);
             $app->redirect($app->urlFor('getContent'));
             $app->halt(503, json_encode(['type' => 'Error', 'title' => 'Oops, something went wrong!', 'message' => $e->getMessage()]));
         } finally {
             $db = null;
         }
     } else {
         $app->halt(503, json_encode(['type' => 'Error', 'title' => 'Oops, sadsomething went wrong!', 'message' => 'No database connection']));
     }
     $app->response->status(200);
     $app->response->body(json_encode(['lan' => $lan, 'textContent' => $textcontent, 'fileContent' => $filecontent]));
 })->via('GET', 'PUT', 'POST', 'DELETE')->name('getFinished');
 $app->map('/get/modified', function () use($app) {
     if ($app->getCookie('aco-lan') !== null) {
         $lan = $app->getCookie('aco-lan');
     }
     if (($db = connectToMySql()) !== false) {
         try {
Example #8
0
    }
}
define("CDN_URL", getCDNPath());
require 'vendor/autoload.php';
require 'models/TaxCalculator.php';
require 'models/StateTaxCalculator.php';
require 'models/FederalTaxCalculator.php';
$state_calculator = new StateTaxCalculatorModel();
$federal_calculator = new FederalTaxCalculatorModel();
$app = new \Slim\Slim();
// Parse the response and display it.
$app->hook('respond', function ($response) use($app) {
    $app->response->header('Access-Control-Allow-Origin', '*');
    $app->response->headers->set('Content-Type', 'application/json');
    if ($response['success'] === false) {
        $app->halt(400, "{\"success\": false, \"reason\": \"" . $response['reason'] . "\"}");
    } else {
        echo json_encode($response['data']);
    }
});
$app->get('/v1/federal/:year/', function ($year) use($app, $federal_calculator) {
    $response = $federal_calculator->get_federal_data($year);
    $app->applyHook('respond', $response);
});
$app->get('/v1/state/:state/:year/', function ($year, $state) use($app, $state_calculator) {
    $response = $state_calculator->get_state_data($year, $state);
    $app->applyHook('respond', $response);
});
$app->post('/v1/calculate/:year/', function ($year) use($app, $state_calculator, $federal_calculator) {
    $pay_rate = $app->request->post('pay_rate');
    $pay_periods = $app->request->post('pay_periods') == false ? 1 : $app->request->post('pay_periods');
Example #9
0
use Flywheel\Loader;
define('ROOT_DIR', dirname(dirname(__DIR__)));
define('MEDIA_DIR', ROOT_DIR . '/public/media');
define('PUBLIC_DIR', ROOT_DIR . '/public/');
require_once __DIR__ . '/../../vendor/autoload.php';
Loader::addNamespace('SFS', ROOT_DIR . '/library/');
Loader::register();
$app = new \Slim\Slim(array('debug' => true, 'mode' => 'development'));
$app->get('/cache/:function/:dimension/:path+', function ($function, $dimension, $path) use($app) {
    $path = implode(DIRECTORY_SEPARATOR, $path);
    $public_dir = rtrim(dirname(MEDIA_DIR), '/');
    //check file exists
    if (!file_exists($public_dir . '/' . $path)) {
        //throw 404
        $app->halt(404, 'File not found!');
    }
    try {
        $dimension = explode('-', $dimension);
        $params = \SFS\Image\Transform::hydrateParameters($dimension);
        $imgTransform = new \SFS\Image\Transform($public_dir . '/' . $path);
        if (!method_exists($imgTransform, $function)) {
            $app->halt(400, 'Not support API "' . $function . '"');
            exit;
        }
        $imgTransform->{$function}($params);
        $dimension = implode('-', $dimension);
        $output = "{$public_dir}/thumbs/cache/{$function}/{$dimension}/{$path}";
        \SFS\Upload::makeFileStorageDir($output);
        $imgTransform->save($output);
        $imgTransform->display();
Example #10
0
<?php

// App dependecies.
require 'vendor/autoload.php';
require 'models/ModelAdapter.php';
require 'models/ModelBase.php';
require 'models/CompanyModel.php';
require 'models/ContactModel.php';
// Create instance of the app on request.
// Define app configuration.
$app = new \Slim\Slim(array('mode' => 'development', 'debug' => true, 'log.enabled' => true, 'cookies.encrypt' => true, 'cookies.secret_key' => 'rMtab79lIsoAbQLryIzQqJHBFRamvvG4oP1FWa26RwsD3zcyFVSiXcRa2HA7QOO'));
// Default Routes
$app->get('/', function () use($app) {
    $auth = array();
    $auth['status'] = "Not Authorized.";
    $app->halt(403, json_encode($auth));
});
// Define API Service Routes
require 'services/ContactService.php';
ContactService::handle_routes($app);
// Run app.
$app->run();
Example #11
0
    $results = $passwd->fetchAll();
    if (count($results) > 0) {
        // valid email
        if (password_verify($password, $results[0]['password'])) {
            unset($results[0]['password']);
            // valid password
            $_SESSION['loggedin'] = true;
            $success = array("success" => array("text" => "Log in successful"), "data" => json_encode($results));
            echo json_encode($success);
            return;
        }
    }
    // Halt if invalid email or password
    $error = array("error" => array("text" => "Username or Password does not exist, is not filled in, or is not correct"));
    $app->response->headers->set('Content-Type', 'application/json');
    $app->halt(401, json_encode($error));
});
//LOGOUT
$app->get('/logout', function () use($app) {
    if (!isset($_SESSION['loggedin'])) {
        $error = array("error" => array("text" => "There is nobody logged in!"));
        $app->response->headers->set('Content-Type', 'application/json');
        echo json_encode($error);
    } else {
        $_SESSION['loggedin'] = false;
        $success = array("success" => array("text" => "You are now logged out!"));
        $app->response->headers->set('Content-Type', 'application/json');
        echo json_encode($success);
    }
});
//***********************************************************
Example #12
0
<?php

define('APIKEYS_DB_PATH', '../apikeys/apikeys.csv');
define('BASE_PATH', dirname(__DIR__));
require BASE_PATH . '/vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/hello/:name/:surname', function ($p1, $p2) {
    echo "What, " . $p1 . " " . $p2 . "<br>";
    echo hash('sha256', 'test');
});
$app->get('/api/currenttime/', function () use($app) {
    $head = array();
    $val = array();
    $ind = 0;
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
        $app->halt(405);
    }
    foreach (getallheaders() as $source => $value) {
        $head[$ind] = strval($source);
        $val[$ind] = strval($value);
        $ind++;
    }
    $q1 = $_GET['source'];
    if ($head[3] != "apikey") {
        $app->halt(400, json_encode(array('status' => 1, 'message' => 'Please specify API key.')));
    }
    if ($q1 == "") {
        $app->halt(400, json_encode(array('status' => 2, 'message' => 'Please specify source.')));
    }
    $s1 = retrieveSource($val[3]);
    $a1 = retrieveUserInfo($val[3]);
Example #13
0
<?php

require '../vendor/autoload.php';
require '../app/config.php';
$app = new \Slim\Slim(array('log.level' => 4, 'log.enabled' => true, 'log.writer' => new \Slim\Extras\Log\DateTimeFileWriter(array('path' => '../var/logs', 'name_format' => 'y-m-d'))));
$app->contentType('application/json; charset=utf-8');
$app->expires('+1 month');
foreach ($active_services as $service) {
    include_once '../app/srv_' . $service . '.php';
}
$app->notFound(function () use($app, $service_doc) {
    $req = $app->request();
    if ($req->isGet()) {
        echo json_encode(array('description' => array('en' => "REST services to query for Peru's UBIGEO (geographical location code)", 'es' => "Servicios REST para buscar los códigos de UBIGEO Peruanos"), 'services' => $service_doc));
    } else {
        $app->halt(405);
    }
});
try {
    $app->run();
} catch (Slim_Exception_Stop $e) {
    // do nothing
}
Example #14
0
use API\OAuthServer\OAuthHelper;
// Initialisation of Database (Illuminate)
// and webapp global object
\API\Core\DB::initCapsule();
$app = new \Slim\Slim();
// Instantiating the Resource Server
$resourceServer = new \League\OAuth2\Server\ResourceServer(OAuthHelper::getSessionStorage(), OAuthHelper::getAccessTokenStorage(), OAuthHelper::getClientStorage(), OAuthHelper::getScopeStorage());
// Loading all REST modules
// with their endpoints like that:
// inside 'src/endpoints'
$dir_endpoints = opendir('src/endpoints');
while ($ent = readdir($dir_endpoints)) {
    // For each .php file
    if (preg_match('/^(.*)\\.php$/', $ent, $m)) {
        $endpoint = $m[0];
        // Read the file with PHP
        require 'src/endpoints/' . $endpoint;
    }
}
closedir($dir_endpoints);
// JSON 404 response
$app->notFound(Tool::makeEndpoint(function () {
    throw new \API\Exception\InvalidEndpoint();
}));
// Welcoming browsers when they reach /api
$app->get('/', function () use($app) {
    $app->halt(200);
    //echo file_get_contents(__DIR__.'/welcome.html');
});
// Ready to serve with Slim
$app->run();
Example #15
0
        $app->render('touch.php', array('title' => $app->gwName));
    }
    $db = null;
});
$app->post('/users', function () use($app) {
    $db = $app->dao;
    $params = $app->request->post();
    $user = $db->query("SELECT * FROM users WHERE phone = '{$params['phone']}'")->fetch();
    if (!$user) {
        $db->exec("INSERT INTO users (phone, mac)\n\t\t\t\t\tVALUES ('{$params['phone']}', '{$params['mac']}')");
    } else {
        $db->exec("UPDATE users SET mac = '{$params['mac']}', updated_at = datetime('now', 'localtime') WHERE id = {$user['id']}");
    }
    $db = null;
    $app->setCookie('is_return_user', true, '365 days');
    $app->halt(200, '{ "error": "" }');
});
$app->get('/portal', function () use($app) {
    $app->render('show.php', array('title' => $app->gwName, 'id' => $app->gwId));
});
$app->get('/portal/touch', function () use($app) {
    $db = $app->dao;
    $uuid = $app->uuid;
    $id = $app->uuid;
    $offset = $app->timeLimit;
    $db->exec("INSERT INTO connections (id, token, expires_on)\n\t\t\t\t\tVALUES ('{$id}', '{$uuid}', datetime(datetime('now','localtime'), '+{$offset} minutes'))");
    $db = null;
    $app->redirect("http://{$app->gwAddress}:{$app->gwPort}/wifidog/auth?token={$uuid}");
});
$app->get('/ping', function () use($app) {
    $db = $app->dao;
Example #16
0
    $password = sha1($req_body->password);
    try {
        $user = User::where('nickname', '=', $nickname)->where('password', '=', $password)->firstOrFail();
        if ($user->token == NULL) {
            // Create a new token object
            $token = new Token();
            $token->generateToken();
            $token->user()->associate($user);
            $token->save();
        } else {
            // Generate a new token value
            $user->token->generateToken();
            $user->token->save();
        }
    } catch (ModelNotFoundException $e) {
        $app->halt(401, 'wrong_credentials');
    }
    echo $user->token->toJson();
});
$app->post('/user', function () use($app) {
    $app->response()->header('Content-Type', 'application/json');
    $req_body = json_decode($app->request->getBody());
    // Check if all fields are present
    if ($req_body->gender == NULL || $req_body->nickname == NULL || $req_body->password1 == NULL || $req_body->password2 == NULL || $req_body->school == NULL) {
        $app->halt(400, '{"message": "er is iets fout gegeaan"}');
    }
    // Check if username exists
    if (User::where('nickname', 'like', $req_body->nickname)->count()) {
        $app->halt(400, 'nickname_exists');
    }
    try {
Example #17
0
        return true;
    }
    if (strpos($url, 'report') > 0 && in_array('admin/reportsmanager', $_SESSION['url'])) {
        return true;
    }
    if (strpos($url, 'machine') !== false && in_array('machine/manager', $_SESSION['url'])) {
        return true;
    }
    if (strpos($url, 'chaxun/export') !== false) {
        return true;
    }
    if (strpos($url, 'show/export') !== false) {
        return true;
    }
    if (!isset($_SESSION['url']) || !in_array($url, $_SESSION['url'])) {
        return $app->halt('401', 'Not Authorized <a href=' . SITE_PREFIX . '/login>Login</a>');
    }
    return true;
});
//单例mysql
$db_config = (require_once CODE_BASE . 'configs/mysql.php');
$app->container->singleton('db_admin', function () use($db_config) {
    return new Mysql($db_config['admin']);
});
$app->container->singleton('db_zebra', function () use($db_config) {
    return new Mysql($db_config['zebra']);
});
$app->container->singleton('db_chaxun', function () use($db_config) {
    return new Mysql($db_config['chaxun']);
});
$app->container->singleton('db_show', function () use($db_config) {
Example #18
0
/*
	$app->get('/wines/', 'getWines');
	$app->post('/wines/', 'insertWine');
	$app->get('/wines/:id',  'getWine');
	$app->get('/wines/search/:query', 'findByName');
	$app->put('/wines/:id', 'updateWine');
	$app->delete('/wines/:id',   'deleteWine');
*/
/**
 * Método que se encarga de la validación de la api key
 */
$app->hook('slim.before.dispatch', function () use($app, $db) {
    //obtengo el parámetro de la key que me tiene que venir como parámetro en el header
    $headers = apache_request_headers();
    $keyToCheck = $headers['Authorization'];
    //compruebo la api key
    $apiUsage = new api_usage($db);
    $api_filter = array();
    add_filter($api_filter, "apikey", $keyToCheck);
    add_filter($api_filter, "enabled", 1);
    $authorized = $apiUsage->authorize($api_filter);
    $development = unserialize(DEVELOPMENT);
    //si no me autorizan el acceso, adios
    if (!$authorized->resultado && !$development['enabled']) {
        //key is false
        $app->halt('403', get_error(1));
        // or redirect, or other something
    }
});
//ejecutamos la api
$app->run();
Example #19
0
require_once getcwd() . '/apiConf.php';
require 'application/REST/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->contentType('application/json');
require_once dirname(__FILE__) . apiConf::$REST_PATH . 'AlbumRestController.php';
require_once dirname(__FILE__) . apiConf::$REST_PATH . 'GenreRestController.php';
require_once dirname(__FILE__) . apiConf::$REST_PATH . 'OrderRestController.php';
require_once dirname(__FILE__) . apiConf::$REST_PATH . 'UserRestController.php';
$album = new AlbumRestController();
$user = new UserRestController();
$genre = new GenreRestController();
$order = new OrderRestController();
$send = function ($data) use($app) {
    if (apiConf::$ERROR != '') {
        $app->halt(400, apiConf::$ERROR);
        //$app->response->setStatus( 400 );
        //$app->response->write(apiConf::$ERROR );
    } else {
        echo $data;
    }
};
$app->get('/', function () {
    echo json_encode(array("error" => 1, "msg" => "No method selected"));
});
//-----------------------------ALBUM----------------------------------//
$app->get('/album/:id', function ($id) use($send, $album) {
    $send($album->RCgetAlbumsDetailsByAlbumId($id));
});
$app->get('/album/term/:term', function ($term) use($send, $album) {
    $send($album->RCgetAlbumsByTerm($term));
Example #20
0
require_once dirname(__FILE__) . '/../core/User.class.php';
require_once dirname(__FILE__) . '/../core/Login.class.php';
require_once dirname(__FILE__) . '/../core/Posts.class.php';
$user = new User();
$post = new Posts();
//function to verify if a session was created. If not the user is not aloud to enter home.php
function authenticate()
{
    if (!$_SESSION['login']) {
        echo json_encode(array("error" => "no session"));
        $app->halt(401);
    }
}
$app->get('/', function () {
    global $app;
    $app->halt(401);
});
$app->get('/user/', function () use($user) {
    echo json_encode($user->getAllUsers());
});
$app->get('/user/:id/', function ($id) use($user) {
    echo json_encode($user->getUserById($id));
});
$app->post('/user/', function () use($user, $app) {
    $new_user = json_decode($app->request->getBody(), true);
    $success = $user->createNewUser($new_user);
    echo $success;
});
$app->delete('/user/:id/', function ($id) use($user) {
    echo $user->deleteUser($id);
});
Example #21
0
<?php

// web/index.php
use Aura\Input\Builder;
use Aura\Input\Filter;
require dirname(__DIR__) . '/vendor/autoload.php';
$app = new \Slim\Slim(array('templates' => dirname(__DIR__) . '/templates'));
$app->map('/contact', function () use($app) {
    $form = new ContactForm(new Builder(), new Filter());
    if ($app->request->isPost()) {
        $form->fill($app->request->post('contact'));
        if ($form->filter()) {
            echo "Yes successfully validated and filtered";
            var_dump($data);
            $app->halt();
        }
    }
    $app->render('contact.php', array('form' => $form));
})->via('GET', 'POST')->name('contact');
$app->run();
Example #22
0
<?php

require_once 'env.php';
require_once APP_DIR . '/vendor/autoload.php';
$app = new \Slim\Slim(array('debug' => false, 'cookies.encrypt' => true, 'cookies.secret_key' => 'd3@SD#@!TXZE@', 'cookies.cipher' => MCRYPT_RIJNDAEL_256, 'cookies.cipher_mode' => MCRYPT_MODE_CBC, 'log.enabled' => true, 'log.writer' => new src\common\LogWriter(), 'log.level' => \Slim\Log::DEBUG));
//处理request数据类型
$app->add(new \Slim\Middleware\ContentTypes());
$app->notFound(function () use($app) {
    $app->getLog()->warning('url not found:' . $app->request()->getResourceUri());
    $app->render('404.html');
});
//处理所有未catch exception
$app->error(function (Exception $e) use($app) {
    $app->getLog()->critical('server error: ' . $e->getMessage());
    $app->halt(500, "sorry! server error");
});
$request = $app->request();
$paths = explode('/', $request->getResourceUri());
if (count($paths) < 4 || strtolower($paths[1]) != 'api') {
    $app->getLog()->error('bad request:' . $request->getResourceUri());
    $app->status(400);
}
$app->group('/api', function () use($app, $paths) {
    $router = ucfirst(strtolower($paths[2]));
    if (!file_exists(APP_DIR . "/src/routers/{$router}.php")) {
        return;
    }
    $app->group("/{$paths['2']}", function () use($app, $router) {
        $routerClass = "src\\routers\\{$router}";
        new $routerClass($app);
    });
Example #23
0
    // Log all requests and responses
    $request = $app->request;
    $response = $app->response;
    $app->log->debug('Request path: ' . $request->getPathInfo());
    $app->log->debug('Response status: ' . $response->getStatus());
});
$app->response->headers->set('Content-Type', 'application/json');
$app->response->headers->set('X-Powered-By', 'Unified Networking Lab API');
$app->response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
$app->response->headers->set('Cache-Control', 'post-check=0, pre-check=0');
$app->response->headers->set('Pragma', 'no-cache');
$app->notFound(function () use($app) {
    $output['code'] = 404;
    $output['status'] = 'fail';
    $output['message'] = $GLOBALS['messages']['60038'];
    $app->halt($output['code'], json_encode($output));
});
class ResourceNotFoundException extends Exception
{
}
class AuthenticateFailedException extends Exception
{
}
$db = checkDatabase();
if ($db === False) {
    // Database is not available
    $app->map('/api/(:path+)', function () use($app) {
        $output['code'] = 500;
        $output['status'] = 'fail';
        $output['message'] = $GLOBALS['messages']['90003'];
        $app->response->setStatus($output['code']);
$authorizationServer->setRefreshTokenStorage($refreshTokenStorage);
//$clientCredentials = new \League\OAuth2\Server\Grant\ClientCredentialsGrant();
//$server->addGrantType($clientCredentials);
$refreshTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$authorizationServer->addGrantType($refreshTokenGrant);
$resourceServer = new ResourceServer($sessionStorage, $accessTokenStorage, $clientStorage, $scopeStorage, $refreshTokenStorage);
$passwordGrant = new \League\OAuth2\Server\Grant\PasswordGrant();
$authorizationServer->addGrantType($passwordGrant);
$passwordGrant->setVerifyCredentialsCallback(function ($username, $password) use($app) {
    // implement logic here to validate a username and password, return an ID if valid, otherwise return false
    $host = new Host();
    $valid = $host->oauth2Login($username, $password);
    if ($valid !== false) {
        return $valid;
    } else {
        $app->halt(401, 'Unauthorized. The user credentials were incorrect.');
    }
});
$authorize = function () use($resourceServer) {
    return function () use($resourceServer) {
        //401 = Unauthorized
        //403 = Forbidden
        $app = \Slim\Slim::getInstance();
        try {
            $authenticated = $resourceServer->isValidRequest(false);
            if ($authenticated === false) {
                $app->halt(401, 'Unauthorized');
            }
            //else {
            //if (!$resourceServer->getAccessToken()->hasScope($scope))
            //$app->halt(403, 'Forbidden');
Example #25
0
        if (param_set_value($m, 'tekst')) {
            $m->setKorisnik($env['ulogovan']['korisnik']);
            $m->setParent(null);
            if (param_set_entity('Kategorija', $m, 'kategorija')) {
                if ($m->getId()) {
                    $em->merge($m);
                } else {
                    $em->persist($m);
                }
                $em->flush();
                echo json_encode(array('id' => $m->getId()));
                $app->stop();
            }
        }
    }
    $app->halt(400, 'Nisu dostavljeni svi neophodni parametri u zahtjevu. [naslov, tekst, kategorija]');
});
$app->delete('/media/:id/', function ($id) use($em) {
});
// ** MEDIATIP **
//$app->get('/mediatip/:id/', function ($id) use ($twig, $em, $urls, $app) {});
//$app->post('/mediatip/:id/', function ($id) use ($twig, $em, $urls, $app) {});
//$app->put('/mediatip/:id/', function ($id) use ($twig, $em, $urls, $app) {});
//$app->delete('/mediatip/:id/', function ($id) use ($twig, $em, $urls, $app) {});
// ** KATEGORIJA **
$app->get('/kategorija/', function () use($em) {
    $ke = $em->getRepository('Kategorija')->findAll();
    $r = array();
    foreach ($ke as $k) {
        $r[] = $k->getSerial();
    }
Example #26
0
    try {
        do {
            $csv = fgetcsv($fh);
            if (!strcmp($apikey, $csv[0])) {
                return $csv;
            }
        } while ($csv !== FALSE);
    } finally {
        fclose($fh);
    }
    return FALSE;
}
$app->post('/api/updates/', function () use($app) {
    $apiKey = $app->request->headers->get('apikey');
    if (!strlen($apiKey)) {
        $app->halt(400, json_encode(array('status' => 0, 'message' => 'Please specify API key')));
    }
    if (($csv = retrieveUserInfo($apiKey)) === FALSE) {
        $app->halt(401, json_encode(array('status' => 0, 'message' => 'Invalid API key')));
    }
    $timestamp = $app->request->headers->get('timestamp');
    if (!strlen($timestamp)) {
        $app->halt(400, json_encode(array('status' => 2, 'message' => 'Please specify Timestamp')));
    }
    $fingerprint = $app->request->headers->get('fingerprint');
    $timestamp = intval($timestamp);
    $current = intval(time());
    $terms = 0;
    $tsB = $current - 90;
    $tsA = $current + 90;
    do {
Example #27
0
        case "/api/getSupNRPEPlugin":
        case "/api/getRouterVM":
        case "/api/getNagiosPlugin":
        case "/api/getNagiosPlugins":
            require_once BASE_PATH . "/routes/apiv1.route.php";
            break;
        default:
            break;
    }
});
$app->contentType('application/json');
$app->notFound(function () use($app) {
    $request = $app->request();
    $headers = $request->headers();
    $uri = $request->getResourceUri();
    $apiResponse = new APIViewData(1, false, "The page you are looking for could not be found. Check the address to ensure your URL is spelled correctly...");
    $apiResponse->setExtraResponseData('url', $request->headers('X_FORWARDED_PROTO') . '://' . $request->headers('HOST') . $request->getRootUri() . $request->getResourceUri());
    $app->halt('404', $apiResponse->returnJson());
});
// Initial Dummy Routes
// Leave the / on the end of /sapi/ due to rewrite engine, otherwise requests to /sapi break
$app->get('/sapi/', function () use($app) {
    $msg = "Welcome to /sapi/ ... What can we help you with?";
    $apiResponse = new APIViewData(0, false, $msg);
    $apiResponse->printJson();
})->name('saigon-api');
$app->get('/sapi/version', function () use($app) {
    $apiResponse = new APIViewData(0, false, API_VERSION . " (alpha/beta/charlie/delta/echo/use at your own risk)");
    $apiResponse->printJson();
})->name('saigon-api-version');
$app->run();
Example #28
0
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
require 'lib/Slim/Slim.php';
require 'lib/Unirest.php';
require 'steamwebapi_config.php';
const STEAM_WEB_API_BASE_URL = 'http://api.steampowered.com';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->setName('Steam Web API');
// Do nothing when we index the Steam Web PHP API
$app->get('/', function () use($app) {
    $app->halt(403);
});
// Do nothing when we don't find an API endpoint
$app->notFound(function () {
});
function get($app, $endpoint)
{
    $parameters = ['key' => STEAM_WEB_API_KEY];
    foreach ($app->request->get() as $key => $value) {
        $parameters[$key] = $value;
    }
    $response = Unirest::get(STEAM_WEB_API_BASE_URL . $endpoint, NULL, $parameters);
    $app->response->setStatus($response->code);
    foreach ($response->headers as $key => $value) {
        if ($key === 'Content-Encoding') {
            continue;
Example #29
0
        // todo: error page
        echo 'Invalid Password<br>';
    }
});
/***
 * Administrator
***/
$oApp->get('/administrator', function () use($oApp, $oProductMgr) {
    if (getUserType() == 'admin') {
        $oApp->render('administrator.phtml', array('title' => 'Administrator', 'userType' => getUserType()));
    }
});
/* CRUD APIs */
$oApp->post('/getALlProducts', function () use($oApp, $oProductMgr) {
    if (getUserType() != 'admin') {
        $oApp->halt(500, 'You are not login');
        return;
    }
    //ChromePhp::info($oProductMgr->getAllProducts());
    echo json_encode($oProductMgr->getAllProducts());
});
$oApp->post('/addProduct', function () use($oApp, $oProductMgr) {
    if (getUserType() != 'admin') {
        $oApp->halt(500, 'You are not login');
        return;
    }
    $oProduct = json_decode($oApp->request->getBody());
    //ChromePhp::info($oProduct);
    $nRow = $oProductMgr->addProduct($oProduct);
    echo json_encode(array("rows" => $nRow));
});
Example #30
0
require '../vendor/autoload.php';
echo 2;
$app = new \Slim\Slim(array('templates.path' => '../templates'));
$name = "Tomiwa";
echo 3;
$app->get('', function () use($app) {
    // Fetch and display events as JSON
    // Get the start and end timestamps from request query parameters
    $startTimestamp = $app->request->get('start');
    $endTimestamp = $app->request->get('end');
    try {
        // Open database connection
        $conn = new mysqli('localhost', 'user1', '', 'Schedy');
        // Query database for events in range
        $stmt = $conn->prepare('SELECT * FROM events WHERE start >= FROM_UNIXTIME(:start) AND end < FROM_UNIXTIME(:end) ORDER BY start ASC');
        $stmt->bindParam(':start', $startTimestamp, \PDO::PARAM_INT);
        $stmt->bindParam(':end', $endTimestamp, \PDO::PARAM_INT);
        $stmt->execute();
        // Fetch query results
        $results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        // Return query results as JSON
        echo json_encode($results);
    } catch (\PDOException $e) {
        $app->halt(500, $e->getMessage());
    }
});
$app->get('/', function () use($app) {
    $app->render('calendar.html');
});
$app->run();
echo "Hello, " . $name;