diff --git a/.env.example b/.env.example index 64e043c..ffddf4b 100644 --- a/.env.example +++ b/.env.example @@ -1,8 +1,10 @@ +APP_NAME="It Guild Micro Framework" + DB_HOST=localhost -DB_USER=user +DB_USER={db_user} DB_DRIVER=mysql -DB_PASSWORD=password -DB_NAME=name +DB_PASSWORD={db_password} +DB_NAME={db_name} DB_CHARSET=utf8mb4 DB_COLLATION=utf8mb4_unicode_ci DB_PREFIX='' @@ -10,6 +12,11 @@ DB_PREFIX='' VIEWS_PATH=/views VIEWS_CACHE_PATH=/views_cache +MAIL_SMTP_HOST=smtp.mail.ru +MAIL_SMTP_PORT=587 +MAIL_SMTP_USERNAME=username@mail.ru +MAIL_SMTP_PASSWORD=somepassword + MODULE_SHOP_URL='http://igfs.loc' MODULE_SHOP_TOKEN='your token' diff --git a/bootstrap/secure.php b/bootstrap/secure.php index a800dda..714beb3 100644 --- a/bootstrap/secure.php +++ b/bootstrap/secure.php @@ -1,7 +1,8 @@ 'JWT', // random_bytes, md5, crypt, hash, JWT + 'web_auth_type' => 'email_code', // login_password, email_code + 'token_type' => 'crypt', // random_bytes, md5, crypt, hash, JWT 'token_expired_time' => "+30 days", // +1 day ]; diff --git a/composer.json b/composer.json index 00bbe7e..ecf8197 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,8 @@ "josantonius/session": "^2.0", "firebase/php-jwt": "^6.10", "k-adam/env-editor": "^2.0", - "guzzlehttp/guzzle": "^7.9" + "guzzlehttp/guzzle": "^7.9", + "phpmailer/phpmailer": "^6.9" }, "autoload": { "psr-4": { diff --git a/composer.lock b/composer.lock index 2f5296e..08443a2 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "9b8653e1a4f451d6e125cb1732ffdeef", + "content-hash": "18fbb67ed0b66029e924b0a6d32f646f", "packages": [ { "name": "brick/math", @@ -1607,6 +1607,87 @@ ], "time": "2024-11-07T17:46:48+00:00" }, + { + "name": "phpmailer/phpmailer", + "version": "v6.9.3", + "source": { + "type": "git", + "url": "https://github.com/PHPMailer/PHPMailer.git", + "reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/2f5c94fe7493efc213f643c23b1b1c249d40f47e", + "reference": "2f5c94fe7493efc213f643c23b1b1c249d40f47e", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-filter": "*", + "ext-hash": "*", + "php": ">=5.5.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "^1.0", + "doctrine/annotations": "^1.2.6 || ^1.13.3", + "php-parallel-lint/php-console-highlighter": "^1.0.0", + "php-parallel-lint/php-parallel-lint": "^1.3.2", + "phpcompatibility/php-compatibility": "^9.3.5", + "roave/security-advisories": "dev-latest", + "squizlabs/php_codesniffer": "^3.7.2", + "yoast/phpunit-polyfills": "^1.0.4" + }, + "suggest": { + "decomplexity/SendOauth2": "Adapter for using XOAUTH2 authentication", + "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses", + "ext-openssl": "Needed for secure SMTP sending and DKIM signing", + "greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)", + "thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication" + }, + "type": "library", + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-only" + ], + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "support": { + "issues": "https://github.com/PHPMailer/PHPMailer/issues", + "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.9.3" + }, + "funding": [ + { + "url": "https://github.com/Synchro", + "type": "github" + } + ], + "time": "2024-11-24T18:04:13+00:00" + }, { "name": "phpoption/phpoption", "version": "1.9.3", @@ -2139,16 +2220,16 @@ }, { "name": "symfony/clock", - "version": "v7.1.6", + "version": "v7.2.0", "source": { "type": "git", "url": "https://github.com/symfony/clock.git", - "reference": "97bebc53548684c17ed696bc8af016880f0f098d" + "reference": "b81435fbd6648ea425d1ee96a2d8e68f4ceacd24" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/clock/zipball/97bebc53548684c17ed696bc8af016880f0f098d", - "reference": "97bebc53548684c17ed696bc8af016880f0f098d", + "url": "https://api.github.com/repos/symfony/clock/zipball/b81435fbd6648ea425d1ee96a2d8e68f4ceacd24", + "reference": "b81435fbd6648ea425d1ee96a2d8e68f4ceacd24", "shasum": "" }, "require": { @@ -2193,7 +2274,7 @@ "time" ], "support": { - "source": "https://github.com/symfony/clock/tree/v7.1.6" + "source": "https://github.com/symfony/clock/tree/v7.2.0" }, "funding": [ { @@ -2209,7 +2290,7 @@ "type": "tidelift" } ], - "time": "2024-09-25T14:20:29+00:00" + "time": "2024-09-25T14:21:43+00:00" }, { "name": "symfony/deprecation-contracts", @@ -2280,16 +2361,16 @@ }, { "name": "symfony/finder", - "version": "v7.1.6", + "version": "v7.2.0", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "2cb89664897be33f78c65d3d2845954c8d7a43b8" + "reference": "6de263e5868b9a137602dd1e33e4d48bfae99c49" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/2cb89664897be33f78c65d3d2845954c8d7a43b8", - "reference": "2cb89664897be33f78c65d3d2845954c8d7a43b8", + "url": "https://api.github.com/repos/symfony/finder/zipball/6de263e5868b9a137602dd1e33e4d48bfae99c49", + "reference": "6de263e5868b9a137602dd1e33e4d48bfae99c49", "shasum": "" }, "require": { @@ -2324,7 +2405,7 @@ "description": "Finds files and directories via an intuitive fluent interface", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/finder/tree/v7.1.6" + "source": "https://github.com/symfony/finder/tree/v7.2.0" }, "funding": [ { @@ -2340,7 +2421,7 @@ "type": "tidelift" } ], - "time": "2024-10-01T08:31:23+00:00" + "time": "2024-10-23T06:56:12+00:00" }, { "name": "symfony/polyfill-ctype", @@ -2368,8 +2449,8 @@ "type": "library", "extra": { "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" } }, "autoload": { @@ -2521,8 +2602,8 @@ "type": "library", "extra": { "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" } }, "autoload": { @@ -2601,8 +2682,8 @@ "type": "library", "extra": { "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" } }, "autoload": { @@ -2677,8 +2758,8 @@ "type": "library", "extra": { "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" } }, "autoload": { @@ -2735,20 +2816,21 @@ }, { "name": "symfony/translation", - "version": "v7.1.6", + "version": "v7.2.0", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "b9f72ab14efdb6b772f85041fa12f820dee8d55f" + "reference": "dc89e16b44048ceecc879054e5b7f38326ab6cc5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/b9f72ab14efdb6b772f85041fa12f820dee8d55f", - "reference": "b9f72ab14efdb6b772f85041fa12f820dee8d55f", + "url": "https://api.github.com/repos/symfony/translation/zipball/dc89e16b44048ceecc879054e5b7f38326ab6cc5", + "reference": "dc89e16b44048ceecc879054e5b7f38326ab6cc5", "shasum": "" }, "require": { "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3", "symfony/polyfill-mbstring": "~1.0", "symfony/translation-contracts": "^2.5|^3.0" }, @@ -2809,7 +2891,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v7.1.6" + "source": "https://github.com/symfony/translation/tree/v7.2.0" }, "funding": [ { @@ -2825,7 +2907,7 @@ "type": "tidelift" } ], - "time": "2024-09-28T12:35:13+00:00" + "time": "2024-11-12T20:47:56+00:00" }, { "name": "symfony/translation-contracts", @@ -2957,16 +3039,16 @@ }, { "name": "twig/twig", - "version": "v3.15.0", + "version": "v3.16.0", "source": { "type": "git", "url": "https://github.com/twigphp/Twig.git", - "reference": "2d5b3964cc21d0188633d7ddce732dc8e874db02" + "reference": "475ad2dc97d65d8631393e721e7e44fb544f0561" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/twigphp/Twig/zipball/2d5b3964cc21d0188633d7ddce732dc8e874db02", - "reference": "2d5b3964cc21d0188633d7ddce732dc8e874db02", + "url": "https://api.github.com/repos/twigphp/Twig/zipball/475ad2dc97d65d8631393e721e7e44fb544f0561", + "reference": "475ad2dc97d65d8631393e721e7e44fb544f0561", "shasum": "" }, "require": { @@ -2977,6 +3059,7 @@ "symfony/polyfill-php81": "^1.29" }, "require-dev": { + "phpstan/phpstan": "^2.0", "psr/container": "^1.0|^2.0", "symfony/phpunit-bridge": "^5.4.9|^6.4|^7.0" }, @@ -3020,7 +3103,7 @@ ], "support": { "issues": "https://github.com/twigphp/Twig/issues", - "source": "https://github.com/twigphp/Twig/tree/v3.15.0" + "source": "https://github.com/twigphp/Twig/tree/v3.16.0" }, "funding": [ { @@ -3032,7 +3115,7 @@ "type": "tidelift" } ], - "time": "2024-11-17T15:59:19+00:00" + "time": "2024-11-29T08:27:05+00:00" }, { "name": "vlucas/phpdotenv", diff --git a/kernel/Mailing.php b/kernel/Mailing.php new file mode 100644 index 0000000..05b341c --- /dev/null +++ b/kernel/Mailing.php @@ -0,0 +1,50 @@ +cgView = new CgView(); + $this->cgView->viewPath = KERNEL_DIR . "/views/mailing/"; + + $this->data = $data; + + $this->SMTP = new SMTP(); + + $this->init(); + } + + /** + * @throws Exception + */ + public function send_html(string $tpl, array $tplParams, array $mailParams): ?false + { + $mailParams['body'] = $this->cgView->fetch($tpl, $tplParams); + return $this->SMTP->send_html($mailParams); + } + + public function run() + { + } + + public static function create(array $data = []): static + { + return new static($data); + } + + protected function init() + { + } + +} \ No newline at end of file diff --git a/kernel/console/controllers/AdminConsoleController.php b/kernel/console/controllers/AdminConsoleController.php index bce72d6..0af6f7b 100644 --- a/kernel/console/controllers/AdminConsoleController.php +++ b/kernel/console/controllers/AdminConsoleController.php @@ -46,6 +46,9 @@ class AdminConsoleController extends ConsoleController $out = $this->migrationService->runAtPath("kernel/modules/post/migrations"); $this->out->r("create post table", "green"); + $out = $this->migrationService->runAtPath("kernel/modules/secure/migrations"); + $this->out->r("create secret_code table", "green"); + $this->optionService->createFromParams( key: "admin_theme_paths", value: "{\"paths\": [\"{KERNEL_ADMIN_THEMES}\", \"{APP}/admin_themes\"]}", diff --git a/kernel/helpers/Html.php b/kernel/helpers/Html.php index 0b834c7..369290f 100644 --- a/kernel/helpers/Html.php +++ b/kernel/helpers/Html.php @@ -11,6 +11,18 @@ class Html return ""; } + public static function h(string|int $type = 1, string $title = '', array $params = []) + { + $paramsStr = self::createParams($params); + return "$title"; + } + + public static function a(string $link, array $params = []): string + { + $paramsStr = self::createParams($params); + return ""; + } + /** * @param array $data * @return string diff --git a/kernel/helpers/RESTClient.php b/kernel/helpers/RESTClient.php index 2706b01..c77cf1b 100644 --- a/kernel/helpers/RESTClient.php +++ b/kernel/helpers/RESTClient.php @@ -2,13 +2,17 @@ namespace kernel\helpers; +use GuzzleHttp\Exception\GuzzleException; use http\Client; class RESTClient { - public static function request(string $url, string $method = 'GET') + /** + * @throws GuzzleException + */ + public static function request(string $url, string $method = 'GET'): \Psr\Http\Message\ResponseInterface { $client = new \GuzzleHttp\Client(); return $client->request($method, $url, [ @@ -18,4 +22,31 @@ class RESTClient ]); } + /** + * @throws GuzzleException + */ + public static function request_without_auth(string $url, string $method = 'GET'): \Psr\Http\Message\ResponseInterface + { + $client = new \GuzzleHttp\Client(); + return $client->request($method, $url); + } + + /** + * @throws GuzzleException + */ + public static function post(string $url, array $data = [], bool $auth = true): \Psr\Http\Message\ResponseInterface + { + $headers = []; + if ($auth){ + $headers = [ + 'Authorization' => 'Bearer ' . $_ENV['MODULE_SHOP_TOKEN'] + ]; + } + $client = new \GuzzleHttp\Client(); + return $client->request("POST", $url, [ + 'form_params' => $data, + 'headers' => $headers, + ]); + } + } \ No newline at end of file diff --git a/kernel/helpers/SMTP.php b/kernel/helpers/SMTP.php new file mode 100644 index 0000000..0f6d5e6 --- /dev/null +++ b/kernel/helpers/SMTP.php @@ -0,0 +1,40 @@ +mail = new PHPMailer(true); + $this->mail->CharSet = 'UTF-8'; + $this->mail->isSMTP(); + $this->mail->SMTPAuth = true; + $this->mail->SMTPDebug = 0; + $this->mail->Host = $_ENV['MAIL_SMTP_HOST']; + $this->mail->Port = $_ENV['MAIL_SMTP_PORT']; + $this->mail->Username = $_ENV['MAIL_SMTP_USERNAME']; + $this->mail->Password = $_ENV['MAIL_SMTP_PASSWORD']; + } + + /** + * @throws Exception + */ + public function send_html(array $params) + { + if (!isset($params['address'])){ + return false; + } + $this->mail->setFrom($this->mail->Username, $params['from_name'] ?? $this->mail->Host); + $this->mail->addAddress($params['address']); + $this->mail->Subject = $params['subject'] ?? 'Без темы'; + $body = $params['body'] ?? 'Нет информации'; + $this->mail->msgHTML($body); + + $this->mail->send(); + } +} \ No newline at end of file diff --git a/kernel/modules/module_shop_client/controllers/ModuleShopClientController.php b/kernel/modules/module_shop_client/controllers/ModuleShopClientController.php index 6e7846b..a83f465 100644 --- a/kernel/modules/module_shop_client/controllers/ModuleShopClientController.php +++ b/kernel/modules/module_shop_client/controllers/ModuleShopClientController.php @@ -10,9 +10,14 @@ use kernel\Flash; use kernel\helpers\Debug; use kernel\helpers\Files; use kernel\helpers\RESTClient; +use kernel\helpers\SMTP; +use kernel\Mailing; use kernel\modules\module_shop_client\services\ModuleShopClientService; use kernel\Request; use kernel\services\ModuleService; +use kernel\services\ModuleShopService; +use kernel\services\TokenService; +use PHPMailer\PHPMailer\Exception; class ModuleShopClientController extends AdminController { @@ -34,18 +39,30 @@ class ModuleShopClientController extends AdminController */ public function actionIndex(int $page_number = 1): void { - $per_page = 8; - $modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug'); - $modules_info = json_decode($modules_info->getBody()->getContents(), true); - $module_count = count($modules_info); - $modules_info = array_slice($modules_info, $per_page*($page_number-1), $per_page); - $this->cgView->render("index.php", [ - 'modules_info' => $modules_info, - 'moduleService' => $this->moduleService, - 'page_number' => $page_number, - 'module_count' => $module_count, - 'per_page' => $per_page, - ]); + + if ($this->moduleService->issetModuleShopToken()) { + if ($this->moduleService->isServerAvailable()) { + + $per_page = 8; + $modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug'); + $modules_info = json_decode($modules_info->getBody()->getContents(), true); + $module_count = count($modules_info); + $modules_info = array_slice($modules_info, $per_page * ($page_number - 1), $per_page); + + $this->cgView->render("index.php", [ + 'modules_info' => $modules_info, + 'moduleService' => $this->moduleService, + 'page_number' => $page_number, + 'module_count' => $module_count, + 'per_page' => $per_page, + ]); + } else { + $this->cgView->render("module_shop_error_connection.php"); + } + + } else { + $this->cgView->render("login_at_module_shop.php"); + } } public function actionView(int $id): void @@ -106,4 +123,58 @@ class ModuleShopClientController extends AdminController $this->redirect('/admin/module_shop_client', 302); } + /** + * @throws Exception + */ + public function actionAuth(): void + { + $request = new Request(); + $address = $request->post("email"); + +// $mailing = new Mailing(); +// $mailing->send_html("login_by_code.php", ['code' => mt_rand(100000, 999999)], [ +// 'address' => $address, +// 'subject' => "Код авторизации", +// "from_name" => $_ENV['APP_NAME'] +// ]); + + $moduleShopService = new ModuleShopService(); + $result = $moduleShopService->email_auth($address); + + if ($result['status'] == 'success'){ + $this->cgView->render('enter_code.php', ['email' => $address]); + } + + $this->cgView->render('module_shop_error_connection.php', ['email' => $address]); + } + + public function actionCodeCheck(): void + { + $request = new Request(); + $code = $request->post("code"); + +// $mailing = new Mailing(); +// $mailing->send_html("login_by_code.php", ['code' => mt_rand(100000, 999999)], [ +// 'address' => $address, +// 'subject' => "Код авторизации", +// "from_name" => $_ENV['APP_NAME'] +// ]); + + $moduleShopService = new ModuleShopService(); + $result = $moduleShopService->code_check($code); + + if (isset($result['access_token'])){ + + $envFile = \EnvEditor\EnvFile::loadFrom(ROOT_DIR . "/.env"); + + $envFile->setValue("MODULE_SHOP_TOKEN", $result['access_token']); + + $envFile->saveTo(ROOT_DIR . "/.env"); + + $this->cgView->render('success_login.php'); + } + + $this->cgView->render('module_shop_error_connection.php'); + } + } \ No newline at end of file diff --git a/kernel/modules/module_shop_client/routs/module_shop_client.php b/kernel/modules/module_shop_client/routs/module_shop_client.php index 416831c..5004486 100644 --- a/kernel/modules/module_shop_client/routs/module_shop_client.php +++ b/kernel/modules/module_shop_client/routs/module_shop_client.php @@ -15,6 +15,8 @@ App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){ App::$collector->get('/view/{id}', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionView']); App::$collector->get('/delete', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionDelete']); App::$collector->get('/update', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionUpdate']); + App::$collector->post('/auth', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionAuth']); + App::$collector->post('/code_check', [\kernel\modules\module_shop_client\controllers\ModuleShopClientController::class, 'actionCodeCheck']); }); }); }); \ No newline at end of file diff --git a/kernel/modules/module_shop_client/views/enter_code.php b/kernel/modules/module_shop_client/views/enter_code.php new file mode 100644 index 0000000..7befe28 --- /dev/null +++ b/kernel/modules/module_shop_client/views/enter_code.php @@ -0,0 +1,36 @@ +run(); + +echo \kernel\helpers\Html::h(2, "Введите код подтверждения отправленный на почту \"$email\""); + +$form = new ActiveForm(); +$form->beginForm("/admin/module_shop_client/code_check/"); + +$form->field(\itguild\forms\inputs\TextInput::class, 'code', [ + 'class' => "form-control", + 'placeholder' => 'Код', +]) + ->setLabel("Код") + ->render(); +?> + +
+
+ field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [ + 'class' => "btn btn-primary ", + 'value' => 'Отправить', + 'typeInput' => 'submit' + ]) + ->render(); + ?> +
+ +
+endForm(); \ No newline at end of file diff --git a/kernel/modules/module_shop_client/views/login_at_module_shop.php b/kernel/modules/module_shop_client/views/login_at_module_shop.php new file mode 100644 index 0000000..b635740 --- /dev/null +++ b/kernel/modules/module_shop_client/views/login_at_module_shop.php @@ -0,0 +1,34 @@ +run(); + +echo \kernel\helpers\Html::h(2, "Форма авторизации/регистрации"); + +$form = new ActiveForm(); +$form->beginForm("/admin/module_shop_client/auth/"); + +$form->field(\itguild\forms\inputs\TextInput::class, 'email', [ + 'class' => "form-control", + 'placeholder' => 'Email', +]) + ->setLabel("Email") + ->render(); +?> + +
+
+ field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [ + 'class' => "btn btn-primary ", + 'value' => 'Отправить', + 'typeInput' => 'submit' + ]) + ->render(); + ?> +
+ +
+endForm(); \ No newline at end of file diff --git a/kernel/modules/module_shop_client/views/module_shop_error_connection.php b/kernel/modules/module_shop_client/views/module_shop_error_connection.php new file mode 100644 index 0000000..bf31edd --- /dev/null +++ b/kernel/modules/module_shop_client/views/module_shop_error_connection.php @@ -0,0 +1,6 @@ +run(); +?> + +

