feat: implement Backups, Security, and SettingsLayout pages with API integration and state management

This commit is contained in:
Wikid82
2025-11-20 11:37:58 -05:00
parent 4fcc0d6c4f
commit 46b67d2414
5 changed files with 502 additions and 202 deletions
+218
View File
@@ -0,0 +1,218 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card } from '../components/ui/Card'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { toast } from '../components/Toast'
import { getBackups, createBackup, restoreBackup, deleteBackup } from '../api/backups'
import { getSettings, updateSetting } from '../api/settings'
import { Loader2, Download, RotateCcw, Plus, Archive, Trash2, Save } from 'lucide-react'
export default function Backups() {
const queryClient = useQueryClient()
const [interval, setInterval] = useState('7')
const [retention, setRetention] = useState('30')
// Fetch Backups
const { data: backups, isLoading: isLoadingBackups } = useQuery({
queryKey: ['backups'],
queryFn: getBackups,
})
// Fetch Settings
const { data: settings } = useQuery({
queryKey: ['settings'],
queryFn: getSettings,
})
// Update local state when settings load
useState(() => {
if (settings) {
if (settings['backup.interval']) setInterval(settings['backup.interval'])
if (settings['backup.retention']) setRetention(settings['backup.retention'])
}
})
const createMutation = useMutation({
mutationFn: createBackup,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['backups'] })
toast.success('Backup created successfully')
},
onError: (error: any) => {
toast.error(`Failed to create backup: ${error.message}`)
},
})
const restoreMutation = useMutation({
mutationFn: restoreBackup,
onSuccess: () => {
toast.success('Backup restored successfully. Please restart the container.')
},
onError: (error: any) => {
toast.error(`Failed to restore backup: ${error.message}`)
},
})
const deleteMutation = useMutation({
mutationFn: deleteBackup,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['backups'] })
toast.success('Backup deleted successfully')
},
onError: (error: any) => {
toast.error(`Failed to delete backup: ${error.message}`)
},
})
const saveSettingsMutation = useMutation({
mutationFn: async () => {
await updateSetting('backup.interval', interval, 'system', 'int')
await updateSetting('backup.retention', retention, 'system', 'int')
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings'] })
toast.success('Backup settings saved')
},
onError: (error: any) => {
toast.error(`Failed to save settings: ${error.message}`)
},
})
const handleDownload = (_filename: string) => {
// Direct download link
// Assuming we have a download endpoint that serves the file
// For now, we can use window.open or create a link element
// But we need an auth token.
// A better way is to use the API client to get a blob and download it.
// Or just show a toast as before if not implemented fully.
toast.info('Download logic needs backend implementation for authenticated file serving')
}
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
<Archive className="w-8 h-8" />
Backups
</h1>
{/* Settings Section */}
<Card className="p-6">
<h2 className="text-lg font-semibold mb-4 text-gray-900 dark:text-white">Configuration</h2>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
<Input
label="Backup Interval (Days)"
type="number"
value={interval}
onChange={(e) => setInterval(e.target.value)}
min="1"
/>
<Input
label="Retention Period (Days)"
type="number"
value={retention}
onChange={(e) => setRetention(e.target.value)}
min="1"
/>
<Button
onClick={() => saveSettingsMutation.mutate()}
isLoading={saveSettingsMutation.isPending}
className="mb-0.5"
>
<Save className="w-4 h-4 mr-2" />
Save Settings
</Button>
</div>
</Card>
{/* Actions */}
<div className="flex justify-end">
<Button onClick={() => createMutation.mutate()} isLoading={createMutation.isPending}>
<Plus className="w-4 h-4 mr-2" />
Create Backup
</Button>
</div>
{/* List */}
<Card className="overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="bg-gray-50 dark:bg-gray-800 text-gray-500 dark:text-gray-400">
<tr>
<th className="px-6 py-3 font-medium">Filename</th>
<th className="px-6 py-3 font-medium">Size</th>
<th className="px-6 py-3 font-medium">Created At</th>
<th className="px-6 py-3 font-medium text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
{isLoadingBackups ? (
<tr>
<td colSpan={4} className="px-6 py-8 text-center">
<Loader2 className="w-6 h-6 animate-spin mx-auto text-blue-500" />
</td>
</tr>
) : backups?.length === 0 ? (
<tr>
<td colSpan={4} className="px-6 py-8 text-center text-gray-500">
No backups found
</td>
</tr>
) : (
backups?.map((backup: any) => (
<tr key={backup.filename} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
<td className="px-6 py-4 font-medium text-gray-900 dark:text-white">
{backup.filename}
</td>
<td className="px-6 py-4 text-gray-500 dark:text-gray-400">
{(backup.size / 1024 / 1024).toFixed(2)} MB
</td>
<td className="px-6 py-4 text-gray-500 dark:text-gray-400">
{new Date(backup.created_at).toLocaleString()}
</td>
<td className="px-6 py-4 text-right space-x-2">
<Button
variant="secondary"
size="sm"
onClick={() => handleDownload(backup.filename)}
title="Download"
>
<Download className="w-4 h-4" />
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => {
if (confirm('Are you sure you want to restore this backup? Current data will be overwritten.')) {
restoreMutation.mutate(backup.filename)
}
}}
isLoading={restoreMutation.isPending}
title="Restore"
>
<RotateCcw className="w-4 h-4" />
</Button>
<Button
variant="danger"
size="sm"
onClick={() => {
if (confirm('Are you sure you want to delete this backup?')) {
deleteMutation.mutate(backup.filename)
}
}}
isLoading={deleteMutation.isPending}
title="Delete"
>
<Trash2 className="w-4 h-4" />
</Button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</Card>
</div>
)
}
+56 -6
View File
@@ -1,13 +1,17 @@
import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getLogs, getLogContent } from '../api/logs';
import { getSettings, updateSetting } from '../api/settings';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { Loader2, RefreshCw, FileText } from 'lucide-react';
import { toast } from '../components/Toast';
import { Loader2, RefreshCw, FileText, Save } from 'lucide-react';
const Logs: React.FC = () => {
const [selectedLog, setSelectedLog] = useState<string | null>(null);
const [lineCount, setLineCount] = useState(100);
const [logLevel, setLogLevel] = useState('INFO');
const queryClient = useQueryClient();
const { data: logs, isLoading: isLoadingLogs, refetch: refetchLogs } = useQuery({
queryKey: ['logs'],
@@ -20,14 +24,60 @@ const Logs: React.FC = () => {
enabled: !!selectedLog,
});
const { data: settings } = useQuery({
queryKey: ['settings'],
queryFn: getSettings,
});
// Update local state when settings load
React.useEffect(() => {
if (settings && settings['logging.level']) {
setLogLevel(settings['logging.level']);
}
}, [settings]);
const saveSettingsMutation = useMutation({
mutationFn: async () => {
await updateSetting('logging.level', logLevel, 'caddy', 'string');
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['settings'] });
toast.success('Log level saved');
},
onError: (error: any) => {
toast.error(`Failed to save log level: ${error.message}`);
},
});
return (
<div className="space-y-6">
<div className="flex justify-between items-center">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">System Logs</h1>
<Button onClick={() => { refetchLogs(); if (selectedLog) refetchContent(); }} variant="secondary" size="sm">
<RefreshCw className="w-4 h-4 mr-2" />
Refresh
</Button>
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<select
value={logLevel}
onChange={(e) => setLogLevel(e.target.value)}
className="block w-32 rounded-md border-gray-300 dark:border-gray-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-gray-700 dark:text-white"
>
<option value="DEBUG">DEBUG</option>
<option value="INFO">INFO</option>
<option value="WARN">WARN</option>
<option value="ERROR">ERROR</option>
</select>
<Button
onClick={() => saveSettingsMutation.mutate()}
isLoading={saveSettingsMutation.isPending}
size="sm"
>
<Save className="w-4 h-4" />
</Button>
</div>
<Button onClick={() => { refetchLogs(); if (selectedLog) refetchContent(); }} variant="secondary" size="sm">
<RefreshCw className="w-4 h-4 mr-2" />
Refresh
</Button>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-4 gap-6">
+146
View File
@@ -0,0 +1,146 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card } from '../components/ui/Card'
import { Input } from '../components/ui/Input'
import { Button } from '../components/ui/Button'
import { toast } from '../components/Toast'
import client from '../api/client'
import { getProfile, regenerateApiKey } from '../api/user'
import { Copy, RefreshCw, Shield } from 'lucide-react'
export default function Security() {
const [oldPassword, setOldPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [loading, setLoading] = useState(false)
const queryClient = useQueryClient()
const { data: profile, isLoading: isLoadingProfile } = useQuery({
queryKey: ['profile'],
queryFn: getProfile,
})
const regenerateMutation = useMutation({
mutationFn: regenerateApiKey,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['profile'] })
toast.success('API Key regenerated successfully')
},
onError: (error: any) => {
toast.error(`Failed to regenerate API key: ${error.message}`)
},
})
const handleChangePassword = async (e: React.FormEvent) => {
e.preventDefault()
if (newPassword !== confirmPassword) {
toast.error('New passwords do not match')
return
}
setLoading(true)
try {
await client.post('/auth/change-password', {
old_password: oldPassword,
new_password: newPassword,
})
toast.success('Password updated successfully')
setOldPassword('')
setNewPassword('')
setConfirmPassword('')
} catch (err: any) {
toast.error(err.response?.data?.error || 'Failed to update password')
} finally {
setLoading(false)
}
}
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text)
toast.success('Copied to clipboard')
}
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
<Shield className="w-8 h-8" />
Security
</h1>
<div className="grid gap-6">
{/* Change Password */}
<Card className="max-w-2xl p-6">
<h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">Change Password</h2>
<form onSubmit={handleChangePassword} className="space-y-4">
<Input
label="Current Password"
type="password"
value={oldPassword}
onChange={e => setOldPassword(e.target.value)}
required
/>
<Input
label="New Password"
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
required
/>
<Input
label="Confirm New Password"
type="password"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
required
/>
<Button type="submit" isLoading={loading}>
Update Password
</Button>
</form>
</Card>
{/* API Key */}
<Card className="max-w-2xl p-6">
<h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">API Key</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
Use this key to authenticate with the API externally. Keep it secret!
</p>
{isLoadingProfile ? (
<div className="animate-pulse h-10 bg-gray-200 dark:bg-gray-700 rounded" />
) : (
<div className="space-y-4">
<div className="flex gap-2">
<Input
value={profile?.api_key || 'No API Key generated'}
readOnly
className="font-mono text-sm"
/>
<Button
variant="secondary"
onClick={() => copyToClipboard(profile?.api_key || '')}
disabled={!profile?.api_key}
>
<Copy className="w-4 h-4" />
</Button>
</div>
<Button
variant="danger"
onClick={() => {
if (confirm('Are you sure? This will invalidate the old key.')) {
regenerateMutation.mutate()
}
}}
isLoading={regenerateMutation.isPending}
>
<RefreshCw className="w-4 h-4 mr-2" />
{profile?.api_key ? 'Regenerate Key' : 'Generate Key'}
</Button>
</div>
)}
</Card>
</div>
</div>
)
}
-196
View File
@@ -1,196 +0,0 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Card } from '../components/ui/Card'
import { Input } from '../components/ui/Input'
import { Button } from '../components/ui/Button'
import { toast } from '../components/Toast'
import client from '../api/client'
import { getBackups, createBackup, restoreBackup } from '../api/backups'
import { Loader2, Download, RotateCcw, Plus, Archive } from 'lucide-react'
export default function Settings() {
const [oldPassword, setOldPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [loading, setLoading] = useState(false)
const queryClient = useQueryClient()
const { data: backups, isLoading: isLoadingBackups } = useQuery({
queryKey: ['backups'],
queryFn: getBackups,
})
const createMutation = useMutation({
mutationFn: createBackup,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['backups'] })
toast.success('Backup created successfully')
},
onError: (error: any) => {
toast.error(`Failed to create backup: ${error.message}`)
},
})
const restoreMutation = useMutation({
mutationFn: restoreBackup,
onSuccess: () => {
toast.success('Backup restored successfully. Please restart the container.')
},
onError: (error: any) => {
toast.error(`Failed to restore backup: ${error.message}`)
},
})
const handleChangePassword = async (e: React.FormEvent) => {
e.preventDefault()
if (newPassword !== confirmPassword) {
toast.error('New passwords do not match')
return
}
setLoading(true)
try {
await client.post('/auth/change-password', {
old_password: oldPassword,
new_password: newPassword,
})
toast.success('Password updated successfully')
setOldPassword('')
setNewPassword('')
setConfirmPassword('')
} catch (err: any) {
toast.error(err.response?.data?.error || 'Failed to update password')
} finally {
setLoading(false)
}
}
const handleDownload = (_filename: string) => {
toast.info('Download not yet implemented in backend')
}
return (
<div className="p-8 space-y-8">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-6">Settings</h1>
<div className="grid gap-6">
<Card className="max-w-md p-6">
<h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">Change Password</h2>
<form onSubmit={handleChangePassword} className="space-y-4">
<Input
label="Current Password"
type="password"
value={oldPassword}
onChange={e => setOldPassword(e.target.value)}
required
/>
<Input
label="New Password"
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
required
/>
<Input
label="Confirm New Password"
type="password"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
required
/>
<Button type="submit" isLoading={loading} className="w-full">
Update Password
</Button>
</form>
</Card>
<Card className="p-6">
<div className="flex justify-between items-center mb-6">
<div>
<h2 className="text-xl font-semibold text-gray-900 dark:text-white flex items-center">
<Archive className="w-5 h-5 mr-2" />
Backups
</h2>
<p className="text-sm text-gray-500 mt-1">
Manage system backups. Backups include the database and Caddy configuration.
</p>
</div>
<Button
onClick={() => createMutation.mutate()}
isLoading={createMutation.isPending}
variant="primary"
>
<Plus className="w-4 h-4 mr-2" />
Create Backup
</Button>
</div>
{isLoadingBackups ? (
<div className="flex justify-center p-8">
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-800">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Filename</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Size</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Date</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Actions</th>
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
{backups?.map((backup) => (
<tr key={backup.name}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
{backup.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{(backup.size / 1024 / 1024).toFixed(2)} MB
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
{new Date(backup.mod_time).toLocaleString()}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
<Button
variant="secondary"
size="sm"
onClick={() => handleDownload(backup.name)}
title="Download"
>
<Download className="w-4 h-4 text-blue-600 dark:text-blue-400" />
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => {
if (confirm(`Are you sure you want to restore ${backup.name}? This will overwrite current data.`)) {
restoreMutation.mutate(backup.name);
}
}}
title="Restore"
isLoading={restoreMutation.isPending}
>
<RotateCcw className="w-4 h-4 text-orange-600 dark:text-orange-400" />
</Button>
</td>
</tr>
))}
{backups?.length === 0 && (
<tr>
<td colSpan={4} className="px-6 py-8 text-center text-sm text-gray-500">
No backups found. Create one to get started.
</td>
</tr>
)}
</tbody>
</table>
</div>
)}
</Card>
</div>
</div>
)
}
+82
View File
@@ -0,0 +1,82 @@
import { Outlet, Link, useLocation } from 'react-router-dom'
import { Shield, Archive, FileText, ChevronDown, ChevronRight } from 'lucide-react'
import { useState } from 'react'
export default function SettingsLayout() {
const location = useLocation()
const [tasksOpen, setTasksOpen] = useState(true)
const isActive = (path: string) => location.pathname === path
return (
<div className="flex h-[calc(100vh-4rem)]">
{/* Settings Sidebar */}
<div className="w-64 bg-white dark:bg-dark-sidebar border-r border-gray-200 dark:border-gray-800 overflow-y-auto">
<div className="p-4">
<h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4">
Settings
</h2>
<nav className="space-y-1">
<Link
to="/settings/security"
className={`flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-md transition-colors ${
isActive('/settings/security')
? 'bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-300'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
}`}
>
<Shield className="w-4 h-4" />
Security
</Link>
{/* Tasks Group */}
<div>
<button
onClick={() => setTasksOpen(!tasksOpen)}
className="w-full flex items-center justify-between px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-md transition-colors"
>
<div className="flex items-center gap-2">
<span className="text-lg">📋</span>
Tasks
</div>
{tasksOpen ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
</button>
{tasksOpen && (
<div className="ml-4 mt-1 space-y-1 border-l-2 border-gray-100 dark:border-gray-800 pl-2">
<Link
to="/settings/tasks/backups"
className={`flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-md transition-colors ${
isActive('/settings/tasks/backups')
? 'bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-300'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
}`}
>
<Archive className="w-4 h-4" />
Backups
</Link>
<Link
to="/settings/tasks/logs"
className={`flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-md transition-colors ${
isActive('/settings/tasks/logs')
? 'bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-300'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
}`}
>
<FileText className="w-4 h-4" />
Logs
</Link>
</div>
)}
</div>
</nav>
</div>
</div>
{/* Content Area */}
<div className="flex-1 overflow-y-auto p-8">
<Outlet />
</div>
</div>
)
}