0
1
Fork 0
hedera-web-mindshore/web/rest-service.php

111 lines
2.1 KiB
PHP
Raw Normal View History

2016-07-22 20:00:27 +00:00
<?php
namespace Vn\Web;
2016-08-22 10:41:05 +00:00
use Vn\Lib;
2017-03-09 12:30:39 +00:00
use Vn\Lib\Locale;
use Vn\Lib\UserException;
2016-08-22 10:41:05 +00:00
2016-07-22 20:00:27 +00:00
/**
2016-08-22 10:41:05 +00:00
* Base class for REST application.
2016-12-20 09:32:17 +00:00
*/
class RestService extends Service
2016-07-22 20:00:27 +00:00
{
function run ()
{
ini_set ('display_errors', _ENABLE_DEBUG);
2016-08-22 10:41:05 +00:00
set_error_handler ([$this, 'errorHandler'], E_ALL);
set_exception_handler ([$this, 'exceptionHandler']);
2016-07-22 20:00:27 +00:00
2017-03-09 12:30:39 +00:00
$this->init ();
2016-07-22 20:00:27 +00:00
$this->startSession ();
2016-09-23 22:47:34 +00:00
$this->loadMethod (__NAMESPACE__.'\RestRequest');
2016-08-22 10:41:05 +00:00
}
2017-03-09 12:30:39 +00:00
/**
* Runs a REST method.
*/
function loadMethod ($class)
{
$db = $this->db;
$this->login ();
$method = $this->app->loadMethod (
$_REQUEST['method'], $class, './rest');
$method->service = $this;
if ($method::SECURITY == Security::DEFINER)
{
$isAuthorized = $db->getValue ('SELECT userCheckRestPriv (#)',
[$_REQUEST['method']]);
if (!$isAuthorized)
throw new UserException (s('You don\'t have enough privileges'));
$methodDb = $db;
}
else
$methodDb = $this->getUserDb ($_SESSION['user']);
if ($method::PARAMS !== NULL && !$method->checkParams ($_REQUEST, $method::PARAMS))
throw new UserException (s('Missing parameters'));
2017-05-02 13:48:47 +00:00
Locale::addPath ('rest/'. dirname ($_REQUEST['method']));
2017-07-04 06:51:41 +00:00
$res = NULL;
2017-05-02 13:48:47 +00:00
try {
$res = $method->run ($methodDb);
}
catch (Db\Exception $e)
{
if ($e->getCode () == 1644)
throw new UserException (s($e->getMessage ()));
}
2017-03-09 12:30:39 +00:00
$db->query ('CALL account.userLogout ()');
return $res;
}
2016-08-22 10:41:05 +00:00
function statusFromException ($e)
{
try {
throw $e;
2016-07-22 20:00:27 +00:00
}
2016-08-22 10:41:05 +00:00
catch (SessionExpiredException $e)
{ $status = 401; }
catch (BadLoginException $e)
{ $status = 401; }
catch (Lib\UserException $e)
{ $status = 400; }
catch (\Exception $e)
{ $status = 500; }
http_response_code ($status);
}
function errorHandler ($errno, $message, $file, $line, $context)
{
$eFlag =
E_USER_NOTICE
| E_USER_WARNING
| E_USER_DEPRECATED
| E_NOTICE
| E_WARNING
| E_DEPRECATED;
if (!($errno & $eFlag))
http_response_code (500);
return FALSE;
2016-07-22 20:00:27 +00:00
}
2016-08-22 10:41:05 +00:00
function exceptionHandler ($e)
2016-07-22 20:00:27 +00:00
{
2016-08-22 10:41:05 +00:00
$this->statusFromException ($e);
throw $e;
2016-07-22 20:00:27 +00:00
}
}