hedera-web/vn/web/service.php

275 lines
6.2 KiB
PHP
Raw Normal View History

<?php
namespace Vn\Web;
require_once ('vn/lib/app.php');
2016-09-23 22:47:34 +00:00
require_once (__DIR__.'/jwt.php');
2016-09-19 06:40:18 +00:00
require_once (__DIR__.'/db-session-handler.php');
use Vn\Lib\Locale;
2016-09-23 22:47:34 +00:00
use Vn\Lib\UserException;
/**
* Thrown when user credentials could not be fetched.
**/
2016-09-23 22:47:34 +00:00
class SessionExpiredException extends UserException {}
/**
* Thrown when user credentials are invalid.
**/
2016-09-23 22:47:34 +00:00
class BadLoginException extends UserException {}
/**
* Thrown when client version is outdated.
**/
2016-09-23 22:47:34 +00:00
class OutdatedVersionException extends UserException {}
/**
* Main class for web applications.
**/
abstract class Service
{
protected $app;
2016-09-23 22:47:34 +00:00
protected $db;
protected $userDb = NULL;
function __construct ($app)
{
$this->app = $app;
2016-09-23 22:47:34 +00:00
$this->db = $app->getSysConn ();
}
/**
* Starts the user session.
**/
function startSession ()
{
2016-09-23 22:47:34 +00:00
$db = $this->db;
2016-09-19 06:40:18 +00:00
ini_set ('session.cookie_secure', TRUE);
ini_set ('session.use_only_cookies', FALSE);
ini_set ('session.cookie_path', 'cookies');
2016-09-23 22:47:34 +00:00
ini_set ('session.hash_function', 'sha256');
2016-09-19 06:40:18 +00:00
session_set_save_handler (new DbSessionHandler ($db));
session_start ();
2016-09-19 06:40:18 +00:00
// Setting the locale
if (isset ($_SERVER['HTTP_ACCEPT_LANGUAGE']))
2016-09-19 06:40:18 +00:00
if (!isset ($_SESSION['httpLanguage'])
|| $_SESSION['httpLanguage'] != $_SERVER['HTTP_ACCEPT_LANGUAGE'])
{
2016-09-19 06:40:18 +00:00
$_SESSION['httpLanguage'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$regexp = '/([a-z]{1,4})(?:-[a-z]{1,4})?\s*(?:;\s*q\s*=\s*(?:1|0\.[0-9]+))?,?/i';
preg_match_all ($regexp, $_SERVER['HTTP_ACCEPT_LANGUAGE'], $languages);
foreach ($languages[1] as $lang)
if (stream_resolve_include_path ("locale/$lang"))
{
$_SESSION['lang'] = $lang;
break;
}
}
if (!isset ($_SESSION['lang']))
$_SESSION['lang'] = NULL;
Locale::set ($_SESSION['lang']);
// Registering the visit
if (!isset ($_COOKIE['PHPSESSID'])
|| isset ($_SESSION['access'])
|| isset ($_SESSION['skipVisit']))
return;
$agent = $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser ($agent, TRUE);
if (isset ($browser['crawler']) && $browser['crawler'])
{
$_SESSION['skipVisit'] = TRUE;
return;
}
if (isset ($_SERVER['REMOTE_ADDR']))
$ip = ip2long ($_SERVER['REMOTE_ADDR']);
$row = $db->getRow (
2016-09-19 06:40:18 +00:00
'CALL visitRegister (#, #, #, #, #, #, #, #, #)',
[
2016-09-19 06:40:18 +00:00
nullIf ($_COOKIE, 'vnVisit')
,nullIf ($browser, 'platform')
,nullIf ($browser, 'browser')
,nullIf ($browser, 'version')
,nullIf ($browser, 'javascript')
,nullIf ($browser, 'cookies')
,isset ($agent) ? $agent : NULL
,isset ($ip) && $ip ? $ip : NULL
,nullIf ($_SERVER, 'HTTP_REFERER')
]
);
if (isset ($row['access']))
{
2016-09-19 06:40:18 +00:00
setcookie ('vnVisit', $row['visit'], time () + 31536000); // 1 Year
$_SESSION['access'] = $row['access'];
}
else
$_SESSION['skipVisit'] = TRUE;
}
2016-09-20 18:36:22 +00:00
/**
* Tries to retrieve user credentials from many sources such as POST,
* SESSION or COOKIES. If $_POST['remember'] is defined the user credentials
* are saved on the client brownser for future logins, cookies names are
* 'vn_user' for the user name and 'vn_pass' for user password, the
* password is encoded using base64_encode() function and should be decoded
* using base64_decode().
*
* return Db\Conn The database connection
**/
function login ()
{
2016-09-23 22:47:34 +00:00
$db = $this->db;
2016-09-20 18:36:22 +00:00
$user = NULL;
$wasLoged = isset ($_SESSION['user']);
if (isset ($_POST['user']) && isset ($_POST['password']))
{
$user = strtolower ($_POST['user']);
try {
$db->query ('CALL account.userLogin (#, #)',
[$user, $_POST['password']]);
}
catch (\Exception $e)
{
throw new BadLoginException ();
}
}
else
{
if (isset ($_POST['token']) || isset ($_GET['token']))
{
if (isset ($_POST['token']))
$token = $_POST['token'];
if (isset ($_GET['token']))
$token = $_GET['token'];
$key = $db->getValue ('SELECT jwt_key FROM config');
$jwtPayload = Jwt::decode ($token, $key);
$expiration = $jwtPayload['exp'];
if (isset ($expiration) && $expiration > time())
throw new SessionExpiredException ();
$user = $jwtPayload['user'];
}
else
$user = $db->getValue ('SELECT guest_user FROM config');
$db->query ('CALL account.userLoginWithName (#)', [$user]);
}
$_SESSION['user'] = $user;
// Registering the user access
if (isset ($_SESSION['access'])
2016-09-23 22:47:34 +00:00
&& (!isset ($_SESSION['visitUser']) || $wasLoged))
2016-09-20 18:36:22 +00:00
{
$_SESSION['visitUser'] = TRUE;
$db->query (
'CALL visitUserNew (#, #)',
[$_SESSION['access'], session_id ()]
);
}
}
/**
* Logouts the current user. Cleans the last saved used credentials.
**/
function logout ()
{
unset ($_SESSION['visitUser']);
unset ($_SESSION['user']);
}
2016-09-23 22:47:34 +00:00
/**
* Creates or returns a database connection where the authenticated user
* is the current logged user.
*
* @return {Db\Conn} The database connection
**/
function getUserDb ($user)
{
if ($this->userDb)
return $this->userDb;
$password = $sysDb->getValue (
'SELECT password FROM user WHERE name = #', [$user]);
return $this->userDb = $this->createConnection ($user, $password);
}
/**
* Runs a method.
**/
function loadMethod ($class)
{
$db = $this->db;
$this->login ();
$method = $this->app->loadMethod (
$_REQUEST['method'], $class, './rest');
if ($method::SECURITY == Security::DEFINER)
{
$isAuthorized = $db->getValue ('SELECT userCheckRestPriv (#)',
[$_REQUEST['method']]);
if (!$isAuthorized)
throw new UserException ('You don\'t have enough privileges');
$methodDb = $db;
}
else
$methodDb = $this->getUserDb ();
if ($method::PARAMS !== NULL && !$method->checkParams ($_REQUEST, $method::PARAMS))
throw new UserException (s('Missing parameters'));
$res = $method->run ($methodDb);
$db->query ('CALL account.userLogout ()');
return $res;
}
/**
* Checks if the HTTP connection is secure.
*
* @return boolean Return %TRUE if its secure, %FALSE otherwise
**/
function isHttps ()
{
return isset ($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
}
/**
* Obtains the application version number. It is based on de last
* modification date of the main script.
**/
function getVersion ()
{
return (int) strftime ('%G%m%d%H%M%S',
2016-08-30 07:43:47 +00:00
filectime ($_SERVER['SCRIPT_FILENAME']));
}
}
?>