kernel, env, compoder, botstrap update

This commit is contained in:
Билай Станислав 2024-12-09 16:46:31 +03:00
parent 0e0bc80260
commit bfeb2d3c56
30 changed files with 926 additions and 56 deletions

View File

@ -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'

View File

@ -1,7 +1,8 @@
<?php
$secure_config = [
'token_type' => '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
];

View File

@ -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": {

149
composer.lock generated
View File

@ -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",

50
kernel/Mailing.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace kernel;
use kernel\helpers\Debug;
use kernel\helpers\SMTP;
use PHPMailer\PHPMailer\Exception;
class Mailing
{
protected SMTP $SMTP;
protected CgView $cgView;
protected array $data;
public function __construct(array $data = [])
{
$this->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()
{
}
}

View File

@ -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\"]}",

View File

@ -11,6 +11,18 @@ class Html
return "<img src='$src' $paramsStr>";
}
public static function h(string|int $type = 1, string $title = '', array $params = [])
{
$paramsStr = self::createParams($params);
return "<h$type $paramsStr>$title</h$type>";
}
public static function a(string $link, array $params = []): string
{
$paramsStr = self::createParams($params);
return "<a href='$link' $paramsStr>";
}
/**
* @param array $data
* @return string

View File

@ -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,
]);
}
}

40
kernel/helpers/SMTP.php Normal file
View File

@ -0,0 +1,40 @@
<?php
namespace kernel\helpers;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
class SMTP
{
public PHPMailer $mail;
public function __construct()
{
$this->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();
}
}

View File

@ -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,11 +39,16 @@ class ModuleShopClientController extends AdminController
*/
public function actionIndex(int $page_number = 1): void
{
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,
@ -46,6 +56,13 @@ class ModuleShopClientController extends AdminController
'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');
}
}

View File

@ -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']);
});
});
});

View File

@ -0,0 +1,36 @@
<?php
/**
* @var $email
*/
use itguild\forms\ActiveForm;
\kernel\widgets\ModuleTabsWidget::create()->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();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@ -0,0 +1,34 @@
<?php
use itguild\forms\ActiveForm;
\kernel\widgets\ModuleTabsWidget::create()->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();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@ -0,0 +1,6 @@
<?php
\kernel\widgets\ModuleTabsWidget::create()->run();
?>
<h1>Ошибка подключения к сервису</h1>

View File

@ -0,0 +1,9 @@
<?php
use itguild\forms\ActiveForm;
\kernel\widgets\ModuleTabsWidget::create()->run();
echo \kernel\helpers\Html::h(2, "Авторизация прошла успешно");
echo \kernel\helpers\Html::a("/admin", ['class' => 'btm btm-primary']);

View File

@ -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');
}

View File

@ -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);
}
/**
* @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']);
}
}

View File

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
\kernel\App::$db->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');
}
};

View File

@ -0,0 +1,25 @@
<?php
namespace kernel\modules\secure\models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property int $user_id
* @property int $code
* @property string $code_expires_at
*/
class SecretCode extends Model {
protected $table = 'secret_code';
protected $fillable = ['user_id', 'code', 'code_expires_at'];
public static function labels(): array
{
return [
'user_id' => 'Пользователь',
'code' => 'Код',
'code_expires_at' => 'Срок жизни кода',
];
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace kernel\modules\secure\models\forms;
use kernel\FormModel;
class LoginEmailForm extends FormModel
{
public function rules(): array
{
return [
'email' => 'required|string|email|max255',
];
}
}

View File

@ -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']);
});
});

View File

@ -0,0 +1,54 @@
<?php
namespace kernel\modules\secure\services;
use kernel\App;
use kernel\FormModel;
use kernel\helpers\Debug;
use kernel\modules\secure\models\SecretCode;
use kernel\modules\user\models\User;
use kernel\modules\user\service\UserService;
use kernel\services\TokenService;
class SecureService
{
public static function createSecretCode(User $user): void
{
$secretCode = new SecretCode();
$secretCode->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),
};
}
}

