api auth email

This commit is contained in:
Билай Станислав 2024-12-09 13:46:10 +03:00
parent 8778c4d725
commit 62ed358a4b
10 changed files with 156 additions and 43 deletions

View File

@ -46,6 +46,9 @@ class AdminConsoleController extends ConsoleController
$out = $this->migrationService->runAtPath("kernel/modules/post/migrations"); $out = $this->migrationService->runAtPath("kernel/modules/post/migrations");
$this->out->r("create post table", "green"); $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( $this->optionService->createFromParams(
key: "admin_theme_paths", key: "admin_theme_paths",
value: "{\"paths\": [\"{KERNEL_ADMIN_THEMES}\", \"{APP}/admin_themes\"]}", value: "{\"paths\": [\"{KERNEL_ADMIN_THEMES}\", \"{APP}/admin_themes\"]}",

View File

@ -11,6 +11,7 @@ use kernel\Mailing;
use kernel\modules\secure\models\forms\LoginEmailForm; use kernel\modules\secure\models\forms\LoginEmailForm;
use kernel\modules\secure\models\forms\LoginForm; use kernel\modules\secure\models\forms\LoginForm;
use kernel\modules\secure\models\forms\RegisterForm; use kernel\modules\secure\models\forms\RegisterForm;
use kernel\modules\secure\services\SecureService;
use kernel\modules\user\models\User; use kernel\modules\user\models\User;
use kernel\modules\user\service\UserService; use kernel\modules\user\service\UserService;
use kernel\Request; use kernel\Request;
@ -86,17 +87,19 @@ class SecureController extends AdminController
UserService::createUserByEmailAndPassword($email, $password); UserService::createUserByEmailAndPassword($email, $password);
$user = $this->userService->getByField('email', $email); $user = $this->userService->getByField('email', $email);
$mailing->send_html("register_by_code.php", ['code' => $user->auth_code, 'password' => $password], [ SecureService::createSecretCode($user);
$secretCode = SecureService::getByField("user_id", $user->id);
$mailing->send_html("register_by_code.php", ['code' => $secretCode->code, 'password' => $password], [
'address' => $email, 'address' => $email,
'subject' => "Код регистрации", 'subject' => "Код регистрации",
"from_name" => $_ENV['APP_NAME'] "from_name" => $_ENV['APP_NAME']
]); ]);
} else { } else {
$user->auth_code = mt_rand(100000, 999999);; SecureService::updateSecretCode($user);
$user->auth_code_expires_at = date("Y-m-d H:i:s", strtotime("+5 minutes")); $secretCode = SecureService::getByField("user_id", $user->id);
$user->save(); $mailing->send_html("login_by_code.php", ['code' => $secretCode->code], [
$mailing->send_html("login_by_code.php", ['code' => $user->auth_code], [
'address' => $email, 'address' => $email,
'subject' => "Код авторизации", 'subject' => "Код авторизации",
"from_name" => $_ENV['APP_NAME'] "from_name" => $_ENV['APP_NAME']
@ -120,7 +123,8 @@ class SecureController extends AdminController
throw new exception("User not found."); throw new exception("User not found.");
} }
$code = $request->post("code"); $code = $request->post("code");
if ($user->auth_code == $code && time() <= strtotime($user->auth_code_expires_at)) { $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); setcookie('user_id', $user->id, time() + 60 * 60 * 24, '/', $_SERVER['SERVER_NAME'], false);
$this->redirect("/admin", code: 302); $this->redirect("/admin", code: 302);
} else { } else {

View File

@ -7,10 +7,15 @@ use Firebase\JWT\Key;
use JetBrains\PhpStorm\NoReturn; use JetBrains\PhpStorm\NoReturn;
use kernel\App; use kernel\App;
use kernel\helpers\Debug; 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\models\User;
use kernel\modules\user\service\UserService;
use kernel\Request; use kernel\Request;
use kernel\RestController; use kernel\RestController;
use kernel\services\TokenService; use kernel\services\TokenService;
use PHPMailer\PHPMailer\Exception;
use Random\RandomException; use Random\RandomException;
class SecureRestController extends RestController class SecureRestController extends RestController
@ -51,32 +56,42 @@ class SecureRestController extends RestController
$this->renderApi($res); $this->renderApi($res);
} }
// #[NoReturn] public function actionEmailAuth(): void /**
// { * @throws Exception
// $request = new Request(); * @throws RandomException
// $data = $request->post(); */
// $model = $this->model->where('email', $data['email'])->first(); #[NoReturn] public function actionEmailAuth(): void
// $res = []; {
// if ($model) { $mailing = new Mailing();
// if (password_verify($data["password"], $model->password_hash)) { $request = new Request();
// $model->access_token_expires_at = date("Y-m-d H:i:s", strtotime(App::$secure['token_expired_time'])); $data = $request->post();
// $model->access_token = match (App::$secure['token_type']) { $model = $this->model->where('email', $data['email'])->first();
// "JWT" => TokenService::JWT($_ENV['SECRET_KEY'], 'HS256'),
// "md5" => TokenService::md5(), if (!$model) {
// "crypt" => TokenService::crypt(), $password = bin2hex(random_bytes(8));
// "hash" => TokenService::hash('sha256'),
// default => TokenService::random_bytes(20), UserService::createUserByEmailAndPassword($data['email'], $password);
// }; $model = UserService::getByField('email', $data['email']);
//
// $res = [ SecureService::createSecretCode($model);
// "access_token" => $model->access_token, $secretCode = SecureService::getByField("user_id", $model->id);
// "access_token_expires_at" => $model->access_token_expires_at,
// ];
// } $mailing->send_html("register_by_code.php", ['code' => $secretCode->code, 'password' => $password], [
// $model->save(); 'address' => $data['email'],
// } 'subject' => "Код регистрации",
// "from_name" => $_ENV['APP_NAME']
// $this->renderApi($res); ]);
// } } 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']
]);
}
}
} }

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

