Update: 2026-05-04 02:53:16
This commit is contained in:
@@ -6,6 +6,19 @@
|
||||
use App\Core\Database;
|
||||
use App\Middleware\AuthMiddleware;
|
||||
|
||||
// Helper to output error as an image for debugging
|
||||
function outputErrorImage($message) {
|
||||
header('Content-Type: image/png');
|
||||
$im = imagecreatetruecolor(400, 100);
|
||||
$bg = imagecolorallocate($im, 20, 20, 20);
|
||||
$tc = imagecolorallocate($im, 255, 50, 50);
|
||||
imagefilledrectangle($im, 0, 0, 400, 100, $bg);
|
||||
imagestring($im, 5, 10, 40, $message, $tc);
|
||||
imagepng($im);
|
||||
imagedestroy($im);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Extract token from header OR query string
|
||||
$headers = getallheaders();
|
||||
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
|
||||
@@ -17,44 +30,41 @@ if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
|
||||
$token = $_GET['token'];
|
||||
}
|
||||
|
||||
if (!$token) die('Forbidden: No token provided');
|
||||
if (!$token) outputErrorImage('Forbidden: No token');
|
||||
|
||||
$decoded = \App\Core\JWT::decode($token);
|
||||
if (!$decoded) die('Forbidden: Invalid token');
|
||||
if (!$decoded) outputErrorImage('Forbidden: Invalid token');
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
$id = input('id');
|
||||
if (!$id) die('Forbidden');
|
||||
if (!$id) outputErrorImage('Forbidden: No ID');
|
||||
|
||||
$stmt = $db->prepare("SELECT tenant_id, original_file_path FROM invoices WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
$invoice = $stmt->fetch();
|
||||
|
||||
if (!$invoice) die('Not found');
|
||||
if (!$invoice) outputErrorImage('Error: Invoice not found');
|
||||
|
||||
// Authorization
|
||||
if ($decoded['role'] !== 'super_admin' && $invoice['tenant_id'] !== $decoded['tenant_id']) {
|
||||
die('Unauthorized');
|
||||
outputErrorImage('Error: Unauthorized');
|
||||
}
|
||||
|
||||
$filePath = $invoice['original_file_path'];
|
||||
|
||||
if (!file_exists($filePath)) {
|
||||
error_log("FILE PROXY ERROR: File not found at " . $filePath);
|
||||
header("HTTP/1.0 404 Not Found");
|
||||
exit('File missing');
|
||||
outputErrorImage('Error: File missing on disk');
|
||||
}
|
||||
|
||||
if (!is_readable($filePath)) {
|
||||
error_log("FILE PROXY ERROR: File not readable at " . $filePath);
|
||||
header("HTTP/1.0 403 Forbidden");
|
||||
exit('Permission denied');
|
||||
outputErrorImage('Error: Permission denied');
|
||||
}
|
||||
|
||||
$mime = mime_content_type($filePath);
|
||||
if (!$mime) $mime = 'application/octet-stream';
|
||||
|
||||
header("Content-Type: $mime");
|
||||
header("Content-Length: " . filesize($filePath));
|
||||
header("Cache-Control: public, max-age=3600"); // Add caching for speed
|
||||
header("Cache-Control: public, max-age=3600");
|
||||
readfile($filePath);
|
||||
exit;
|
||||
|
||||
Reference in New Issue
Block a user