View File

@ -0,0 +1,48 @@
<!-- Section: Design Block -->
<section class=" text-center text-lg-start">
<style>
.rounded-t-5 {
border-top-left-radius: 0.5rem;
border-top-right-radius: 0.5rem;
}
@media (min-width: 992px) {
.rounded-tr-lg-0 {
border-top-right-radius: 0;
}
.rounded-bl-lg-5 {
border-bottom-left-radius: 0.5rem;
}
}
</style>
<div class="card mb-3">
<div class="row g-0 d-flex align-items-center">
<div class="col-lg-4 d-none d-lg-flex">
<img src="https://mdbootstrap.com/img/new/ecommerce/vertical/004.jpg" alt="Trendy Pants and Shoes"
class="w-100 rounded-t-5 rounded-tr-lg-0 rounded-bl-lg-5" />
</div>
<div class="col-lg-8">
<div class="card-body py-5 px-md-5">
<div class="row md-4 text-md-center">
<h1>Форма авторизации/регистрации</h1>
</div>
<form action="/admin/email_auth" method="post">
<!-- Email input -->
<div data-mdb-input-init class="form-outline mb-4">
<input type="text" id="form2Example1" class="form-control" name="email" />
<label class="form-label" for="form2Example1">Email</label>
</div>
<!-- Submit button -->
<button type="submit" data-mdb-button-init data-mdb-ripple-init class="btn btn-primary btn-block mb-4">Отправить</button>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- Section: Design Block -->

View File

@ -0,0 +1,60 @@
<?php
/**
* @var string $email
*/
?>
<!-- Section: Design Block -->
<section class=" text-center text-lg-start">
<style>
.rounded-t-5 {
border-top-left-radius: 0.5rem;
border-top-right-radius: 0.5rem;
}
@media (min-width: 992px) {
.rounded-tr-lg-0 {
border-top-right-radius: 0;
}
.rounded-bl-lg-5 {
border-bottom-left-radius: 0.5rem;
}
}
</style>
<div class="card mb-3">
<div class="row g-0 d-flex align-items-center">
<div class="col-lg-4 d-none d-lg-flex">
<img src="https://mdbootstrap.com/img/new/ecommerce/vertical/004.jpg" alt="Trendy Pants and Shoes"
class="w-100 rounded-t-5 rounded-tr-lg-0 rounded-bl-lg-5" />
</div>
<div class="col-lg-8">
<div class="card-body py-5 px-md-5">
<div class="row md-4 text-md-center">
<h1>Введите код, отправленный на почту "<?php echo $email ?>"</h1>
</div>
<form action="/admin/code_check" method="post">
<!-- Email input -->
<div data-mdb-input-init class="form-outline mb-4">
<input type="text" id="form2Example1" class="form-control" name="code" />
<label class="form-label" for="form2Example1">Код подтверждения</label>
</div>
<div class="row-md-4">
<div class="col">
<button type="submit" data-mdb-button-init data-mdb-ripple-init class="btn btn-primary btn-block mb-4">Подтвердить</button>
</div>
<div class="col">
<br>
<a href="/admin/login/"> <h5>Отправить код еще раз</h5></a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- Section: Design Block -->

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace kernel\services;
use GuzzleHttp\Exception\GuzzleException;
use kernel\helpers\RESTClient;
class ModuleShopService
{
protected string $url;
protected string $token;
public function __construct()
{
$this->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);
}
}

View File

@ -0,0 +1,12 @@
<?php
/**
* @var int $code
*/
?>
<p>
Код подтверждения: <?= $code ?>
</p>
<p>
Если вы не запрашивали код, проигнорируйте данное письмо.
</p>

View File

@ -0,0 +1,15 @@
<?php
/**
* @var int $code
* @var string $password
*/
?>
<p>
Код подтверждения: <?= $code ?> <br><br>
Ваш пароль: <?= $password ?>
</p>
<p>
Если вы не запрашивали код, проигнорируйте данное письмо.
</p>

View File

@ -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();