This commit is contained in:
@@ -1,23 +1,68 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { fetchAllStatus, containerAction, addVps, deleteVps, fetchLogs } from './api/client'
|
||||
import { fetchAllStatus, containerAction, addVps, deleteVps, fetchLogs, authStatus, getToken, setToken } from './api/client'
|
||||
import Header from './components/Header'
|
||||
import VpsCard from './components/VpsCard'
|
||||
import LogsModal from './components/LogsModal'
|
||||
import AddVpsModal from './components/AddVpsModal'
|
||||
import LoginPage from './components/LoginPage'
|
||||
|
||||
const REFRESH_INTERVAL = 30_000
|
||||
|
||||
export default function App() {
|
||||
const [token, setTokenState] = useState(() => getToken())
|
||||
const [username, setUsername] = useState(null)
|
||||
const [isFirstUser, setIsFirstUser] = useState(false)
|
||||
const [authChecked, setAuthChecked] = useState(false)
|
||||
|
||||
const [vpsList, setVpsList] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
const [error, setError] = useState(null)
|
||||
const [lastUpdate, setLastUpdate] = useState(null)
|
||||
const [logsModal, setLogsModal] = useState(null) // { vpsId, containerId, name }
|
||||
const [logsModal, setLogsModal] = useState(null)
|
||||
const [logsContent, setLogsContent] = useState('')
|
||||
const [logsLoading, setLogsLoading] = useState(false)
|
||||
const [showAddVps, setShowAddVps] = useState(false)
|
||||
|
||||
// Vérifie si des utilisateurs existent (pour afficher login ou register)
|
||||
useEffect(() => {
|
||||
authStatus()
|
||||
.then(({ has_users }) => setIsFirstUser(!has_users))
|
||||
.catch(() => setIsFirstUser(false))
|
||||
.finally(() => setAuthChecked(true))
|
||||
}, [])
|
||||
|
||||
// Écoute l'événement d'expiration de token émis par client.js
|
||||
useEffect(() => {
|
||||
const onExpired = () => {
|
||||
setToken(null)
|
||||
setTokenState(null)
|
||||
setUsername(null)
|
||||
}
|
||||
window.addEventListener('auth:expired', onExpired)
|
||||
return () => window.removeEventListener('auth:expired', onExpired)
|
||||
}, [])
|
||||
|
||||
const handleAuthenticated = (accessToken, role, user) => {
|
||||
setToken(accessToken)
|
||||
setTokenState(accessToken)
|
||||
// Récupère le username depuis le payload JWT (base64)
|
||||
try {
|
||||
const payload = JSON.parse(atob(accessToken.split('.')[1]))
|
||||
setUsername(payload.sub)
|
||||
} catch {
|
||||
setUsername(user ?? 'user')
|
||||
}
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
setToken(null)
|
||||
setTokenState(null)
|
||||
setUsername(null)
|
||||
setVpsList([])
|
||||
setLoading(true)
|
||||
}
|
||||
|
||||
const refresh = useCallback(async (showSpinner = false) => {
|
||||
if (showSpinner) setRefreshing(true)
|
||||
try {
|
||||
@@ -34,10 +79,21 @@ export default function App() {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
refresh()
|
||||
const id = setInterval(() => refresh(), REFRESH_INTERVAL)
|
||||
return () => clearInterval(id)
|
||||
}, [refresh])
|
||||
}, [refresh, token])
|
||||
|
||||
// Extrait le username du token stocké au rechargement de page
|
||||
useEffect(() => {
|
||||
if (token && !username) {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]))
|
||||
setUsername(payload.sub)
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}, [token, username])
|
||||
|
||||
const openLogs = async (vpsId, containerId, name) => {
|
||||
setLogsModal({ vpsId, containerId, name })
|
||||
@@ -70,10 +126,23 @@ export default function App() {
|
||||
await refresh(true)
|
||||
}
|
||||
|
||||
// Attente vérification auth
|
||||
if (!authChecked) return null
|
||||
|
||||
// Pas de token → login / register
|
||||
if (!token) {
|
||||
return (
|
||||
<LoginPage
|
||||
isFirstUser={isFirstUser}
|
||||
onAuthenticated={handleAuthenticated}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Statistiques globales
|
||||
const totalOnline = vpsList.filter(v => v.online).length
|
||||
const totalOnline = vpsList.filter(v => v.online).length
|
||||
const totalContainers = vpsList.reduce((acc, v) => acc + v.containers.length, 0)
|
||||
const totalRunning = vpsList.reduce((acc, v) => acc + v.containers.filter(c => c.status === 'running').length, 0)
|
||||
const totalRunning = vpsList.reduce((acc, v) => acc + v.containers.filter(c => c.status === 'running').length, 0)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 text-gray-100">
|
||||
@@ -82,6 +151,8 @@ export default function App() {
|
||||
onRefresh={() => refresh(true)}
|
||||
onAddVps={() => setShowAddVps(true)}
|
||||
refreshing={refreshing}
|
||||
username={username}
|
||||
onLogout={handleLogout}
|
||||
/>
|
||||
|
||||
<main className="max-w-7xl mx-auto px-4 py-8">
|
||||
|
||||
@@ -1,33 +1,23 @@
|
||||
const BASE = '/api'
|
||||
|
||||
export async function fetchAllStatus() {
|
||||
const res = await fetch(`${BASE}/status`)
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
return res.json()
|
||||
// ─── Token helpers ────────────────────────────────────────────────────────────
|
||||
|
||||
export function getToken() { return localStorage.getItem('token') }
|
||||
export function setToken(t) { t ? localStorage.setItem('token', t) : localStorage.removeItem('token') }
|
||||
|
||||
function authHeaders(extra = {}) {
|
||||
const token = getToken()
|
||||
return token
|
||||
? { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, ...extra }
|
||||
: { 'Content-Type': 'application/json', ...extra }
|
||||
}
|
||||
|
||||
export async function fetchLogs(vpsId, containerId, lines = 200) {
|
||||
const res = await fetch(`${BASE}/vps/${vpsId}/containers/${containerId}/logs?lines=${lines}`)
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function containerAction(vpsId, containerId, action) {
|
||||
const res = await fetch(`${BASE}/vps/${vpsId}/containers/${containerId}/action`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action }),
|
||||
})
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function addVps(data) {
|
||||
const res = await fetch(`${BASE}/vps`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
async function handleResponse(res) {
|
||||
if (res.status === 401) {
|
||||
setToken(null)
|
||||
window.dispatchEvent(new Event('auth:expired'))
|
||||
throw new Error('Session expirée, veuillez vous reconnecter.')
|
||||
}
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
throw new Error(err.detail ?? `HTTP ${res.status}`)
|
||||
@@ -35,8 +25,68 @@ export async function addVps(data) {
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function deleteVps(vpsId) {
|
||||
const res = await fetch(`${BASE}/vps/${vpsId}`, { method: 'DELETE' })
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
return res.json()
|
||||
// ─── Auth ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function authStatus() {
|
||||
const res = await fetch(`${BASE}/auth/status`)
|
||||
return handleResponse(res)
|
||||
}
|
||||
|
||||
export async function register(username, password) {
|
||||
const res = await fetch(`${BASE}/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
})
|
||||
return handleResponse(res)
|
||||
}
|
||||
|
||||
export async function login(username, password) {
|
||||
const res = await fetch(`${BASE}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
})
|
||||
return handleResponse(res)
|
||||
}
|
||||
|
||||
// ─── VPS ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchAllStatus() {
|
||||
const res = await fetch(`${BASE}/status`, { headers: authHeaders() })
|
||||
return handleResponse(res)
|
||||
}
|
||||
|
||||
export async function fetchLogs(vpsId, containerId, lines = 200) {
|
||||
const res = await fetch(
|
||||
`${BASE}/vps/${vpsId}/containers/${containerId}/logs?lines=${lines}`,
|
||||
{ headers: authHeaders() }
|
||||
)
|
||||
return handleResponse(res)
|
||||
}
|
||||
|
||||
export async function containerAction(vpsId, containerId, action) {
|
||||
const res = await fetch(`${BASE}/vps/${vpsId}/containers/${containerId}/action`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
body: JSON.stringify({ action }),
|
||||
})
|
||||
return handleResponse(res)
|
||||
}
|
||||
|
||||
export async function addVps(data) {
|
||||
const res = await fetch(`${BASE}/vps`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
return handleResponse(res)
|
||||
}
|
||||
|
||||
export async function deleteVps(vpsId) {
|
||||
const res = await fetch(`${BASE}/vps/${vpsId}`, {
|
||||
method: 'DELETE',
|
||||
headers: authHeaders(),
|
||||
})
|
||||
return handleResponse(res)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Monitor } from 'lucide-react'
|
||||
import { Monitor, LogOut } from 'lucide-react'
|
||||
|
||||
export default function Header({ lastUpdate, onRefresh, onAddVps, refreshing }) {
|
||||
export default function Header({ lastUpdate, onRefresh, onAddVps, refreshing, username, onLogout }) {
|
||||
return (
|
||||
<header className="sticky top-0 z-40 border-b border-gray-800 bg-gray-900/80 backdrop-blur-sm">
|
||||
<div className="max-w-7xl mx-auto px-4 h-14 flex items-center justify-between">
|
||||
@@ -41,6 +41,17 @@ export default function Header({ lastUpdate, onRefresh, onAddVps, refreshing })
|
||||
</svg>
|
||||
Ajouter un VPS
|
||||
</button>
|
||||
|
||||
{username && (
|
||||
<button
|
||||
onClick={onLogout}
|
||||
title={`Déconnexion (${username})`}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm bg-gray-800 hover:bg-gray-700 transition-colors text-gray-400 hover:text-gray-200"
|
||||
>
|
||||
<LogOut size={14} />
|
||||
<span className="hidden sm:inline">{username}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
123
vps-monitor/frontend/src/components/LoginPage.jsx
Normal file
123
vps-monitor/frontend/src/components/LoginPage.jsx
Normal file
@@ -0,0 +1,123 @@
|
||||
import { useState } from 'react'
|
||||
import { Monitor } from 'lucide-react'
|
||||
import { login, register } from '../api/client'
|
||||
|
||||
export default function LoginPage({ isFirstUser, onAuthenticated }) {
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [password2, setPassword2] = useState('')
|
||||
const [error, setError] = useState(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const isRegister = isFirstUser
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
setError(null)
|
||||
|
||||
if (isRegister) {
|
||||
if (password !== password2) {
|
||||
setError('Les mots de passe ne correspondent pas.')
|
||||
return
|
||||
}
|
||||
if (password.length < 6) {
|
||||
setError('Le mot de passe doit contenir au moins 6 caractères.')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = isRegister
|
||||
? await register(username.trim(), password)
|
||||
: await login(username.trim(), password)
|
||||
onAuthenticated(data.access_token, data.role)
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 text-gray-100 flex items-center justify-center px-4">
|
||||
<div className="w-full max-w-sm">
|
||||
{/* Logo */}
|
||||
<div className="flex flex-col items-center mb-8">
|
||||
<div className="p-3 rounded-2xl bg-indigo-500/15 mb-3">
|
||||
<Monitor size={28} className="text-indigo-400" />
|
||||
</div>
|
||||
<h1 className="text-xl font-semibold">VPS Monitor</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{isRegister ? 'Créer le compte administrateur' : 'Connexion'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="bg-gray-900 border border-gray-800 rounded-2xl p-6 space-y-4">
|
||||
{isRegister && (
|
||||
<div className="bg-indigo-950/40 border border-indigo-800/50 rounded-lg px-3 py-2 text-xs text-indigo-300">
|
||||
Aucun utilisateur n'existe encore. Le premier compte créé sera <strong>admin</strong>.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-xs text-gray-400 mb-1.5">Nom d'utilisateur</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
autoFocus
|
||||
autoComplete="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs text-gray-400 mb-1.5">Mot de passe</label>
|
||||
<input
|
||||
type="password"
|
||||
required
|
||||
autoComplete={isRegister ? 'new-password' : 'current-password'}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isRegister && (
|
||||
<div>
|
||||
<label className="block text-xs text-gray-400 mb-1.5">Confirmer le mot de passe</label>
|
||||
<input
|
||||
type="password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
value={password2}
|
||||
onChange={(e) => setPassword2(e.target.value)}
|
||||
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-sm font-medium transition-colors mt-2"
|
||||
>
|
||||
{loading
|
||||
? 'Chargement…'
|
||||
: isRegister
|
||||
? 'Créer le compte'
|
||||
: 'Se connecter'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user