Ошибка подключения к сервису

+ diff --git a/kernel/modules/module_shop_client/views/success_login.php b/kernel/modules/module_shop_client/views/success_login.php new file mode 100644 index 0000000..927f680 --- /dev/null +++ b/kernel/modules/module_shop_client/views/success_login.php @@ -0,0 +1,9 @@ +run(); + +echo \kernel\helpers\Html::h(2, "Авторизация прошла успешно"); +echo \kernel\helpers\Html::a("/admin", ['class' => 'btm btm-primary']); + diff --git a/kernel/modules/secure/controllers/SecureController.php b/kernel/modules/secure/controllers/SecureController.php index bdea8ab..8498c77 100644 --- a/kernel/modules/secure/controllers/SecureController.php +++ b/kernel/modules/secure/controllers/SecureController.php @@ -4,11 +4,19 @@ namespace kernel\modules\secure\controllers; use JetBrains\PhpStorm\NoReturn; use kernel\AdminController; +use kernel\App; use kernel\Flash; use kernel\helpers\Debug; +use kernel\Mailing; +use kernel\modules\secure\models\forms\LoginEmailForm; use kernel\modules\secure\models\forms\LoginForm; use kernel\modules\secure\models\forms\RegisterForm; +use kernel\modules\secure\services\SecureService; +use kernel\modules\user\models\User; use kernel\modules\user\service\UserService; +use kernel\Request; +use PHPMailer\PHPMailer\Exception; +use Random\RandomException; class SecureController extends AdminController { @@ -24,7 +32,12 @@ class SecureController extends AdminController public function actionLogin(): void { - $this->cgView->render('login.php'); + $this->cgView->render(match (App::$secure['web_auth_type']) { + "login_password" => "login.php", + "email_code" => "email_login.php", + }); + +// $this->cgView->render('login.php'); } #[NoReturn] public function actionAuth(): void @@ -54,14 +67,83 @@ class SecureController extends AdminController } } + /** + * @throws RandomException + * @throws Exception + */ + public function actionEmailAuth(): void + { + $mailing = new Mailing(); + + $loginForm = new LoginEmailForm(); + $loginForm->load($_REQUEST); + + $email = $loginForm->getItem("email"); + $user = $this->userService->getByField('email', $email); + + if (!$user){ + $password = bin2hex(random_bytes(8)); + + UserService::createUserByEmailAndPassword($email, $password); + $user = $this->userService->getByField('email', $email); + + SecureService::createSecretCode($user); + $secretCode = SecureService::getByField("user_id", $user->id); + + + $mailing->send_html("register_by_code.php", ['code' => $secretCode->code, 'password' => $password], [ + 'address' => $email, + 'subject' => "Код регистрации", + "from_name" => $_ENV['APP_NAME'] + ]); + } else { + SecureService::updateSecretCode($user); + $secretCode = SecureService::getByField("user_id", $user->id); + $mailing->send_html("login_by_code.php", ['code' => $secretCode->code], [ + 'address' => $email, + 'subject' => "Код авторизации", + "from_name" => $_ENV['APP_NAME'] + ]); + } + + setcookie('user_email', $email, time()+60*15, '/', $_SERVER['SERVER_NAME'], false); + $this->cgView->render("enter_code.php", ['email' => $email]); + } + + /** + * @throws Exception + */ + public function actionCodeCheck(): void + { + $request = new Request(); + + if (isset($_COOKIE['user_email'])) { + $user = User::where('email', $_COOKIE["user_email"])->first(); + if (!$user) { + throw new exception("User not found."); + } + $code = $request->post("code"); + $secretCode = SecureService::getByField("user_id", $user->id); + if ($secretCode->code == $code && time() <= strtotime($secretCode->code_expires_at)) { + setcookie('user_id', $user->id, time() + 60 * 60 * 24, '/', $_SERVER['SERVER_NAME'], false); + $this->redirect("/admin", code: 302); + } else { + Flash::setMessage("error", "Wrong code."); + $this->cgView->render("enter_code.php", ['email' => $_COOKIE["user_email"]]); + } + + } + } + #[NoReturn] public function actionLogout(): void { unset($_COOKIE['user_id']); setcookie('user_id', "", -1, '/', ".".$_SERVER['SERVER_NAME'], false); + setcookie('user_email', "", -1, '/', ".".$_SERVER['SERVER_NAME'], false); $this->redirect("/", code: 302); } - public function actionRegister() + public function actionRegister(): void { $this->cgView->render('register.php'); } diff --git a/kernel/modules/secure/controllers/SecureRestController.php b/kernel/modules/secure/controllers/SecureRestController.php index 42ede4a..7e82699 100644 --- a/kernel/modules/secure/controllers/SecureRestController.php +++ b/kernel/modules/secure/controllers/SecureRestController.php @@ -7,10 +7,15 @@ use Firebase\JWT\Key; use JetBrains\PhpStorm\NoReturn; use kernel\App; use kernel\helpers\Debug; +use kernel\Mailing; +use kernel\modules\secure\models\SecretCode; +use kernel\modules\secure\services\SecureService; use kernel\modules\user\models\User; +use kernel\modules\user\service\UserService; use kernel\Request; use kernel\RestController; use kernel\services\TokenService; +use PHPMailer\PHPMailer\Exception; use Random\RandomException; class SecureRestController extends RestController @@ -51,4 +56,75 @@ class SecureRestController extends RestController $this->renderApi($res); } -} \ No newline at end of file + /** + * @throws Exception + * @throws RandomException + */ + #[NoReturn] public function actionEmailAuth(): void + { + $mailing = new Mailing(); + $request = new Request(); + $data = $request->post(); + $model = $this->model->where('email', $data['email'])->first(); + + if (!$model) { + $password = bin2hex(random_bytes(8)); + + UserService::createUserByEmailAndPassword($data['email'], $password); + $model = UserService::getByField('email', $data['email']); + + SecureService::createSecretCode($model); + $secretCode = SecureService::getByField("user_id", $model->id); + + + $mailing->send_html("register_by_code.php", ['code' => $secretCode->code, 'password' => $password], [ + 'address' => $data['email'], + 'subject' => "Код регистрации", + "from_name" => $_ENV['APP_NAME'] + ]); + } else { + SecureService::updateSecretCode($model); + $secretCode = SecureService::getByField("user_id", $model->id); + + $mailing->send_html("login_by_code.php", ['code' => $secretCode->code], [ + 'address' => $data['email'], + 'subject' => "Код авторизации", + "from_name" => $_ENV['APP_NAME'] + ]); + } + + $res = [ + "status" => "success", + "code_expires_at" => $secretCode->code_expires_at, + ]; + + setcookie('user_email', $data['email'], time()+60*15, '/', $_SERVER['SERVER_NAME'], false); + $this->renderApi($res); + } + + /** + * @throws Exception + */ + #[NoReturn] public function actionCodeCheck(): void + { + $request = new Request(); + $code = $request->post("code"); + + $model = SecretCode::where("code", $code)->first(); + if (time() <= strtotime($model->code_expires_at)) { + $user = $this->model->where("id", $model->user_id)->first(); + if ($user){ + $user->access_token_expires_at = date("Y-m-d H:i:s", strtotime(App::$secure['token_expired_time'])); + $user->access_token = SecureService::generateAccessToken(); + $user->save(); + $this->renderApi([ + "access_token" => $user->access_token, + "access_token_expires_at" => $user->access_token_expires_at, + ]); + } + } + + $this->renderApi(['status' => 'error', 'message' => 'incorrect code']); + } + +} diff --git a/kernel/modules/secure/migrations/2024_12_09_081420_create_secret_code_table.php b/kernel/modules/secure/migrations/2024_12_09_081420_create_secret_code_table.php new file mode 100644 index 0000000..c5acce1 --- /dev/null +++ b/kernel/modules/secure/migrations/2024_12_09_081420_create_secret_code_table.php @@ -0,0 +1,31 @@ +schema->create('secret_code', function (Blueprint $table) { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('code'); + $table->dateTime('code_expires_at')->nullable(true); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + \kernel\App::$db->schema->dropIfExists('secret_code'); + + } +}; diff --git a/kernel/modules/secure/models/SecretCode.php b/kernel/modules/secure/models/SecretCode.php new file mode 100644 index 0000000..0caaa60 --- /dev/null +++ b/kernel/modules/secure/models/SecretCode.php @@ -0,0 +1,25 @@ + 'Пользователь', + 'code' => 'Код', + 'code_expires_at' => 'Срок жизни кода', + ]; + } + +} diff --git a/kernel/modules/secure/models/forms/LoginEmailForm.php b/kernel/modules/secure/models/forms/LoginEmailForm.php new file mode 100644 index 0000000..201817a --- /dev/null +++ b/kernel/modules/secure/models/forms/LoginEmailForm.php @@ -0,0 +1,17 @@ + 'required|string|email|max255', + ]; + } + +} \ No newline at end of file diff --git a/kernel/modules/secure/routs/secure.php b/kernel/modules/secure/routs/secure.php index 0377475..be041d8 100644 --- a/kernel/modules/secure/routs/secure.php +++ b/kernel/modules/secure/routs/secure.php @@ -14,13 +14,17 @@ App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){ App::$collector->get('/login', [\kernel\modules\secure\controllers\SecureController::class, 'actionLogin']); App::$collector->get('/logout', [\kernel\modules\secure\controllers\SecureController::class, 'actionLogout']); App::$collector->post('/auth', [\kernel\modules\secure\controllers\SecureController::class, 'actionAuth']); + App::$collector->post('/email_auth', [\kernel\modules\secure\controllers\SecureController::class, 'actionEmailAuth']); App::$collector->get('/register', [\kernel\modules\secure\controllers\SecureController::class, 'actionRegister']); App::$collector->post('/registration', [\kernel\modules\secure\controllers\SecureController::class, 'actionRegistration']); + App::$collector->post('/code_check', [\kernel\modules\secure\controllers\SecureController::class, 'actionCodeCheck']); }); App::$collector->group(["prefix" => "api"], function (CgRouteCollector $router){ App::$collector->group(["prefix" => "secure"], function (CgRouteCollector $router) { App::$collector->post('/auth', [\kernel\modules\secure\controllers\SecureRestController::class, 'actionAuth']); + App::$collector->post('/email_auth', [\kernel\modules\secure\controllers\SecureRestController::class, 'actionEmailAuth']); + App::$collector->post('/code_check', [\kernel\modules\secure\controllers\SecureRestController::class, 'actionCodeCheck']); }); }); diff --git a/kernel/modules/secure/services/SecureService.php b/kernel/modules/secure/services/SecureService.php new file mode 100644 index 0000000..b47f4d4 --- /dev/null +++ b/kernel/modules/secure/services/SecureService.php @@ -0,0 +1,54 @@ +user_id = $user->id; + $secretCode->code = mt_rand(100000, 999999); + $secretCode->code_expires_at = date("Y-m-d H:i:s", strtotime("+5 minutes"));; + $secretCode->save(); + } + + public static function updateSecretCode(User $user): void + { + $secretCode = SecretCode::where('user_id', $user->id)->first(); + $secretCode->code = mt_rand(100000, 999999); + $secretCode->code_expires_at = date("Y-m-d H:i:s", strtotime("+5 minutes"));; + $secretCode->save(); + } + + public static function getCodeByUserId(int $user_id) + { + return SecretCode::where('user_id', $user_id)->one()->code; + } + + public static function getByField(string $field, mixed $value) + { + return SecretCode::where($field, $value)->first(); + } + + public static function generateAccessToken(): string + { + return match (App::$secure['token_type']) { + "JWT" => TokenService::JWT($_ENV['SECRET_KEY'], 'HS256'), + "md5" => TokenService::md5(), + "crypt" => TokenService::crypt(), + "hash" => TokenService::hash('sha256'), + default => TokenService::random_bytes(20), + }; + } + +} \ No newline at end of file diff --git a/kernel/modules/secure/views/email_login.php b/kernel/modules/secure/views/email_login.php new file mode 100644 index 0000000..eadc71b --- /dev/null +++ b/kernel/modules/secure/views/email_login.php @@ -0,0 +1,48 @@ + +
+ +
+
+
+ Trendy Pants and Shoes +
+
+
+
+

Форма авторизации/регистрации

+
+ +
+ +
+ + +
+ + + + +
+ +
+
+
+
+
+ \ No newline at end of file diff --git a/kernel/modules/secure/views/enter_code.php b/kernel/modules/secure/views/enter_code.php new file mode 100644 index 0000000..57aed3a --- /dev/null +++ b/kernel/modules/secure/views/enter_code.php @@ -0,0 +1,60 @@ + + + +
+ +
+ +
+
+ \ No newline at end of file diff --git a/kernel/modules/user/service/UserService.php b/kernel/modules/user/service/UserService.php index 077edab..9e8dd5d 100644 --- a/kernel/modules/user/service/UserService.php +++ b/kernel/modules/user/service/UserService.php @@ -41,7 +41,7 @@ class UserService * @param string $value * @return mixed */ - public function getByField(string $field, string $value) + public static function getByField(string $field, string $value): mixed { return User::where($field, $value)->first(); } @@ -85,4 +85,13 @@ class UserService return $this->getByField("access_token", $token); } + public static function createUserByEmailAndPassword(string $email, string $password): void + { + $user = new User(); + $user->email = $email; + $user->username = $email; + $user->password_hash = password_hash($password, PASSWORD_DEFAULT); + $user->save(); + } + } \ No newline at end of file diff --git a/kernel/services/ModuleService.php b/kernel/services/ModuleService.php index c112e2f..50a3603 100644 --- a/kernel/services/ModuleService.php +++ b/kernel/services/ModuleService.php @@ -476,6 +476,10 @@ class ModuleService if ($this->isServerAvailable()){ $modules_info = RESTClient::request($_ENV['MODULE_SHOP_URL'] . '/api/module_shop/gb_slug'); + if (!$this->issetModuleShopToken()){ + return false; + } + $modules_info = json_decode($modules_info->getBody()->getContents(), true); $mod_info = $this->getModuleInfoBySlug($slug); foreach ($modules_info as $mod) { @@ -516,4 +520,13 @@ class ModuleService } } + public function issetModuleShopToken(): bool + { + if (!empty($_ENV['MODULE_SHOP_TOKEN'])){ + return true; + } + + return false; + } + } \ No newline at end of file diff --git a/kernel/services/ModuleShopService.php b/kernel/services/ModuleShopService.php new file mode 100644 index 0000000..72562ad --- /dev/null +++ b/kernel/services/ModuleShopService.php @@ -0,0 +1,36 @@ +url = $_ENV['MODULE_SHOP_URL']; + $this->token = $_ENV['MODULE_SHOP_TOKEN']; + } + + /** + * @throws GuzzleException + */ + public function email_auth(string $email) + { + $request = RESTClient::post($this->url . "/api/secure/email_auth", ['email' => $email], false); + + return json_decode($request->getBody()->getContents(), true); + } + + public function code_check(string $code) + { + $request = RESTClient::post($this->url . "/api/secure/code_check", ['code' => $code], false); + + return json_decode($request->getBody()->getContents(), true); + } + +} \ No newline at end of file diff --git a/kernel/views/mailing/login_by_code.php b/kernel/views/mailing/login_by_code.php new file mode 100644 index 0000000..a172e1d --- /dev/null +++ b/kernel/views/mailing/login_by_code.php @@ -0,0 +1,12 @@ + + +

+ Код подтверждения: +

+

+ Если вы не запрашивали код, проигнорируйте данное письмо. +

\ No newline at end of file diff --git a/kernel/views/mailing/register_by_code.php b/kernel/views/mailing/register_by_code.php new file mode 100644 index 0000000..4dc6a54 --- /dev/null +++ b/kernel/views/mailing/register_by_code.php @@ -0,0 +1,15 @@ + + +

+ Код подтверждения:

+ Ваш пароль: +

+ +

+ Если вы не запрашивали код, проигнорируйте данное письмо. +

\ No newline at end of file diff --git a/kernel/views/module/index.php b/kernel/views/module/index.php index 52c6bcb..8cb34f8 100644 --- a/kernel/views/module/index.php +++ b/kernel/views/module/index.php @@ -75,9 +75,11 @@ $table->addAction(function ($row) use ($moduleService){ return false; }); -if ($moduleService->isActive('module_shop_client') && $moduleService->isServerAvailable()) { +if ($moduleService->isActive('module_shop_client')) { ModuleTabsWidget::create()->run(); } + + $table->create(); $table->render();