2024-10-17 16:47:04 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace kernel\modules\secure\controllers;
|
|
|
|
|
2024-10-18 13:45:18 +03:00
|
|
|
use Firebase\JWT\JWT;
|
|
|
|
use Firebase\JWT\Key;
|
2024-10-17 16:47:04 +03:00
|
|
|
use JetBrains\PhpStorm\NoReturn;
|
|
|
|
use kernel\helpers\Debug;
|
|
|
|
use kernel\modules\user\models\User;
|
|
|
|
use kernel\Request;
|
|
|
|
use kernel\RestController;
|
|
|
|
|
|
|
|
class SecureRestController extends RestController
|
|
|
|
{
|
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
$this->model = new User();
|
|
|
|
}
|
|
|
|
|
|
|
|
#[NoReturn] public function actionAuth(): void
|
|
|
|
{
|
|
|
|
$request = new Request();
|
|
|
|
$data = $request->post();
|
2024-10-18 13:45:18 +03:00
|
|
|
$model = $this->model->where('username', $data['username'])->first();
|
|
|
|
$res = [];
|
|
|
|
if ($model) {
|
|
|
|
if (password_verify($data["password"], $model->password_hash)) {
|
|
|
|
$baseUrl = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
|
|
|
|
$baseUrl .= $_SERVER['HTTP_HOST'];
|
|
|
|
// $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"))
|
|
|
|
],
|
2024-10-21 15:56:51 +03:00
|
|
|
key: $model->password_hash,
|
2024-10-18 13:45:18 +03:00
|
|
|
alg: 'HS256'
|
|
|
|
);
|
|
|
|
|
2024-10-21 15:56:51 +03:00
|
|
|
$model->access_token = $jwt;
|
|
|
|
$model->access_token_expires_at =
|
|
|
|
JWT::decode($jwt, new Key($model->password_hash, 'HS256'))->exp;
|
2024-10-18 13:45:18 +03:00
|
|
|
|
|
|
|
$res = [
|
2024-10-21 15:56:51 +03:00
|
|
|
"access_token" => $model->access_token,
|
|
|
|
"access_token_expires_at" => $model->access_token_expires_at,
|
2024-10-18 13:45:18 +03:00
|
|
|
];
|
|
|
|
}
|
|
|
|
$model->save();
|
2024-10-17 16:47:04 +03:00
|
|
|
}
|
2024-10-18 13:45:18 +03:00
|
|
|
|
|
|
|
$this->renderApi($res);
|
2024-10-17 16:47:04 +03:00
|
|
|
|
|
|
|
}
|
|
|
|
}
|