added laboratory creation with API secret and key

This commit is contained in:
Claudio 2024-10-17 17:25:43 +02:00
parent 4f0ad202c9
commit 837bfbaded
8 changed files with 641 additions and 25 deletions

View File

@ -0,0 +1,38 @@
<?php
include('../include/headscript.php');
include('../class/company.php');
$conn = new mysqli($servername, $username, $password, $database);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'];
$country = $_POST['country'];
// Generate unique reflab (1 letter followed by 5 digits)
do {
$reflab = chr(rand(65, 90)) . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
$check_query = $conn->prepare("SELECT idlab FROM laboratories WHERE reflab = ?");
$check_query->bind_param("s", $reflab);
$check_query->execute();
$check_query->store_result();
} while ($check_query->num_rows > 0);
$check_query->close();
// Generate API Key and Secret Key
$api_key = bin2hex(random_bytes(16));
$api_secret = bin2hex(random_bytes(16));
// Hash secret key before saving
$hashed_secret = password_hash($api_secret, PASSWORD_BCRYPT);
$stmt = $conn->prepare("INSERT INTO laboratories (name, reflab, country, api_key, api_secret) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $name, $reflab, $country, $api_key, $hashed_secret);
if ($stmt->execute()) {
// Show API Key, Secret Key, and Reflab to the user
echo json_encode(["status" => "success", "message" => "Laboratory added successfully.", "reflab" => $reflab, "api_key" => $api_key, "api_secret" => $api_secret]);
} else {
echo json_encode(["status" => "error", "message" => "Failed to add laboratory."]);
}
$stmt->close();
}
$conn->close();

View File

