api secure auth

This commit is contained in:
2024-10-18 13:45:18 +03:00
parent bda9b03a9f
commit 68615d1f8d
4 changed files with 116 additions and 31 deletions

View File

@ -2,6 +2,8 @@
namespace kernel\modules\secure\controllers;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use JetBrains\PhpStorm\NoReturn;
use kernel\helpers\Debug;
use kernel\modules\user\models\User;
@ -19,19 +21,37 @@ class SecureRestController extends RestController
{
$request = new Request();
$data = $request->post();
$model = $this->model->where(['username', $data['username']])->first();
$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"))
],
key: $model->{'password_hash'},
alg: 'HS256'
);
$access_token = 123124312313;
$access_token_expires_at = time() + 3600;
$model->{'access_token'} = $jwt;
$model->{'access_token_expires_at'} =
JWT::decode($jwt, new Key($model->{'password_hash'}, 'HS256'))->exp;
$model->{'access_token'} = $access_token;
$model->{'access_token_expires_at'} = $access_token_expires_at;
foreach ($model->getFillable() as $item){
$model->{$item} = $data[$item] ?? null;
$res = [
"access_token" => $model->{'access_token'},
"access_token_expires_at" => $model->{'access_token_expires_at'},
];
}
$model->save();
}
$this->renderApi($res);
$model->save();
$this->renderApi($this->model->toArray());
}
}