[+] базовая реализация функционала API

This commit is contained in:
rsgrinko committed 2023-03-02 11:53:53 +03:00
1 parent 30d612e52b
commit 7b183b6c32
14 files changed
+342 -11

No files matched your search

+6
View File
@@ -22,6 +22,12 @@
use Core\Helpers\{Cache, SystemFunctions};
require_once __DIR__ . '/inc/header.php';
global $USER;
if ($USER->isAdmin() === false) {
header('Location: ./');
die();
}
?>
<div class="pageheader">
<div class="media">
+6
View File
@@ -22,6 +22,12 @@
use Core\Models\{User, Roles};
require_once __DIR__ . '/inc/header.php';
global $USER;
if ($USER->isAdmin() === false) {
header('Location: ./');
die();
}
?>
<div class="pageheader">
<div class="media">
+6
View File
@@ -23,6 +23,12 @@
use Core\ExternalServices\RemoteHosts;
require_once __DIR__ . '/inc/header.php';
global $USER;
if ($USER->isAdmin() === false) {
header('Location: ./');
die();
}
?>
<div class="pageheader">
<div class="media">
+12 -9
View File
@@ -68,7 +68,8 @@
<div class="headerwrapper">
<div class="header-left">
<a href="index.php" class="logo">
<img src="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/images/logo.png" alt=""/>
<span class="" style="color: white;font-size: 1.5em;">Панель админа</span>
<!--<img src="//<?= $_SERVER['SERVER_NAME'] ?>/admin/styles/images/logo.png" alt=""/>-->
</a>
<div class="pull-right">
<a href="" class="menu-collapse">
@@ -246,15 +247,17 @@
<h5 class="leftpanel-title">Навигация</h5>
<ul class="nav nav-pills nav-stacked">
<li><a href="/admin/"><i class="fa fa-home"></i> <span>Дашбоард</span></a></li>
<li><a href="/admin/users.php"><i class="fa fa-home"></i> <span>Список пользователей</span></a></li>
<li><a href="/admin/groups.php"><i class="fa fa-home"></i> <span>Список ролей</span></a></li>
<li><a href="/admin/cacheInfo.php"><i class="fa fa-home"></i> <span>Кэширование</span></a></li>
<li><a href="/admin/hosts.php"><i class="fa fa-home"></i> <span>Управление хостами</span></a></li>
<li><a href="/admin/threads.php"><i class="fa fa-home"></i> <span>Диспетчер очереди</span></a></li>
<li><a href="/admin/phpcmd.php"><i class="fa fa-home"></i> <span>Командная PHP строка</span></a></li>
<li><a href="/admin/nginx.php"><i class="fa fa-home"></i> <span>Логи nginx</span></a></li>
<li><a href="index.html"><i class="fa fa-home"></i> <span>Dashboard</span></a></li>
<?php if ($USER->isAdmin()) { ?>
<li><a href="/admin/users.php"><i class="fa fa-home"></i> <span>Список пользователей</span></a></li>
<li><a href="/admin/groups.php"><i class="fa fa-home"></i> <span>Список ролей</span></a></li>
<li><a href="/admin/cacheInfo.php"><i class="fa fa-home"></i> <span>Кэширование</span></a></li>
<li><a href="/admin/hosts.php"><i class="fa fa-home"></i> <span>Управление хостами</span></a></li>
<li><a href="/admin/threads.php"><i class="fa fa-home"></i> <span>Диспетчер очереди</span></a></li>
<li><a href="/admin/phpcmd.php"><i class="fa fa-home"></i> <span>Командная PHP строка</span></a></li>
<li><a href="/admin/nginx.php"><i class="fa fa-home"></i> <span>Логи nginx</span></a></li>
<?php } ?>
<li><a href="#"><i class="fa fa-home"></i> <span>В никуда</span></a></li>
</ul>
+6
View File
@@ -23,6 +23,12 @@
use Core\Helpers\SystemFunctions;
require_once __DIR__ . '/inc/header.php';
global $USER;
if ($USER->isAdmin() === false) {
header('Location: ./');
die();
}
?>
<div class="pageheader">
<div class="media">
+4
View File
@@ -24,6 +24,10 @@
require_once __DIR__ . '/inc/header.php';
global $USER;
if ($USER->isAdmin() === false) {
header('Location: ./');
die();
}
if (isset($_REQUEST['execute']) && $_REQUEST['execute'] == 'Y') {
$_SESSION['phpcmd_query'] = $_REQUEST['query'];
+6
View File
@@ -22,6 +22,12 @@
use Core\Models\{User, MQ};
require_once __DIR__ . '/inc/header.php';
global $USER;
if ($USER->isAdmin() === false) {
header('Location: ./');
die();
}
$MQ = new MQ();
?>
<div class="pageheader">
+5
View File
@@ -23,7 +23,12 @@
use Core\Models\User;
require_once __DIR__ . '/inc/header.php';
global $USER;
if ($USER->isAdmin() === false) {
header('Location: ./');
die();
}
?>
<div class="pageheader">
<div class="media">
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* 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.
*/
use Core\Api\{ApiController, ApiException, ApiView};
use Core\Models\User;
require_once __DIR__ . '/bootstrap.php';
session_write_close();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 6000');
header('Content-type: text/json; charset=UTF-8;');
/** @var array $noAuthMethods Методы, не требующие авторизации */
$noAuthMethods = [
'testNoAuth',
'test',
'testNotFound',
];
$method = $_REQUEST['method'] ?: null;
$token = $_REQUEST['token'] ?: null;
try {
// Если вызван метод, не требующий авторизации
if (in_array($method, $noAuthMethods, true)) {
ApiController::$method();
die();
}
if (empty($token)) {
throw new ApiException('Не задан токен', ApiException::ERROR_TOKEN_UNDEFINED);
}
$userObject = User::getByToken($token);
if ($userObject === null) {
throw new ApiException('Токен некорректен', ApiException::ERROR_INCORRECT_TOKEN);
}
$apiController = new ApiController($userObject);
// Проверяем существование метода контроллера
if (!method_exists($apiController, $method)) {
throw new ApiException('Метод не существует', ApiException::ERROR_METHOD_NOT_FOUND);
}
$apiController->$method();
} catch (Throwable $e) {
ApiView::outputError($e);
}
+76
View File
@@ -0,0 +1,76 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* 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.
*/
namespace Core\Api;
use Core\CoreException;
use Core\Models\File;
use Core\Models\User;
/**
* Класс API контроллера
*/
class ApiController
{
/** @var User $userObject Объект пользователя */
private $userObject;
public function __construct(User $userObject)
{
$this->userObject = $userObject;
}
/**
* Получение информации о текущем пользователе
*
* @return void
* @throws CoreException
* @throws \JsonException
*/
public function getUserInfo(): void
{
$result = $this->userObject->getAllUserData();
$result['image'] = (new File((int)$result['image_id']))->getAllProps();
$result['email_confirmed'] = $result['email_confirmed'] === CODE_VALUE_Y;
unset($result['password'], $result['token'], $result['image_id']);
ApiView::output($result);
}
/**
* Тестовый метод (не требующий авторизации)
*
* @return void
* @throws \JsonException
*/
public static function testNoAuth(): void
{
ApiView::output(
[
'message' => 'test completed',
'randomInt' => random_int(1000, 9999),
]
);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* 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.
*/
namespace Core\Api;
class ApiException extends \Exception
{
/** @var int ERROR_TOKEN_UNDEFINED Токен не определен */
const ERROR_TOKEN_UNDEFINED = 10001;
/** @var int ERROR_INCORRECT_TOKEN Некорректный токен */
const ERROR_INCORRECT_TOKEN = 10002;
/** @var int ERROR_METHOD_NOT_FOUND Метод не существует */
const ERROR_METHOD_NOT_FOUND = 10003;
}
+95
View File
@@ -0,0 +1,95 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* 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.
*/
namespace Core\Api;
use Core\CoreException;
use Throwable;
/**
* Класс представления API
*/
class ApiView
{
/**
* Подготовка результата
*
* @param mixed $data Данные
*
* @return mixed
*/
private static function prepare($data)
{
if (is_string($data) && $data === strip_tags($data)) {
$data = htmlentities($data, ENT_QUOTES);
}
if (is_int($data)) {
$data = (int)$data;
}
return $data;
}
/**
* Вывод результата в API
*
* @param mixed $data Данные
*
* @return void
* @throws \JsonException
*/
public static function output($data): void
{
header('Content-Type: application/json');
echo json_encode(
[
'success' => true,
'time' => time(),
'data' => self::prepare($data),
],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
}
/**
* Вывод ошибки в API
* @param Throwable $exception Исключение
*
* @return void
* @throws \JsonException
*/
public static function outputError (Throwable $exception): void
{
echo json_encode(
[
'success' => false,
'time' => time(),
'error' => [
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
],
],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
}
}
+5
View File
@@ -52,6 +52,11 @@
*/
const ADMIN_PANEL_ROLE_ID = 3;
/**
* Роль "менеджер"
*/
const MANAGER_ROLE_ID = 4;
/**
* Роль "пользователь"
*/
+13 -2
View File
@@ -285,11 +285,11 @@
* @return User|null
* @throws CoreException
*/
public static function getUserByToken(string $token): ?self
public static function getByToken(string $token): ?self
{
$result = (DB::getInstance())->getItem(self::TABLE, ['token' => $token]);
if ($result) {
return (new self($result['id']));
return (new self((int)$result['id']));
}
return null;
@@ -641,6 +641,17 @@
return in_array(Roles::ADMIN_ROLE_ID, $this->getRolesObject()->getRoles(), true);
}
/**
* Проверка на менеджера
*
* @return bool
* @throws CoreException
*/
public function isManager(): bool
{
return in_array(Roles::MANAGER_ROLE_ID, $this->getRolesObject()->getRoles(), true);
}
/**
* Проверка на доступ в админку
*