@ -23,6 +23,7 @@ App::$collector->group(["prefix" => "admin"], function (RouteCollector $router){
App::$collector->group(["prefix" => "api"], function (CgRouteCollector $router){ App::$collector->group(["prefix" => "api"], function (CgRouteCollector $router){
App::$collector->group(["prefix" => "secure"], 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('/auth', [\kernel\modules\secure\controllers\SecureRestController::class, 'actionAuth']);
App::$collector->post('/email_auth', [\kernel\modules\secure\controllers\SecureRestController::class, 'actionEmailAuth']);
}); });
}); });

View File

@ -0,0 +1,40 @@
<?php
namespace kernel\modules\secure\services;
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;
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->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();
}
}

View File

@ -19,8 +19,6 @@ return new class extends Migration
$table->string('email', 255); $table->string('email', 255);
$table->string('password_hash', 255); $table->string('password_hash', 255);
$table->integer('role')->default(1); $table->integer('role')->default(1);
$table->integer('auth_code')->default(1);
$table->dateTime('auth_code_expires_at')->nullable(true);
$table->string('access_token', 255)->nullable(true); $table->string('access_token', 255)->nullable(true);
$table->dateTime('access_token_expires_at')->nullable(true); $table->dateTime('access_token_expires_at')->nullable(true);
$table->timestamps(); $table->timestamps();

View File

@ -7,8 +7,6 @@ use Illuminate\Database\Eloquent\Model;
* @property string $username * @property string $username
* @property string $email * @property string $email
* @property string $password_hash * @property string $password_hash
* @property int $auth_code
* @property string $auth_code_expires_at
* @property string $access_token * @property string $access_token
* @property string $access_token_expires_at * @property string $access_token_expires_at
* @method static find($id) * @method static find($id)
@ -19,7 +17,7 @@ class User extends Model {
const ADMIN_USER_ROLE = 9; const ADMIN_USER_ROLE = 9;
protected $table = 'user'; protected $table = 'user';
protected $fillable = ['username', 'email', 'password_hash', 'role', 'auth_code', 'auth_code_expires_at', 'access_token', 'access_token_expires_at']; protected $fillable = ['username', 'email', 'password_hash', 'role', 'access_token', 'access_token_expires_at'];
protected array $dates = ['deleted at']; protected array $dates = ['deleted at'];
public static function labels(): array public static function labels(): array

View File

@ -41,7 +41,7 @@ class UserService
* @param string $value * @param string $value
* @return mixed * @return mixed
*/ */
public function getByField(string $field, string $value) public static function getByField(string $field, string $value): mixed
{ {
return User::where($field, $value)->first(); return User::where($field, $value)->first();
} }
@ -91,8 +91,6 @@ class UserService
$user->email = $email; $user->email = $email;
$user->username = $email; $user->username = $email;
$user->password_hash = password_hash($password, PASSWORD_DEFAULT); $user->password_hash = password_hash($password, PASSWORD_DEFAULT);
$user->auth_code = mt_rand(100000, 999999);
$user->auth_code_expires_at = date("Y-m-d H:i:s", strtotime("+5 minutes"));
$user->save(); $user->save();
} }