[+] базовая реализация функционала 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

+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);
}
/**
* Проверка на доступ в админку
*