Files
breadcrumb-the-shire/pages/api/v1/users/avatar($id).php

69 lines
2.1 KiB
PHP

<?php
use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Access\AccessServicesFactory;
use MintyPHP\Service\Access\AuthorizationDecision;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\User\UserServicesFactory;
define('MINTY_ALLOW_OUTPUT', true);
ApiBootstrap::init();
ApiResponse::requireMethod('GET');
$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
http_response_code(404);
header('Content-Type: application/json');
echo json_encode(['error' => 'not_found']);
return;
}
$userServicesFactory = new UserServicesFactory();
$userAccountService = $userServicesFactory->createUserAccountService();
$userAvatarService = $userServicesFactory->createUserAvatarService();
$user = $userAccountService->findByUuid($uuid);
$userId = (int) ($user['id'] ?? 0);
$authorizationService = (new AccessServicesFactory())->createAuthorizationService();
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET, [
'actor_user_id' => ApiAuth::userId(),
'target_user_id' => $userId,
'scoped_tenant_id' => ApiAuth::scopedTenantId(),
]);
if (!$decision->isAllowed()) {
$status = $decision->status() ?: 403;
http_response_code($status);
header('Content-Type: application/json');
echo json_encode(['error' => $decision->error() ?: 'forbidden']);
return;
}
if (!$user) {
http_response_code(404);
header('Content-Type: application/json');
echo json_encode(['error' => 'not_found']);
return;
}
$size = isset($_GET['size']) ? (int) $_GET['size'] : null;
$path = $userAvatarService->findAvatarPath($uuid, $size);
if (!$path || !is_file($path)) {
http_response_code(404);
header('Content-Type: application/json');
echo json_encode(['error' => 'not_found']);
return;
}
$mime = $userAvatarService->detectMime($path);
header('Content-Type: ' . $mime);
header('X-Content-Type-Options: nosniff');
header('Content-Security-Policy: sandbox');
header('Cache-Control: private, max-age=300');
header('Content-Length: ' . filesize($path));
readfile($path);