44 lines
1.2 KiB
PHP
44 lines
1.2 KiB
PHP
<?php
|
|
namespace WorkbloomERP\Middleware;
|
|
|
|
use Throwable;
|
|
use KrothiumAPI\Utils\HttpUtil;
|
|
use WorkbloomERP\Security\JwtService;
|
|
use WorkbloomERP\Security\AuthContext;
|
|
|
|
class AuthMiddleware {
|
|
private JwtService $jwtService;
|
|
|
|
public function __construct(?JwtService $jwtService = null) {
|
|
$this->jwtService = $jwtService ?? new JwtService();
|
|
}
|
|
|
|
/**
|
|
* Executa a validação de autenticação Bearer Token.
|
|
* Retorna true em caso de sucesso ou array estruturado de bloqueio (401).
|
|
*/
|
|
public function handle(): array|bool {
|
|
$token = HttpUtil::getBearerToken();
|
|
|
|
if (empty($token)) {
|
|
return [
|
|
'block' => true,
|
|
'response_code' => 401,
|
|
'message' => 'Token de autenticação não fornecido.',
|
|
];
|
|
}
|
|
|
|
try {
|
|
$payload = $this->jwtService->validateToken($token);
|
|
AuthContext::setUser($payload);
|
|
return true;
|
|
} catch (Throwable) {
|
|
return [
|
|
'block' => true,
|
|
'response_code' => 401,
|
|
'message' => 'Token inválido ou expirado.',
|
|
];
|
|
}
|
|
}
|
|
}
|