|
|
|
<?php
|
|
|
|
|
|
|
|
namespace app\middleware;
|
|
|
|
|
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request;
|
|
|
|
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
|
|
|
|
use Psr\Http\Message\ResponseInterface;
|
|
|
|
use Tuupola\Http\Factory\ResponseFactory;
|
|
|
|
use Exception;
|
|
|
|
|
|
|
|
use app\traits\AuthToken;
|
|
|
|
use app\shared\Logger;
|
|
|
|
|
|
|
|
class AuthMiddleware
|
|
|
|
{
|
|
|
|
use AuthToken;
|
|
|
|
|
|
|
|
// does constructor works here?
|
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
self::$logger = new Logger('api' . date('Ymd'), self::LOG_ACTIVE);
|
|
|
|
self::$logger->debug('AuthMiddleware instantiated', true);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function __invoke(Request $request, RequestHandler $handler): ResponseInterface
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
self::$logger->debug('Will try to find token', true);
|
|
|
|
|
|
|
|
//returns [user_id, token_id, id_organizacao, token, expired_at] if not found --> throws exception
|
|
|
|
$orgToken = $this->findToken($request);
|
|
|
|
|
|
|
|
/* // creating array of orgs
|
|
|
|
$orgs = [];
|
|
|
|
foreach ($orgToken as $value) {
|
|
|
|
$orgs[] = $value['id_organizacao'];
|
|
|
|
} */
|
|
|
|
|
|
|
|
//$request = $request->withAttribute('orgs', $orgToken['id_organizacao']);
|
|
|
|
$response = $handler->handle($request);
|
|
|
|
} catch (Exception $e) {
|
|
|
|
self::$logger->error('Exception in AuthMiddleware: ' . $e->getMessage(), true);
|
|
|
|
$fac = new ResponseFactory;
|
|
|
|
$response = $fac->createResponse(403);
|
|
|
|
$message = mb_convert_encoding($e->getMessage(), 'ISO8859-1');
|
|
|
|
$response->withStatus(403)->withHeader('Content-Type', 'application/json')->getBody()->write(
|
|
|
|
json_encode(['status' => false, 'data' => ['message' => $message]])
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return $response;
|
|
|
|
}
|
|
|
|
}
|