@ -1,56 +1,104 @@
<?php
// Connessione al database
// Database connection
include('../../Connections/repnew.php');
// Inizia la sessione per gestire le variabili di sessione
// Starts the session to handle session variables
$conn = new mysqli($servername, $username, $password, $database);
// Verifica la connessione
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Controlla se il JSON è stato ricevuto tramite POST
// Check if JSON was received via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Riceve il JSON dal laboratorio
// Receive JSON from the laboratory
$json_data = file_get_contents('php://input');
// Decodifica il JSON per la validazione (facoltativa)
// Decode JSON for optional validation
$decoded_data = json_decode($json_data, true);
// Se il JSON è valido
// If the JSON is valid
if (json_last_error() === JSON_ERROR_NONE) {
// Genera un UUID per identificare univocamente il record
$uuid = uniqid(); // Alternativamente puoi usare UUID() in MySQL
// Authenticate using key, secret_key, and reflab
if (!isset($decoded_data['key']) || !isset($decoded_data['secret_key']) || !isset($decoded_data['reflab'])) {
echo json_encode([
"status" => "error",
"message" => "Missing authentication fields (key, secret_key, reflab)."
]);
exit;
}
// ID del laboratorio dal quale proviene il JSON (puoi aggiungere autenticazione)
$lab_id = isset($_POST['lab_id']) ? $_POST['lab_id'] : 'Unknown Lab'; // Modifica a seconda della tua logica
$api_key = $decoded_data['key'];
$secret_key = $decoded_data['secret_key'];
$reflab = $decoded_data['reflab'];
// Estrai alcune informazioni dal JSON
$product_refnumber = $decoded_data['product']['products_refnumber']; // Numero prodotto
$report_number = $decoded_data['product']['reports'][0]['reportsNumberLab']; // Numero report
$rating = $decoded_data['product']['reports'][0]['reportsRating']; // Rating del report (es. Pass/Fail)
$saved_at = date("Y-m-d H:i:s"); // Data del salvataggio
// For testing purposes, use hardcoded credentials
$valid_api_key = 'api_key_123';
$valid_secret_key = 'api_secret_123';
$valid_reflab = 'REF001';
// Query per inserire i dati nella tabella temp_json_queue
if ($api_key !== $valid_api_key) {
echo json_encode([
"status" => "error",
"message" => "Invalid API key."
]);
exit;
}
if ($secret_key !== $valid_secret_key) {
echo json_encode([
"status" => "error",
"message" => "Invalid secret key."
]);
exit;
}
if ($reflab !== $valid_reflab) {
echo json_encode([
"status" => "error",
"message" => "Invalid reflab."
]);
exit;
}
// Generate a UUID to uniquely identify the record
$uuid = uniqid(); // Alternatively, use UUID() in MySQL
// Extract some information from JSON
if (!isset($decoded_data['product']['products_refnumber'])) {
echo json_encode([
"status" => "error",
"message" => "Missing product reference number."
]);
exit;
}
$product_refnumber = $decoded_data['product']['products_refnumber']; // Product number
$report_number = $decoded_data['product']['reports'][0]['reportsNumberLab'] ?? null; // Report number
$rating = $decoded_data['product']['reports'][0]['reportsRating'] ?? null; // Report rating (e.g., Pass/Fail)
$saved_at = date("Y-m-d H:i:s"); // Save date
// Query to insert data into the temp_json_queue table
$stmt = $conn->prepare("INSERT INTO temp_json_queue (uuid, lab_id, json_data) VALUES (?, ?, ?)");
$lab_id = 1; // Set lab_id to a fixed value for testing purposes
$stmt->bind_param("sss", $uuid, $lab_id, $json_data);
if ($stmt->execute()) {
// Imposta una variabile di sessione per notificare l'importazione del report
// Set a session variable to notify the report import
$_SESSION['new_report'] = [
'report_number' => $report_number,
'rating' => $rating,
'timestamp' => time() // Puoi usare un timestamp per gestire la scadenza della notifica
'timestamp' => time() // You can use a timestamp to manage the expiration of the notification
];
echo json_encode([
"status" => "success",
"message" => "Data successfully saved.",
"uuid" => $uuid,
"product_refnumber" => $product_refnumber, // Numero del prodotto
"report_number" => $report_number, // Numero del report
"rating" => $rating, // Rating del report
"saved_at" => $saved_at // Data del salvataggio
"product_refnumber" => $product_refnumber, // Product number
"report_number" => $report_number, // Report number
"rating" => $rating, // Report rating
"saved_at" => $saved_at // Save date
]);
} else {
echo json_encode([
@ -61,7 +109,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$stmt->close();
} else {
// Se il JSON è invalido
// If the JSON is invalid
echo json_encode([
"status" => "error",
"message" => "Invalid JSON format."
@ -74,5 +122,5 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
]);
}
// Chiude la connessione al database
// Close the database connection
$conn->close();

View File

@ -0,0 +1,19 @@
<?php
include('../include/headscript.php');
include('../class/company.php');
$conn = new mysqli($servername, $username, $password, $database);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$idlab = $_POST['idlab'];
$stmt = $conn->prepare("DELETE FROM laboratories WHERE idlab = ?");
$stmt->bind_param("i", $idlab);
if ($stmt->execute()) {
echo json_encode(["status" => "success", "message" => "Laboratory deleted successfully."]);
} else {
echo json_encode(["status" => "error", "message" => "Failed to delete laboratory."]);
}
$stmt->close();
}
$conn->close();

View File

@ -0,0 +1,27 @@
<?php
include('../include/headscript.php');
include('../class/company.php');
$conn = new mysqli($servername, $username, $password, $database);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$idlab = $_POST['idlab'];
$stmt = $conn->prepare("SELECT * FROM laboratories WHERE idlab = ?");
$stmt->bind_param("i", $idlab);
$stmt->execute();
$result = $stmt->get_result();
$lab = $result->fetch_assoc();
if ($lab) {
echo json_encode([
"status" => "success",
"name" => $lab['name'],
"country" => $lab['country'],
"status" => $lab['status']
]);
} else {
echo json_encode(["status" => "error", "message" => "Laboratory not found"]);
}
$stmt->close();
}
$conn->close();

View File

@ -0,0 +1,391 @@
<?php include('../include/headscript.php'); ?>
<?php
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php include("../class/company.php"); ?>
<?php include('../include/navigationbar.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<?php include('../include/seo.php'); ?>
<link rel="shortcut icon" href="../assets/images/favicon.ico">
<link href="../assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../assets/css/icons.css" rel="stylesheet" type="text/css">
<link href="../assets/css/style.css" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">
<script src="../assets/js/jquery.min.js"></script>
<link rel="stylesheet" href="../assets/plugins/select2/select2.min.css">
<script src="../assets/plugins/select2/select2.min.js"></script>
</head>
<style>
/* Assicura che gli input e il select abbiano margini e padding corretti */
.swal2-input,
.swal2-select {
width: 100% !important;
margin-bottom: 15px;
/* Aggiungi uno spazio tra gli elementi */
padding: 10px;
box-sizing: border-box;
/* Assicura che padding e bordi siano inclusi nella larghezza */
}
/* Corregge la visualizzazione del select all'interno di SweetAlert */
.swal2-select select {
display: block;
width: 100%;
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
font-size: 1rem;
}
</style>
<body class="fixed-left">
<!-- Loader -->
<!-- Begin page -->
<div id="wrapper">
<!-- Start right Content here -->
<div class="content-page">
<!-- Start content -->
<div class="content">
<?php include('../include/topbar.php'); ?>
<div class="page-content-wrapper ">
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div class="page-title-box">
<div class="btn-group float-right">
<ol class="breadcrumb hide-phone p-0 m-0">
<li class="breadcrumb-item"><a href="#">Reportify</a></li>
<li class="breadcrumb-item active">Laboratories</li>
</ol>
</div>
<h4 class="page-title">Laboratories Management</h4>
</div>
</div>
</div>
<!-- end page title end breadcrumb -->
<div class="row">
<div class="col-xl-12">
<div class="card">
<div class="card-body">
<h5 class="header-title pb-3 mt-0">Laboratories List</h5>
<div class="table-responsive">
<table class="table table-striped table-custom">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Reflab</th>
<th>Country</th>
<th>Status</th>
<th>API Key</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM laboratories";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['idlab'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['reflab'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . substr($row['api_key'], 0, 5) . "*****" . "</td>";
echo "<td>
<button class='btn btn-primary btn-sm' onclick='editLab(" . $row['idlab'] . ")'>Edit</button>
<button class='btn btn-danger btn-sm' onclick='deleteLab(" . $row['idlab'] . ")'>Delete</button>
<button class='btn btn-warning btn-sm' onclick='regenerateKeys(" . $row['idlab'] . ")'>Regenerate Keys</button>
</td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='7'>No laboratories found</td></tr>";
}
?>
</tbody>
</table>
</div><!-- end table-responsive -->
<button class="btn btn-success mt-3" onclick="addLab()">Add New Laboratory</button>
</div>
</div>
</div>
</div>
<!-- end row -->
</div><!-- container -->
</div> <!-- Page content Wrapper -->
</div> <!-- content -->
<?php include('../include/footer.php'); ?>
</div>
<!-- End Right content here -->
</div>
<!-- END wrapper -->
<!-- plugin JS -->
<script src="../assets/js/popper.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/modernizr.min.js"></script>
<script src="../assets/js/detect.js"></script>
<script src="../assets/js/fastclick.js"></script>
<script src="../assets/js/jquery.slimscroll.js"></script>
<script src="../assets/js/jquery.blockUI.js"></script>
<script src="../assets/js/waves.js"></script>
<script src="../assets/js/jquery.nicescroll.js"></script>
<script src="../assets/js/jquery.scrollTo.min.js"></script>
<script src="../assets/js/common_helper.js"></script>
<script src="../assets/plugins/chart.js/chart.min.js"></script>
<script src="../assets/pages/dashboard.js"></script>
<!-- App js -->
<script src="../assets/js/app.js"></script>
<script src="../assets/plugins/alertify/js/alertify.js"></script>
<script>
function addLab() {
Swal.fire({
title: 'Add New Laboratory',
html: `
<input id="lab_name" class="swal2-input" placeholder="Lab Name">
<input id="country" class="swal2-input" placeholder="Country">
`,
focusConfirm: false,
preConfirm: () => {
const name = document.getElementById('lab_name').value;
const country = document.getElementById('country').value;
if (!name || !country) {
Swal.showValidationMessage('Please enter all fields');
} else {
$.ajax({
url: 'add_lab.php',
method: 'POST',
data: {
name: name,
country: country
},
success: function(response) {
response = JSON.parse(response);
if (response.status === 'success') {
Swal.fire({
title: 'Laboratory Added',
html: `<p>Reflab: ${response.reflab}</p>
<p>API Key: <strong>${response.api_key}</strong></p>
<p>Secret Key: <strong>${response.api_secret}</strong></p>
<p>Please copy these keys securely. This is your only chance to view the secret key.</p>`,
icon: 'success',
showCancelButton: true,
cancelButtonText: 'Close'
}).then(() => {
// Aggiorna la tabella dinamicamente senza ricaricare l'intera pagina
loadLaboratories();
});
} else {
alertify.error('Failed to add laboratory');
}
},
error: function() {
alertify.error('Failed to add laboratory');
}
});
}
}
});
}
function loadLaboratories() {
$.ajax({
url: 'load_laboratories.php', // Questo file restituisce il codice HTML della tabella
method: 'GET',
success: function(data) {
$('tbody').html(data); // Aggiorna solo il contenuto della tabella
},
error: function() {
alertify.error('Failed to load laboratories');
}
});
}
function editLab(idlab) {
// Recupera i dati del laboratorio tramite AJAX
$.ajax({
url: 'get_lab.php',
method: 'POST',
data: {
idlab: idlab
},
success: function(response) {
response = JSON.parse(response);
if (response.name && response.country) {
// Mostra SweetAlert con i dati precompilati
Swal.fire({
title: 'Edit Laboratory',
html: `
<div style="margin-bottom: 10px;">
<input id="lab_name" class="swal2-input" placeholder="Lab Name" value="${response.name}">
</div>
<div style="margin-bottom: 10px;">
<input id="country" class="swal2-input" placeholder="Country" value="${response.country}">
</div>
<div style="margin-bottom: 10px;">
<select id="status" name="status" class="swal2-select">
<option value="active" ${response.status === 'active' ? 'selected' : ''}>Active</option>
<option value="inactive" ${response.status === 'inactive' ? 'selected' : ''}>Inactive</option>
<option value="suspended" ${response.status === 'suspended' ? 'selected' : ''}>Suspended</option>
</select>
</div>
`,
focusConfirm: false,
preConfirm: () => {
const name = document.getElementById('lab_name').value.trim();
const country = document.getElementById('country').value.trim();
const status = document.getElementById('status').value;
if (name === '' || country === '' || status === '') {
Swal.showValidationMessage('Please enter all fields');
return false;
} else {
// Esegui l'aggiornamento tramite AJAX
$.ajax({
url: 'update_lab.php',
method: 'POST',
data: {
idlab: idlab,
name: name,
country: country,
status: status // Assicurati che lo status venga inviato
},
success: function(response) {
console.log(response); // Debug per verificare cosa restituisce il server
response = JSON.parse(response);
if (response.status === 'success') {
Swal.fire('Updated!', response.message, 'success').then(() => {
loadLaboratories(); // Aggiorna la tabella dinamicamente
});
} else {
alertify.error('Failed to update laboratory');
}
},
error: function() {
alertify.error('Failed to update laboratory');
}
});
}
}
});
} else {
alertify.error('Failed to retrieve laboratory data');
}
},
error: function() {
alertify.error('Failed to retrieve laboratory data');
}
});
}
function deleteLab(idlab) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: 'delete_lab.php',
method: 'POST',
data: {
idlab: idlab
},
success: function(response) {
response = JSON.parse(response);
if (response.status === 'success') {
Swal.fire('Deleted!', response.message, 'success').then(() => {
// Aggiorna la tabella dinamicamente senza ricaricare l'intera pagina
loadLaboratories();
});
} else {
alertify.error('Failed to delete laboratory');
}
},
error: function() {
alertify.error('Failed to delete laboratory');
}
});
}
});
}
function regenerateKeys(idlab) {
Swal.fire({
title: 'Regenerate API Keys?',
text: "This will invalidate the current keys!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, regenerate!'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: 'regenerate_keys.php',
method: 'POST',
data: {
idlab: idlab
},
success: function(response) {
response = JSON.parse(response);
if (response.status === 'success') {
// Mostra le nuove chiavi rigenerate in un SweetAlert
Swal.fire({
title: 'Keys Regenerated',
html: `<p>API Key: <strong>${response.api_key}</strong></p>
<p>Secret Key: <strong>${response.api_secret}</strong></p>
<p>Please copy these keys securely. This is your only chance to view the secret key.</p>`,
icon: 'success',
showCancelButton: true,
cancelButtonText: 'Close'
});
} else {
alertify.error('Failed to regenerate keys');
}
},
error: function() {
alertify.error('Failed to regenerate keys');
}
});
}
});
}
</script>
</body>
</html>

