From 7ccf0957bfee93c40385c5874ad841926eafb42a Mon Sep 17 00:00:00 2001 From: Kavalar Date: Tue, 22 Oct 2024 11:09:35 +0300 Subject: [PATCH] bearer middleware --- kernel/App.php | 3 ++ kernel/RestController.php | 8 ++++ .../controllers/AdminConsoleController.php | 21 +++++++- kernel/controllers/ModuleController.php | 8 +++- .../post/controllers/PostRestController.php | 30 ++++++++++++ kernel/modules/post/routs/post.php | 5 +- .../controllers/SecureRestController.php | 2 - kernel/modules/secure/manifest.json | 3 +- .../middlewares/BearerAuthMiddleware.php | 48 +++++++++++++++++++ kernel/modules/secure/routs/secure.php | 1 + kernel/modules/user/manifest.json | 2 +- kernel/modules/user/models/User.php | 8 +++- kernel/modules/user/service/UserService.php | 10 ++++ kernel/routs/admin.php | 1 + 14 files changed, 141 insertions(+), 9 deletions(-) create mode 100644 kernel/modules/secure/middlewares/BearerAuthMiddleware.php diff --git a/kernel/App.php b/kernel/App.php index 855e082..07b8f71 100644 --- a/kernel/App.php +++ b/kernel/App.php @@ -5,6 +5,7 @@ namespace kernel; use kernel\helpers\Debug; +use kernel\modules\user\models\User; use kernel\services\ModuleService; use Phroute\Phroute\Dispatcher; @@ -17,6 +18,8 @@ class App static Header $header; + static User $user; + public ModuleService $moduleService; public static Database $db; diff --git a/kernel/RestController.php b/kernel/RestController.php index 797885f..0da92ff 100644 --- a/kernel/RestController.php +++ b/kernel/RestController.php @@ -101,6 +101,12 @@ class RestController $this->renderApi($model->toArray()); } + #[NoReturn] public function returnError(int $code): void + { + http_response_code($code); + die('Forbidden'); + } + #[NoReturn] protected function renderApi(array $data): void { header("Content-Type: application/json"); @@ -108,4 +114,6 @@ class RestController exit(); } + + } \ No newline at end of file diff --git a/kernel/console/controllers/AdminConsoleController.php b/kernel/console/controllers/AdminConsoleController.php index 83e33ee..4b1bce3 100644 --- a/kernel/console/controllers/AdminConsoleController.php +++ b/kernel/console/controllers/AdminConsoleController.php @@ -69,7 +69,7 @@ class AdminConsoleController extends ConsoleController $this->optionService->createFromParams( key: "active_modules", - value: "{\"modules\":[\"admin_themes\", \"secure\", \"user\"]}", + value: "{\"modules\":[\"admin_themes\", \"secure\", \"user\", \"menu\"]}", label: "Активные модули" ); $this->out->r("create option active_modules", "green"); @@ -82,6 +82,25 @@ class AdminConsoleController extends ConsoleController ]); $this->out->r("create item menu module", "green"); + $this->menuService->createItem([ + "label" => "Пользователи", + "url" => "#", + "slug" => "user", + ]); + $this->menuService->createItem([ + "label" => "Список", + "url" => "/admin/user", + "slug" => "user_list", + "parent_slug" => "user", + ]); + $this->menuService->createItem([ + "label" => "Создать", + "url" => "/admin/user/create", + "slug" => "user_create", + "parent_slug" => "user", + ]); + $this->out->r("create item menu user", "green"); + $this->menuService->createItem([ "label" => "Настройки", "url" => "#", diff --git a/kernel/controllers/ModuleController.php b/kernel/controllers/ModuleController.php index 799833d..323a537 100644 --- a/kernel/controllers/ModuleController.php +++ b/kernel/controllers/ModuleController.php @@ -41,8 +41,14 @@ class ModuleController extends AdminController foreach (new DirectoryIterator($dir) as $fileInfo) { $info = []; if($fileInfo->isDot()) continue; + $mi = $this->moduleService->getModuleInfo($fileInfo->getPathname()); + if (isset($mi['show_in_admin'])){ + if ($mi['show_in_admin'] == 0){ + continue; + } + } $info['id'] = $i; - $modules_info[] = array_merge($info, $this->moduleService->getModuleInfo($fileInfo->getPathname())); + $modules_info[] = array_merge($info, $mi); $i++; } } diff --git a/kernel/modules/post/controllers/PostRestController.php b/kernel/modules/post/controllers/PostRestController.php index c640608..4f79482 100644 --- a/kernel/modules/post/controllers/PostRestController.php +++ b/kernel/modules/post/controllers/PostRestController.php @@ -4,7 +4,10 @@ namespace kernel\modules\post\controllers; use Illuminate\Database\Eloquent\Model; use JetBrains\PhpStorm\NoReturn; +use kernel\App; +use kernel\helpers\Debug; use kernel\modules\post\models\Post; +use kernel\Request; use kernel\RestController; class PostRestController extends RestController @@ -19,4 +22,31 @@ class PostRestController extends RestController return ["user"]; } + public function actionIndex(): void + { + $request = new Request(); + $page = $request->get('page') ?? 1; + $perPage = $request->get('per_page') ?? 10; + $query = $this->model->query(); + if (App::$user){ + $query->where("user_id", App::$user->id); + } + + if ($page > 1) { + $query->skip(($page - 1) * $perPage)->take($perPage); + } else { + $query->take($perPage); + } + + $expand = $this->expand(); + $expandParams = explode( ",", $request->get('expand') ?? ""); + $finalExpand = array_intersect($expandParams, $expand); + if ($finalExpand) { + $res = $query->get()->load($finalExpand)->toArray(); + } else { + $res = $query->get()->toArray(); + } + + $this->renderApi($res); + } } \ No newline at end of file diff --git a/kernel/modules/post/routs/post.php b/kernel/modules/post/routs/post.php index 3bba27d..c52a2bb 100644 --- a/kernel/modules/post/routs/post.php +++ b/kernel/modules/post/routs/post.php @@ -4,6 +4,7 @@ use kernel\App; use kernel\CgRouteCollector; use Phroute\Phroute\RouteCollector; +App::$collector->filter('bearer', [\kernel\modules\secure\middlewares\BearerAuthMiddleware::class, "handler"]); App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){ App::$collector->group(["before" => "auth"], function (RouteCollector $router) { @@ -21,5 +22,7 @@ App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){ }); App::$collector->group(["prefix" => "api"], function (CgRouteCollector $router){ - $router->rest("post", [\kernel\modules\post\controllers\PostRestController::class]); + App::$collector->group(['before' => 'bearer'], function (CgRouteCollector $router){ + $router->rest("post", [\kernel\modules\post\controllers\PostRestController::class]); + }); }); \ No newline at end of file diff --git a/kernel/modules/secure/controllers/SecureRestController.php b/kernel/modules/secure/controllers/SecureRestController.php index 0eec824..89d3583 100644 --- a/kernel/modules/secure/controllers/SecureRestController.php +++ b/kernel/modules/secure/controllers/SecureRestController.php @@ -30,8 +30,6 @@ class SecureRestController extends RestController // $baseUrl .= $_SERVER['REQUEST_URI'];; $jwt = JWT::encode( payload: [ - "iss" => $baseUrl, - "aud" => $baseUrl, "iat" => time(), "exp" => date("Y-m-d H:i:s", strtotime("+30 days")) ], diff --git a/kernel/modules/secure/manifest.json b/kernel/modules/secure/manifest.json index e0ccf6e..6d93a08 100644 --- a/kernel/modules/secure/manifest.json +++ b/kernel/modules/secure/manifest.json @@ -5,5 +5,6 @@ "slug": "secure", "description": "Secure module", "routs": "routs/secure.php", - "dependence": "user" + "dependence": "user", + "show_in_admin": 0 } \ No newline at end of file diff --git a/kernel/modules/secure/middlewares/BearerAuthMiddleware.php b/kernel/modules/secure/middlewares/BearerAuthMiddleware.php new file mode 100644 index 0000000..d77893d --- /dev/null +++ b/kernel/modules/secure/middlewares/BearerAuthMiddleware.php @@ -0,0 +1,48 @@ +userService = new UserService(); + } + + function handler(): void + { + $request = new Request(); + $authorization = $request->getHeader("Authorization"); + if ($authorization){ + $authorization = explode(" ", $authorization); + $type = $authorization[0]; + $token = $authorization[1]; + if ($type === "Bearer"){ + $user = $this->userService->getByAccessToken($token); + if ($user){ + if ($user->access_token_expires_at > date("Y-m-d")){ + App::$user = $user; + return; + } + } + } + } + + $this->returnError(403); + } + + #[NoReturn] public function returnError(int $code): void + { + http_response_code($code); + die('Forbidden'); + } +} \ No newline at end of file diff --git a/kernel/modules/secure/routs/secure.php b/kernel/modules/secure/routs/secure.php index d96b914..84b37c3 100644 --- a/kernel/modules/secure/routs/secure.php +++ b/kernel/modules/secure/routs/secure.php @@ -5,6 +5,7 @@ use kernel\CgRouteCollector; use Phroute\Phroute\RouteCollector; App::$collector->filter("auth", [\kernel\middlewares\AuthMiddleware::class, "handler"]); +App::$collector->filter('bearer', [\kernel\modules\secure\middlewares\BearerAuthMiddleware::class, "handler"]); App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){ App::$collector->group(["before" => "auth"], function (RouteCollector $router){ diff --git a/kernel/modules/user/manifest.json b/kernel/modules/user/manifest.json index 2ddffae..72e1b80 100644 --- a/kernel/modules/user/manifest.json +++ b/kernel/modules/user/manifest.json @@ -7,5 +7,5 @@ "module_class": "kernel\\modules\\user\\UserModule", "module_class_file": "{KERNEL_MODULES}/user/UserModule.php", "routs": "routs/user.php", - "dependence": "menu" + "dependence": "menu,secure" } \ No newline at end of file diff --git a/kernel/modules/user/models/User.php b/kernel/modules/user/models/User.php index 6663709..15fdc55 100644 --- a/kernel/modules/user/models/User.php +++ b/kernel/modules/user/models/User.php @@ -7,6 +7,8 @@ use Illuminate\Database\Eloquent\Model; * @property string $username * @property string $email * @property string $password_hash + * @property string $access_token + * @property string $access_token_expires_at * @method static find($id) */ class User extends Model { @@ -15,7 +17,7 @@ class User extends Model { const ADMIN_USER_ROLE = 9; protected $table = 'user'; - protected $fillable = ['username', 'email', 'password_hash', 'role']; + protected $fillable = ['username', 'email', 'password_hash', 'role', 'access_token', 'access_token_expires_at']; protected array $dates = ['deleted at']; public static function labels(): array @@ -24,7 +26,9 @@ class User extends Model { 'username' => 'Логин', 'email' => 'Email', 'created_at' => 'Создан', - 'updated_at' => 'Обновлен' + 'updated_at' => 'Обновлен', + 'access_token' => 'Token', + 'access_token_expires_at' => 'Token expires at', ]; } } diff --git a/kernel/modules/user/service/UserService.php b/kernel/modules/user/service/UserService.php index 514675e..8619038 100644 --- a/kernel/modules/user/service/UserService.php +++ b/kernel/modules/user/service/UserService.php @@ -33,6 +33,11 @@ class UserService return false; } + /** + * @param string $field + * @param string $value + * @return mixed + */ public function getByField(string $field, string $value) { return User::where($field, $value)->first(); @@ -72,4 +77,9 @@ class UserService return ''; } + public function getByAccessToken(string $token) + { + return $this->getByField("access_token", $token); + } + } \ No newline at end of file diff --git a/kernel/routs/admin.php b/kernel/routs/admin.php index d144bd5..ddddeaf 100644 --- a/kernel/routs/admin.php +++ b/kernel/routs/admin.php @@ -3,6 +3,7 @@ use kernel\App; use Phroute\Phroute\RouteCollector; +App::$collector->filter("auth", [\kernel\middlewares\AuthMiddleware::class, "handler"]); App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){ App::$collector->group(["before" => "auth"], function (RouteCollector $router){