Einstellungen von Header nach Einstellungsseite ausgelagert

This commit is contained in:
ISA
2025-03-14 11:41:31 +01:00
parent 8c638acfc7
commit 0139ef656b
11 changed files with 541 additions and 91 deletions

View File

@@ -88,13 +88,17 @@ function Header() {
<div className="p-4 w-full lg:w-full flex flex-row gap-4 justify-between">
<div className="flex items-center justify-end w-full">
{/* Admin-Login */}
{/*
<button
onClick={handleSettingsClick}
className="text-3xl text-black mr-0"
>
<i className="bi bi-gear"></i>
</button>
*/}
</div>
<div className="flex items-center justify-end w-1/4 space-x-1">
<button
onClick={handleLogout}

View File

@@ -1,18 +1,28 @@
"use client";
"use client"; // /components/main/settingsPageComponents/GeneralSettings.tsx
import React, { useState } from "react";
import { RootState } from "../../../redux/store";
import { useSelector } from "react-redux";
import handleClearDatabase from "../../header/settingsModal/handlers/handleClearDatabase";
import handleReboot from "../../header/settingsModal/handlers/handleReboot";
import handleSetDateTime from "../../header/settingsModal/handlers/handleSetDateTime";
import handleSubmit from "../../header/settingsModal/handlers/handleSubmit";
import handleClearDatabase from "./handlers/handleClearDatabase";
import handleReboot from "./handlers/handleReboot";
import handleSetDateTime from "./handlers/handleSetDateTime";
import handleSubmit from "./handlers/handleSubmit";
import { useAdminAuth } from "./hooks/useAdminAuth";
import handleAdminLogin from "./handlers/handleAdminLogin";
const GeneralSettings = () => {
const systemSettings = useSelector(
(state: RootState) => state.systemSettings
);
const { isAdminLoggedIn, logoutAdmin } = useAdminAuth(true);
const [loginSuccess, setLoginSuccess] = useState(false);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [name, setName] = useState(systemSettings.deviceName || "");
const [mac1] = useState(systemSettings.mac1 || "");
const [ip, setIp] = useState(systemSettings.ip || "");
const [subnet, setSubnet] = useState(systemSettings.subnet || "");
const [gateway, setGateway] = useState(systemSettings.gateway || "");
@@ -26,145 +36,167 @@ const GeneralSettings = () => {
systemSettings.ntpTimezone || ""
);
const [active, setActive] = useState(systemSettings.ntpActive || false);
const handleLogin = async () => {
handleAdminLogin(
username,
password,
() => {
setLoginSuccess(true);
setError("");
},
(errorMsg) => {
setLoginSuccess(false);
setError(errorMsg);
}
);
};
return (
<div className="p-2 bg-gray-100">
<h2 className="text-md font-bold mb-2">General Settings</h2>
<form className="grid grid-cols-2 gap-2">
<div className="p-2 md:p-3 bg-gray-100 max-w-2xl mx-auto">
<h2 className="text-sm md:text-md font-bold mb-2">
Allgemeine Einstellungen
</h2>
<form className="grid grid-cols-1 md:grid-cols-2 gap-2">
{/* ✅ Geräte-Name */}
<div className="col-span-2">
<label className="block text-xs font-medium">Name:</label>
<label className="block text-xs md:text-sm font-medium">Name:</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
{/* ✅ Netzwerk-Einstellungen */}
{/* ✅ MAC Adresse (nur Anzeige) */}
<div>
<label className="block text-xs font-medium">IP:</label>
<label className="block text-xs md:text-sm font-medium">
MAC Adresse 1:
</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
value={ip}
onChange={(e) => setIp(e.target.value)}
/>
</div>
<div>
<label className="block text-xs font-medium">Subnet:</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
value={subnet}
onChange={(e) => setSubnet(e.target.value)}
/>
</div>
<div>
<label className="block text-xs font-medium">Gateway:</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
value={gateway}
onChange={(e) => setGateway(e.target.value)}
className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
value={mac1}
disabled
/>
</div>
{/* ✅ System-Zeit */}
<div className="col-span-2 flex items-center gap-2">
{/* ✅ Systemzeit & Setzen */}
<div className="flex flex-col md:flex-row md:items-center gap-1 col-span-2">
<div className="flex-1">
<label className="block text-xs font-medium">Systemzeit:</label>
<label className="block text-xs md:text-sm font-medium">
Systemzeit:
</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
value={systemUhr}
disabled
/>
</div>
<button
type="button"
className="bg-littwin-blue text-white px-3 py-1 rounded text-xs"
className="bg-littwin-blue text-white px-2 py-1 rounded w-full md:w-auto text-xs"
onClick={() => handleSetDateTime()}
>
Setzen
Systemzeit übernehmen
</button>
</div>
{/* ✅ NTP-Server */}
{/* ✅ Netzwerk-Einstellungen */}
<div>
<label className="block text-xs font-medium">NTP Server 1:</label>
<label className="block text-xs md:text-sm font-medium">IP:</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
value={ntp1}
onChange={(e) => setNtp1(e.target.value)}
className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
value={ip}
onChange={(e) => setIp(e.target.value)}
/>
</div>
<div>
<label className="block text-xs font-medium">NTP Server 2:</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
value={ntp2}
onChange={(e) => setNtp2(e.target.value)}
/>
</div>
<div>
<label className="block text-xs font-medium">NTP Server 3:</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
value={ntp3}
onChange={(e) => setNtp3(e.target.value)}
/>
</div>
<div>
<label className="block text-xs font-medium">Zeitzone:</label>
<input
type="text"
className="border border-gray-300 rounded p-1 w-full text-sm"
value={ntpTimezone}
onChange={(e) => setNtpTimezone(e.target.value)}
/>
</div>
<div className="col-span-2 flex items-center gap-2">
<input
id="ntpActive"
type="checkbox"
className="peer hidden"
checked={active}
onChange={(e) => setActive(e.target.checked)}
/>
<label
htmlFor="ntpActive"
className="w-5 h-5 border-2 border-gray-300 rounded cursor-pointer flex items-center justify-center
peer-checked:bg-littwin-blue peer-checked:border-littwin-blue peer-checked:text-white"
>
<label className="block text-xs md:text-sm font-medium">
Subnet:
</label>
<span className="text-xs font-medium">NTP Aktiv</span>
<input
type="text"
className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
value={subnet}
onChange={(e) => setSubnet(e.target.value)}
/>
</div>
<div>
<label className="block text-xs md:text-sm font-medium">
Gateway:
</label>
<input
type="text"
className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
value={gateway}
onChange={(e) => setGateway(e.target.value)}
/>
</div>
{/* ✅ Admin-Login/Logout */}
<div className="col-span-2 flex flex-col gap-1">
{isAdminLoggedIn ? (
<button
type="button"
className="bg-red-500 text-white px-2 py-1 rounded text-xs"
onClick={logoutAdmin}
>
Admin abmelden
</button>
) : (
<>
<input
type="text"
placeholder="Benutzername"
className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Passwort"
className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button
type="button"
className="bg-littwin-blue text-white px-2 py-1 rounded text-xs"
onClick={handleLogin}
>
Admin anmelden
</button>
</>
)}
</div>
{/* ✅ Feedback für den Benutzer */}
{loginSuccess && (
<p className="text-green-600 text-xs">Login erfolgreich!</p>
)}
{error && <p className="text-red-500 text-xs">{error}</p>}
{/* ✅ Buttons */}
<div className="col-span-2 flex justify-between mt-2">
<div className="col-span-2 flex flex-wrap md:justify-between gap-1 mt-2">
<button
type="button"
className="bg-littwin-blue text-white px-3 py-1 rounded text-xs"
className="bg-littwin-blue text-white px-2 py-1 rounded text-xs w-full md:w-auto"
onClick={() => handleReboot()}
>
Neustart
Neustart CPL
</button>
<button
type="button"
className="bg-littwin-blue text-white px-3 py-1 rounded text-xs"
className="bg-littwin-blue text-white px-2 py-1 rounded text-xs w-full md:w-auto"
onClick={() => handleClearDatabase()}
>
Datenbank leeren
</button>
<button
type="button"
className="bg-littwin-blue text-white px-3 py-1 rounded text-xs"
className="bg-littwin-blue text-white px-2 py-1 rounded text-xs w-full md:w-auto"
onClick={() =>
handleSubmit(
{

View File

@@ -0,0 +1,10 @@
// components/main/settingsPageComponents/config/users.ts
const USERS = {
Admin: {
username: "admin",
password: "$2a$10$xpq/.tcOJN/LXfzdCcCVrenlBh2nRlM1R1ISY7dd1q2qGWC9Fyd2G", // Gehashte Version von "admin"
role: "Admin",
},
};
export default USERS;

View File

@@ -0,0 +1,27 @@
// components/main/settingsPageComponents/GeneralSettings.tsx
import bcrypt from "bcryptjs";
import { generateToken } from "../utils/cryptoUtils";
import USERS from "../config/users";
const handleAdminLogin = (
username: string,
password: string,
onSuccess: () => void,
onError: (errorMsg: string) => void
) => {
const user = USERS.Admin;
bcrypt.compare(password, user.password, (err, isMatch) => {
if (isMatch) {
const token = generateToken(user);
sessionStorage.setItem("token", token);
localStorage.setItem("isAdminLoggedIn", "true");
onSuccess();
} else {
onError(
"Login fehlgeschlagen. Bitte überprüfen Sie Benutzername und Passwort."
);
}
});
};
export default handleAdminLogin;

View File

@@ -0,0 +1,34 @@
// components/main/settingsPageComponents/handlers/handleClearDatabase.ts
const handleClearDatabase = async () => {
const confirmClear = window.confirm(
"Sind Sie sicher, dass Sie die Datenbank leeren möchten?"
);
if (!confirmClear) return;
// Get the current path and ensure it ends with ".html"
let currentPath = window.location.pathname;
if (!currentPath.endsWith(".html")) {
currentPath += ".html";
}
// Full URL with host, current path, and clear database command
const url = `${window.location.origin}/CPL?${currentPath}&DEDB=1`;
// Log the full URL to the console for debugging
console.log(url);
// Send the clear database command to the server using fetch and GET method
try {
const response = await fetch(url, { method: "GET" });
if (response.ok) {
alert("Datenbank erfolgreich geleert!");
} else {
alert("Fehler beim Leeren der Datenbank!");
}
} catch (error) {
console.error("Fehler:", error);
alert("Fehler beim Leeren der Datenbank!");
}
};
export default handleClearDatabase;

View File

@@ -0,0 +1,93 @@
// components/main/settingsPageComponents/handlers/handleReboot.ts
const handleReboot = async (newIp: string | null = null): Promise<void> => {
const showWaitPage = () => {
const waitHTML = `
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bitte warten...</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
color: #333;
}
.message {
text-align: center;
}
.progress-container {
width: 100%;
background-color: #ddd;
border-radius: 10px;
overflow: hidden;
margin-top: 20px;
}
.progress-bar {
height: 20px;
width: 0;
background-color: #3498db;
transition: width 0.3s;
}
</style>
</head>
<body>
<div class="message">
<p>Bitte warten, CPL wird neu gestartet...</p>
<div class="progress-container">
<div class="progress-bar" id="progress-bar"></div>
</div>
</div>
</body>
</html>
`;
document.documentElement.innerHTML = waitHTML;
let progress = 0;
const progressBar = document.getElementById("progress-bar");
if (progressBar) {
const interval = setInterval(() => {
progress += 1;
progressBar.style.width = progress + "%";
if (progress >= 100) {
clearInterval(interval);
}
}, 300);
} else {
console.error("Progress-Bar-Element nicht gefunden.");
}
};
if (
window.confirm("Sind Sie sicher, dass Sie den CPL neu starten möchten?")
) {
showWaitPage();
const baseRedirectURL = newIp ? `https://${newIp}` : window.location.origin;
const redirectPath =
process.env.NODE_ENV === "production" ? "/dashboard.html" : "/dashboard";
setTimeout(() => {
window.location.href = `${baseRedirectURL}${redirectPath}`;
}, 33000);
const url = `${window.location.origin}/CPL?wait2reboot.html&BOOT=1`;
console.log(url);
fetch(url, { method: "GET" })
.then(() => {
console.log("Neustart-Anfrage erfolgreich gesendet.");
})
.catch((error) => {
console.error("Fehler beim Senden der Neustartanfrage:", error);
});
}
};
export default handleReboot;

View File

@@ -0,0 +1,45 @@
//components/main/settingsPageComponents/handlers/handleSetDateTime.ts
const handleSetDateTime = () => {
const currentDate = new Date();
// Format date and time as required by the system without leading zeros:
const year = currentDate.getFullYear().toString().slice(-2); // Last two digits of the year
const month = Number(currentDate.getMonth() + 1); // Convert to Number to remove leading zero
const day = Number(currentDate.getDate()); // Convert to Number to remove leading zero
const hours = Number(currentDate.getHours()); // Convert to Number to remove leading zero
const minutes = Number(currentDate.getMinutes()); // Convert to Number to remove leading zero
const seconds = Number(currentDate.getSeconds()); // Convert to Number to remove leading zero
// Date and Time commands
const dateCommand = `CLK00=${year}-${month}-${day}`;
const timeCommand = `CLK01=${hours}-${minutes}-${seconds}`;
// Get the current path and ensure it ends with ".html"
let currentPath = window.location.pathname;
if (!currentPath.endsWith(".html")) {
currentPath += ".html";
}
// Full URL with host, current path, date, and time commands
const url = `${window.location.origin}/CPL?${currentPath}&${dateCommand}&${timeCommand}`;
// Log the full URL to the console
console.log(url);
// Send the commands to the server using fetch and GET method
fetch(url, { method: "GET" })
.then((response) => {
if (response.ok) {
alert("Datum und Uhrzeit erfolgreich gesetzt!");
} else {
alert("Fehler beim Setzen von Datum und Uhrzeit!");
}
})
.catch((error) => {
console.error("Fehler:", error);
alert("Fehler beim Setzen von Datum und Uhrzeit!");
});
};
export default handleSetDateTime;

View File

@@ -0,0 +1,98 @@
// components/main/settingsPageComponents/handlers/handleSubmit.ts
import handleReboot from "./handleReboot";
interface OriginalValues {
name: string;
ip: string;
subnet: string;
gateway: string;
ntp1: string;
ntp2: string;
ntp3: string;
ntpTimezone: string;
active: boolean;
}
interface CurrentValues {
name: string;
ip: string;
subnet: string;
gateway: string;
ntp1: string;
ntp2: string;
ntp3: string;
ntpTimezone: string;
active: boolean;
}
const handleSubmit = (
originalValues: OriginalValues,
currentValues: CurrentValues
): void => {
const changes: { [key: string]: string | boolean } = {};
let networkChanges = false;
let newIp: string | null = null;
// Überprüfe, welche Werte sich geändert haben
if (currentValues.name !== originalValues.name) {
changes.SNNA = currentValues.name;
networkChanges = true;
}
if (currentValues.ip !== originalValues.ip) {
changes.SEI01 = currentValues.ip;
newIp = currentValues.ip; // Neue IP speichern
networkChanges = true;
}
if (currentValues.subnet !== originalValues.subnet) {
changes.SEI02 = currentValues.subnet;
networkChanges = true;
}
if (currentValues.gateway !== originalValues.gateway) {
changes.SEI03 = currentValues.gateway;
networkChanges = true;
}
if (currentValues.ntp1 !== originalValues.ntp1) {
changes.SNIP1 = currentValues.ntp1;
}
if (currentValues.ntp2 !== originalValues.ntp2) {
changes.SNIP2 = currentValues.ntp2;
}
if (currentValues.ntp3 !== originalValues.ntp3) {
changes.SNIP3 = currentValues.ntp3;
}
if (currentValues.ntpTimezone !== originalValues.ntpTimezone) {
changes.SNTZ = currentValues.ntpTimezone;
}
if (currentValues.active !== originalValues.active) {
changes.SNAC = currentValues.active;
}
if (Object.keys(changes).length > 0) {
// URL für die Änderungen erstellen
let url = `${window.location.origin}/CPL?${window.location.pathname}`;
Object.keys(changes).forEach((paramKey) => {
url += `&${paramKey}=${encodeURIComponent(String(changes[paramKey]))}`;
});
console.log(url);
fetch(url, { method: "GET" })
.then(() => {
alert("Daten erfolgreich gesendet!");
if (networkChanges) {
alert(
"Hinweis: Die Änderungen in CPL-Name und den Netzwerkeinstellungen werden erst nach einem Neustart des CPL wirksam."
);
handleReboot(newIp); // handleReboot mit neuer IP aufrufen
}
})
.catch((error) => {
console.error("Fehler beim Senden der Daten:", error);
alert("Fehler beim Senden der Daten.");
});
} else {
alert("Keine Änderungen vorgenommen.");
}
};
export default handleSubmit;

View File

@@ -0,0 +1,49 @@
// components/main/settingsPageComponents/hooks/useAdminAuth.ts
import { useState, useEffect } from "react";
import CryptoJS from "crypto-js";
function decryptToken(encryptedToken: string) {
const encryptionKey = process.env.NEXT_PUBLIC_ENCRYPTION_KEY;
const encryptionIV = process.env.NEXT_PUBLIC_ENCRYPTION_IV;
if (!encryptionKey || !encryptionIV) {
throw new Error("Encryption key or IV is not defined.");
}
const key = CryptoJS.enc.Utf8.parse(encryptionKey);
const iv = CryptoJS.enc.Utf8.parse(encryptionIV);
const bytes = CryptoJS.AES.decrypt(encryptedToken, key, { iv });
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
}
export function useAdminAuth(showModal: boolean) {
const [isAdminLoggedIn, setAdminLoggedIn] = useState(false);
function logoutAdmin() {
sessionStorage.removeItem("token");
localStorage.setItem("isAdminLoggedIn", "false");
setAdminLoggedIn(false);
}
useEffect(() => {
if (showModal) {
const token = sessionStorage.getItem("token");
if (token) {
try {
const { exp } = decryptToken(token);
if (Date.now() < exp) {
setAdminLoggedIn(true);
} else {
logoutAdmin();
}
} catch (error) {
console.error("Token-Entschlüsselung fehlgeschlagen:", error);
logoutAdmin();
}
}
}
}, [showModal]);
return { isAdminLoggedIn, logoutAdmin };
}

View File

@@ -0,0 +1,30 @@
// components/main/settingsPageComponents/hooks/useSystemSettings.ts
import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../../../redux/store";
export function useSystemSettings(showModal: boolean) {
const settings = useSelector((state: RootState) => state.systemSettings);
const [formValues, setFormValues] = useState(settings);
const [originalValues, setOriginalValues] = useState({});
useEffect(() => {
if (showModal) {
setFormValues(settings);
setOriginalValues({
name: settings.deviceName,
mac1: settings.mac1,
ip: settings.ip,
subnet: settings.subnet,
gateway: settings.gateway,
systemUhr: settings.cplInternalTimestamp,
ntp1: settings.ntp1,
ntp2: settings.ntp2,
ntp3: settings.ntp3,
ntpTimezone: settings.ntpTimezone,
active: settings.ntpActive,
});
}
}, [showModal, settings]);
return { formValues, setFormValues, originalValues };
}

View File

@@ -0,0 +1,28 @@
// components/main/settingsPageComponents/utils/cryptoUtils.ts
import CryptoJS from "crypto-js";
// Generiert den Schlüssel und IV für AES-Verschlüsselung
export function generateKeyAndIV() {
const encryptionKey = process.env.NEXT_PUBLIC_ENCRYPTION_KEY;
const encryptionIV = process.env.NEXT_PUBLIC_ENCRYPTION_IV;
if (!encryptionKey || !encryptionIV) {
throw new Error("Encryption key or IV is not defined.");
}
const key = CryptoJS.enc.Utf8.parse(encryptionKey);
const iv = CryptoJS.enc.Utf8.parse(encryptionIV);
return { key, iv };
}
// Generiert einen verschlüsselten Token
export function generateToken(user) {
const payload = {
username: user.username,
role: user.role,
exp: Date.now() + 5 * 60 * 1000, // Ablaufzeit: 5 Minuten
};
const token = JSON.stringify(payload);
const { key, iv } = generateKeyAndIV();
return CryptoJS.AES.encrypt(token, key, { iv }).toString();
}