MicroFrameWork/kernel/modules/secure/middlewares/BearerAuthMiddleware.php

48 lines
1.2 KiB
PHP
Raw Normal View History

2024-10-22 11:09:35 +03:00
<?php
namespace kernel\modules\secure\middlewares;
use JetBrains\PhpStorm\NoReturn;
use kernel\App;
use kernel\helpers\Debug;
use kernel\Middleware;
use kernel\modules\user\service\UserService;
use kernel\Request;
class BearerAuthMiddleware extends Middleware
{
protected UserService $userService;
public function __construct()
{
$this->userService = new UserService();
}
function handler(): void
{
$request = new Request();
$authorization = $request->getHeader("Authorization");
if ($authorization){
$authorization = explode(" ", $authorization);
$type = $authorization[0];
$token = $authorization[1];
if ($type === "Bearer"){
$user = $this->userService->getByAccessToken($token);
if ($user){
if ($user->access_token_expires_at > date("Y-m-d")){
App::$user = $user;
return;
}
}
}
}
$this->returnError(403);
}
#[NoReturn] public function returnError(int $code): void
{
http_response_code($code);
die('Forbidden');
}
}