View File

@ -0,0 +1,29 @@
<?php
include('../include/headscript.php');
include('../class/company.php');
$conn = new mysqli($servername, $username, $password, $database);
$query = "SELECT * FROM laboratories";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['idlab'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['reflab'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . substr($row['api_key'], 0, 5) . "*****" . "</td>";
echo "<td>
<button class='btn btn-primary btn-sm' onclick='editLab(" . $row['idlab'] . ")'>Edit</button>
<button class='btn btn-danger btn-sm' onclick='deleteLab(" . $row['idlab'] . ")'>Delete</button>
<button class='btn btn-warning btn-sm' onclick='regenerateKeys(" . $row['idlab'] . ")'>Regenerate Keys</button>
</td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='7'>No laboratories found</td></tr>";
}
$conn->close();

View File

@ -0,0 +1,27 @@
<?php
include('../include/headscript.php');
include('../class/company.php');
$conn = new mysqli($servername, $username, $password, $database);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$idlab = $_POST['idlab'];
// Generate new API Key and Secret Key
$new_api_key = bin2hex(random_bytes(16));
$new_api_secret = bin2hex(random_bytes(16));
// Hash secret key before saving
$hashed_secret = password_hash($new_api_secret, PASSWORD_BCRYPT);
$stmt = $conn->prepare("UPDATE laboratories SET api_key = ?, api_secret = ? WHERE idlab = ?");
$stmt->bind_param("ssi", $new_api_key, $hashed_secret, $idlab);
if ($stmt->execute()) {
// Show success message and display the new keys
echo json_encode(["status" => "success", "message" => "Keys regenerated successfully.", "api_key" => $new_api_key, "api_secret" => $new_api_secret]);
} else {
echo json_encode(["status" => "error", "message" => "Failed to regenerate keys."]);
}
$stmt->close();
}
$conn->close();

View File

@ -0,0 +1,37 @@
<?php
include('../include/headscript.php');
include('../class/company.php');
$conn = new mysqli($servername, $username, $password, $database);
// Debug per visualizzare i dati inviati
// Per vedere cosa viene inviato
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$idlab = $_POST['idlab'];
$name = $_POST['name'];
$country = $_POST['country'];
$status = $_POST['status'];
// Prepara la query di aggiornamento
$stmt = $conn->prepare("UPDATE laboratories SET name = ?, country = ?, status = ? WHERE idlab = ?");
$stmt->bind_param("sssi", $name, $country, $status, $idlab);
// Esegui la query e verifica il risultato
if ($stmt->execute()) {
echo json_encode(["status" => "success", "message" => "Laboratory updated successfully."]);
} else {
// Mostra l'errore se la query fallisce
echo json_encode([
"status" => "error",
"message" => "Failed to update laboratory.",
"error" => $stmt->error, // Mostra il messaggio di errore
"errno" => $stmt->errno // Mostra il codice di errore
]);
}
$stmt->close();
} else {
echo json_encode(["status" => "error", "message" => "Invalid request method"]);
exit;
}
$conn->close();