maybe fix database and dashboard

This commit is contained in:
2026-04-24 15:36:51 +07:00
parent 75312d035a
commit 808c07855c
9 changed files with 508 additions and 54 deletions
+201
View File
@@ -0,0 +1,201 @@
import { useState, useEffect } from "react";
import { Shield, Server, Activity, Plus, Power, RefreshCw } from "lucide-react";
interface VpnNode {
id: string;
name: string;
country_code: string;
ip_address: string;
port: number;
status: string;
current_load: number;
}
export default function AdminDashboard() {
const [nodes, setNodes] = useState<VpnNode[]>([]);
const [loading, setLoading] = useState(true);
// Стейт формы
const [name, setName] = useState("");
const [ip, setIp] = useState("");
const [code, setCode] = useState("de");
const fetchNodes = async () => {
try {
// Пока стучимся в публичный роут, чтобы увидеть список
const res = await fetch("/api/nodes");
const data = await res.json();
setNodes(data);
} catch (e) {
console.error(e);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchNodes();
}, []);
const handleAddNode = async (e: React.FormEvent) => {
e.preventDefault();
try {
const res = await fetch("/api/admin/nodes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
country_code: code,
ip_address: ip,
port: 443,
}),
});
if (res.ok) {
setName("");
setIp("");
fetchNodes();
}
} catch (e) {
console.error(e);
}
};
return (
<div className="min-h-screen bg-[#05050A] text-foreground font-mono p-6 sm:p-12">
<header className="flex items-center justify-between mb-12 border-b border-white/10 pb-6">
<div>
<h1 className="text-2xl font-black tracking-widest text-primary flex items-center gap-3">
<Shield className="w-6 h-6" />
ORCHESTRATOR_NEXUS
</h1>
<p className="text-xs text-muted-foreground mt-2 uppercase tracking-widest">
Netrunner Global Infrastructure Control
</p>
</div>
<button
onClick={fetchNodes}
className="p-3 bg-white/5 hover:bg-white/10 rounded-full transition-colors"
>
<RefreshCw
className={`w-5 h-5 text-secondary ${loading ? "animate-spin" : ""}`}
/>
</button>
</header>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Панель добавления сервера */}
<div className="lg:col-span-1">
<div className="bg-black/40 border border-white/10 rounded-2xl p-6 relative overflow-hidden group">
<div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-secondary to-primary opacity-50" />
<h2 className="text-sm font-bold uppercase tracking-widest mb-6 flex items-center gap-2">
<Plus className="w-4 h-4 text-secondary" />
Deploy New Node
</h2>
<form onSubmit={handleAddNode} className="space-y-4">
<div>
<label className="text-[10px] text-muted-foreground uppercase tracking-widest">
Designation
</label>
<input
required
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Frankfurt Alpha"
className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-[10px] text-muted-foreground uppercase tracking-widest">
IPv4 Address
</label>
<input
required
value={ip}
onChange={(e) => setIp(e.target.value)}
placeholder="147.x.x.x"
className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1 font-mono"
/>
</div>
<div>
<label className="text-[10px] text-muted-foreground uppercase tracking-widest">
Region (ISO)
</label>
<input
required
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="de"
className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1 uppercase"
/>
</div>
</div>
<button
type="submit"
className="w-full mt-4 bg-secondary/10 hover:bg-secondary/20 text-secondary border border-secondary/30 font-bold uppercase tracking-widest text-xs py-3 rounded-lg transition-all flex items-center justify-center gap-2"
>
<Server className="w-4 h-4" /> Initialize Node
</button>
</form>
</div>
</div>
{/* Активные узлы */}
<div className="lg:col-span-2 space-y-4">
<h2 className="text-sm font-bold uppercase tracking-widest text-muted-foreground mb-4">
Active Grid
</h2>
{nodes.map((node) => (
<div
key={node.id}
className="bg-black/60 border border-white/5 rounded-2xl p-5 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 hover:border-primary/30 transition-colors"
>
<div>
<div className="flex items-center gap-3 mb-1">
<div
className={`w-2 h-2 rounded-full ${node.status === "online" ? "bg-green-500 animate-pulse" : "bg-red-500"}`}
/>
<h3 className="font-bold text-lg">{node.name}</h3>
<span className="text-[10px] bg-white/10 px-2 py-0.5 rounded text-muted-foreground uppercase">
{node.country_code}
</span>
</div>
<p className="text-xs text-muted-foreground font-mono">
{node.ip_address}:{node.port}
</p>
</div>
<div className="flex items-center gap-6 w-full sm:w-auto">
<div className="flex-1 sm:flex-none">
<p className="text-[10px] text-muted-foreground uppercase tracking-widest mb-1 flex items-center gap-1">
<Activity className="w-3 h-3" /> Load
</p>
<div className="w-full sm:w-32 h-2 bg-white/10 rounded-full overflow-hidden">
<div
className="h-full bg-primary"
style={{ width: `${node.current_load}%` }}
/>
</div>
</div>
<button
className="p-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 border border-red-500/20 rounded-lg transition-colors"
title="Force Restart"
>
<Power className="w-4 h-4" />
</button>
</div>
</div>
))}
{nodes.length === 0 && !loading && (
<div className="text-center p-12 border border-dashed border-white/10 rounded-2xl text-muted-foreground text-sm uppercase tracking-widest">
No active nodes in the grid
</div>
)}
</div>
</div>
</div>
);
}
+35 -9
View File
@@ -1,29 +1,54 @@
import { useEffect } from "react";
import { BrowserRouter, Routes, Route, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Profile from "./Profile";
import HackGame from "./HackGame"; // <-- ИМПОРТ НОВОЙ СТРАНИЦЫ
import HackGame from "./HackGame";
import { TOKEN_KEY } from "./api";
import AdminDashboard from "./AdminDashboard";
function AuthHandler({ children }: { children: React.ReactNode }) {
const navigate = useNavigate();
// Добавляем состояния для отслеживания загрузки и авторизации
const [isProcessing, setIsProcessing] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
// 1. Ищем токен в URL
const hash = window.location.hash;
if (hash.includes("token=")) {
const params = new URLSearchParams(hash.replace("#", "?"));
const token = params.get("token");
if (token) {
localStorage.setItem(TOKEN_KEY, token);
// Зачищаем URL от токена, чтобы не светить им
window.history.replaceState(null, "", window.location.pathname);
}
}
if (!localStorage.getItem(TOKEN_KEY)) {
document.body.innerHTML =
"<h1 style='color:red; text-align:center; margin-top:20%; font-family:monospace'>[ERROR] UNAUTHORIZED ACCESS</h1>";
// 2. Проверяем наличие токена после обработки URL
if (localStorage.getItem(TOKEN_KEY)) {
setIsAuthenticated(true);
}
}, [navigate]);
// 3. Сигнализируем, что проверка завершена
setIsProcessing(false);
}, []);
// БЛОКИРОВЩИК РЕНДЕРА: Пока обрабатываем токен, не пускаем детей рендериться
if (isProcessing) {
return <div className="min-h-screen bg-[#05050A]" />;
}
// Если токена нет, показываем ошибку ПРАВИЛЬНЫМ React-способом
if (!isAuthenticated) {
return (
<div className="min-h-screen bg-[#05050A] flex items-center justify-center font-mono">
<h1 className="text-[#FF003C] text-xl tracking-widest uppercase animate-pulse drop-shadow-[0_0_15px_rgba(255,0,60,0.5)]">
[ERROR] UNAUTHORIZED ACCESS
</h1>
</div>
);
}
// Если токен на месте — пускаем в ЛК
return <>{children}</>;
}
@@ -34,7 +59,8 @@ export default function App() {
<Routes>
<Route path="/" element={<Profile />} />
<Route path="/profile" element={<Profile />} />
<Route path="/hack" element={<HackGame />} /> {/* <-- НОВЫЙ РОУТ */}
<Route path="/hack" element={<HackGame />} />
<Route path="/admin" element={<AdminDashboard />} />
</Routes>
</AuthHandler>
</BrowserRouter>