57 lines
2.0 KiB
PHP
57 lines
2.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace BattleForge\Http\Handlers;
|
|
|
|
use BattleForge\Application\ImageUploadService;
|
|
use BattleForge\Application\InvalidImageException;
|
|
use BattleForge\Http\CsrfToken;
|
|
use BattleForge\Http\Request;
|
|
use BattleForge\Http\Response;
|
|
|
|
final class PostImageUpload
|
|
{
|
|
public function __construct(private readonly string $uploadsRoot)
|
|
{
|
|
}
|
|
|
|
/** @param array<string, string> $params */
|
|
public function handle(Request $request, array $params): Response
|
|
{
|
|
$submitted = (string) ($request->post['_csrf'] ?? '');
|
|
$expected = (string) ($request->cookies['__csrf'] ?? '');
|
|
$secret = (string) ($request->server['__csrf_secret'] ?? '');
|
|
|
|
if ($secret === '' || $expected === '' || !CsrfToken::verify($submitted, $secret, $expected)) {
|
|
return Response::json(403, ['error' => 'csrf']);
|
|
}
|
|
|
|
$file = $request->files['image'] ?? null;
|
|
if ($file === null) {
|
|
return Response::json(400, ['error' => 'No image uploaded.']);
|
|
}
|
|
|
|
$tempPath = (string) ($file['tmp_name'] ?? '');
|
|
$declaredMime = (string) ($file['type'] ?? '');
|
|
|
|
if ($tempPath === '' || !is_file($tempPath)) {
|
|
// Production: $request->files['image']['tmp_name'] is PHP-set from the multipart body,
|
|
// so is_file() confirms the temp file exists. is_uploaded_file() is stricter but
|
|
// unsuitable for unit tests that synthesize tmp files via tempnam().
|
|
return Response::json(400, ['error' => 'Upload is not a file.']);
|
|
}
|
|
|
|
$userToken = hash_hmac('sha256', $secret, 'bf-uploads');
|
|
|
|
try {
|
|
$service = new ImageUploadService($userToken, $this->uploadsRoot);
|
|
$url = $service->store($tempPath, $declaredMime);
|
|
} catch (InvalidImageException $exception) {
|
|
return Response::json(400, ['error' => $exception->getMessage()]);
|
|
}
|
|
|
|
return Response::json(200, ['url' => $url]);
|
|
}
|
|
}
|