api certificate

This commit is contained in:
2026-08-22 07:57:06 +02:00
parent 10cb0a890c
commit f7a8d24f26
3 changed files with 282 additions and 0 deletions
@@ -0,0 +1,91 @@
<?php
/**
* api_medical_certificates_delete.php
* --------------------------------------------------------------------------
* Elimina un certificato medico dell'utente autenticato (con ownership check).
*
* Posizione: public/api/api_medical_certificates_delete.php
* Metodo: POST
* Auth: Bearer token (Sanctum) via _bootstrap.php
*
* Body:
* - cert_id (int) id del certificato (idcertificateuserprofile)
* accettato sia via form-urlencoded sia via JSON.
*
* Tabella: certificateuserprofile
* --------------------------------------------------------------------------
*/
require_once __DIR__ . '/_bootstrap.php';
$userId = (int) $user->id;
$uploadDir = __DIR__ . '/../user/document/';
// ==========================================================================
// INPUT (JSON o form-urlencoded)
// ==========================================================================
$raw = file_get_contents('php://input');
$json = json_decode($raw, true);
if (is_array($json) && isset($json['cert_id'])) {
$certId = (int) $json['cert_id'];
} else {
$certId = (int) ($_POST['cert_id'] ?? 0);
}
if ($certId <= 0) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Parametro cert_id mancante.']);
exit;
}
// ==========================================================================
// 1) Recupera il certificato e verifica ownership
// ==========================================================================
$stmt = $db->prepare("
SELECT idcertificateuserprofile, filenamedocument
FROM certificateuserprofile
WHERE idcertificateuserprofile = :cid AND iduser = :uid
LIMIT 1
");
$stmt->execute([':cid' => $certId, ':uid' => $userId]);
$cert = $stmt->fetch();
if (!$cert) {
http_response_code(404);
echo json_encode(['success' => false, 'message' => 'Certificato non trovato.']);
exit;
}
// ==========================================================================
// 2) Elimina record + file
// ==========================================================================
try {
$del = $db->prepare("
DELETE FROM certificateuserprofile
WHERE idcertificateuserprofile = :cid AND iduser = :uid
LIMIT 1
");
$del->execute([':cid' => $certId, ':uid' => $userId]);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Errore durante la cancellazione.']);
exit;
}
// Rimuovi il file fisico (best effort)
$filename = (string) ($cert['filenamedocument'] ?? '');
if ($filename !== '') {
$path = $uploadDir . $filename;
if (is_file($path)) {
@unlink($path);
}
}
// ==========================================================================
// OUTPUT
// ==========================================================================
echo json_encode([
'success' => true,
'message' => 'Certificato eliminato.',
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+54
View File
@@ -0,0 +1,54 @@
<?php
/**
* api_medical_certificates_list.php
* --------------------------------------------------------------------------
* Restituisce i certificati medici dell'utente autenticato.
*
* Posizione: public/api/api_medical_certificates_list.php
* Metodo: GET
* Auth: Bearer token (Sanctum) via _bootstrap.php
*
* Tabella: certificateuserprofile
* idcertificateuserprofile, documentdescription, filenamedocument,
* iduser, expirydatedocument, uploaded_at
* --------------------------------------------------------------------------
*/
require_once __DIR__ . '/_bootstrap.php';
$userId = (int) $user->id;
$today = date('Y-m-d');
$stmt = $db->prepare("
SELECT idcertificateuserprofile, documentdescription, filenamedocument,
expirydatedocument, uploaded_at
FROM certificateuserprofile
WHERE iduser = :uid
ORDER BY uploaded_at DESC, idcertificateuserprofile DESC
");
$stmt->execute([':uid' => $userId]);
$rows = $stmt->fetchAll();
$certificates = [];
foreach ($rows as $r) {
$filename = (string) ($r['filenamedocument'] ?? '');
$expiry = $r['expirydatedocument'] ?? null;
$isExpired = ($expiry !== null && $expiry !== '' && $expiry < $today);
$certificates[] = [
'id' => (int) $r['idcertificateuserprofile'],
'document_name' => (string) ($r['documentdescription'] ?? ''),
'filename' => $filename,
'uploaded_at' => $r['uploaded_at'] ?? null,
'expiry_date' => $expiry,
'is_expired' => $isExpired,
// percorso file relativo (la webapp li serve da public/user/document/)
'file_url' => $filename !== '' ? '/user/document/' . $filename : null,
];
}
echo json_encode([
'success' => true,
'certificates' => $certificates,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+137
View File
@@ -0,0 +1,137 @@
<?php
/**
* api_medical_certificates_upload.php
* --------------------------------------------------------------------------
* Carica un certificato medico per l'utente autenticato.
*
* Posizione: public/api/api_medical_certificates_upload.php
* Metodo: POST (multipart/form-data)
* Auth: Bearer token (Sanctum) via _bootstrap.php
*
* Campi attesi (form-data):
* - certificate (file) campo file (PDF/JPG/PNG, max 16MB)
* - document_name (text) descrizione documento
* - expiry_date (text) YYYY-MM-DD
*
* Logica ricalcata da certificate.php (webapp).
* Tabella: certificateuserprofile
* --------------------------------------------------------------------------
*/
require_once __DIR__ . '/_bootstrap.php';
$userId = (int) $user->id;
// La cartella upload è public/user/document/. Questo file sta in public/api/,
// quindi saliamo di un livello.
$uploadDir = __DIR__ . '/../user/document/';
$allowedExt = ['pdf', 'jpg', 'jpeg', 'png'];
$allowedMime = ['application/pdf', 'image/jpeg', 'image/png'];
$maxBytes = 16 * 1024 * 1024; // 16 MB
// ==========================================================================
// INPUT
// ==========================================================================
$documentName = trim($_POST['document_name'] ?? '');
$expiryDate = trim($_POST['expiry_date'] ?? '');
if ($documentName === '') {
$documentName = 'Certificato Medico';
}
if ($expiryDate === '') {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Data di scadenza obbligatoria.']);
exit;
}
// Validazione formato data YYYY-MM-DD
$d = DateTime::createFromFormat('Y-m-d', $expiryDate);
if ($d === false || $d->format('Y-m-d') !== $expiryDate) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Formato data non valido (YYYY-MM-DD).']);
exit;
}
// File
if (!isset($_FILES['certificate']) || $_FILES['certificate']['error'] !== UPLOAD_ERR_OK) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Nessun file ricevuto o errore upload.']);
exit;
}
$file = $_FILES['certificate'];
if ($file['size'] > $maxBytes) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Il file supera i 16 MB.']);
exit;
}
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$finfo = new finfo(FILEINFO_MIME_TYPE);
$realMime = $finfo->file($file['tmp_name']);
if (!in_array($ext, $allowedExt, true) || !in_array($realMime, $allowedMime, true)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Formato non consentito. Usa PDF, JPG o PNG.']);
exit;
}
// ==========================================================================
// SALVATAGGIO FILE
// ==========================================================================
if (!is_dir($uploadDir)) {
@mkdir($uploadDir, 0755, true);
}
$safeName = bin2hex(random_bytes(16)) . '.' . $ext;
$destination = $uploadDir . $safeName;
if (!move_uploaded_file($file['tmp_name'], $destination)) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Salvataggio del file non riuscito.']);
exit;
}
// ==========================================================================
// INSERT DB
// ==========================================================================
try {
$sql = "INSERT INTO certificateuserprofile
(iduser, documentdescription, filenamedocument, expirydatedocument, uploaded_at)
VALUES (:iduser, :descr, :fname, :expiry, :uploaded)";
$stmt = $db->prepare($sql);
$stmt->execute([
':iduser' => $userId,
':descr' => $documentName,
':fname' => $safeName,
':expiry' => $expiryDate,
':uploaded' => date('Y-m-d'),
]);
$newId = (int) $db->lastInsertId();
} catch (Throwable $e) {
// rollback file se l'insert fallisce
@unlink($destination);
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Errore nel salvataggio del documento.']);
exit;
}
// ==========================================================================
// OUTPUT
// ==========================================================================
echo json_encode([
'success' => true,
'message' => 'Documento caricato correttamente.',
'certificate' => [
'id' => $newId,
'document_name' => $documentName,
'filename' => $safeName,
'uploaded_at' => date('Y-m-d'),
'expiry_date' => $expiryDate,
'is_expired' => false,
'file_url' => '/user/document/' . $safeName,
],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);