db backup and restore implemented
This commit is contained in:
1 parent
8353a24f6b
commit
19ec020046
18 files changed
+847
-118
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import { auth } from '@clerk/nextjs/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getDatabase, DatabaseFactory } from '@/lib/database'
|
||||
import { ensureUserSynced } from '@/lib/sync-user'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
const BACKUP_DIR = path.join(process.cwd(), 'backups')
|
||||
const DB_PATH = path.join(process.cwd(), 'data', 'fitai.db')
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const { userId } = await auth()
|
||||
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
|
||||
|
||||
const db = await getDatabase()
|
||||
const user = await ensureUserSynced(userId, db)
|
||||
|
||||
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
|
||||
return new NextResponse('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
const { filename } = await req.json()
|
||||
if (!filename) {
|
||||
return new NextResponse('Filename is required', { status: 400 })
|
||||
}
|
||||
|
||||
const backupPath = path.join(BACKUP_DIR, filename)
|
||||
if (!fs.existsSync(backupPath)) {
|
||||
return new NextResponse('Backup file not found', { status: 404 })
|
||||
}
|
||||
|
||||
// Close existing connection
|
||||
await DatabaseFactory.disconnect()
|
||||
|
||||
// Restore file
|
||||
fs.copyFileSync(backupPath, DB_PATH)
|
||||
|
||||
// Re-initialize connection (will happen automatically on next getDatabase call, but good to verify)
|
||||
await getDatabase()
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Restore backup error:', error)
|
||||
return new NextResponse('Internal Server Error', { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { auth } from '@clerk/nextjs/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getDatabase } from '@/lib/database'
|
||||
import { ensureUserSynced } from '@/lib/sync-user'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
const BACKUP_DIR = path.join(process.cwd(), 'backups')
|
||||
const DB_PATH = path.join(process.cwd(), 'data', 'fitai.db')
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const { userId } = await auth()
|
||||
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
|
||||
|
||||
const db = await getDatabase()
|
||||
const user = await ensureUserSynced(userId, db)
|
||||
|
||||
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
|
||||
return new NextResponse('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
if (!fs.existsSync(BACKUP_DIR)) {
|
||||
fs.mkdirSync(BACKUP_DIR, { recursive: true })
|
||||
}
|
||||
|
||||
const files = fs.readdirSync(BACKUP_DIR)
|
||||
.filter(file => file.endsWith('.db'))
|
||||
.map(file => {
|
||||
const stats = fs.statSync(path.join(BACKUP_DIR, file))
|
||||
return {
|
||||
name: file,
|
||||
size: stats.size,
|
||||
createdAt: stats.birthtime
|
||||
}
|
||||
})
|
||||
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
|
||||
|
||||
return NextResponse.json(files)
|
||||
} catch (error) {
|
||||
console.error('List backups error:', error)
|
||||
return new NextResponse('Internal Server Error', { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const { userId } = await auth()
|
||||
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
|
||||
|
||||
const db = await getDatabase()
|
||||
const user = await ensureUserSynced(userId, db)
|
||||
|
||||
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
|
||||
return new NextResponse('Forbidden', { status: 403 })
|
||||
}
|
||||
|
||||
if (!fs.existsSync(BACKUP_DIR)) {
|
||||
fs.mkdirSync(BACKUP_DIR, { recursive: true })
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
|
||||
const backupPath = path.join(BACKUP_DIR, `backup-${timestamp}.db`)
|
||||
|
||||
// Ensure source DB exists
|
||||
if (!fs.existsSync(DB_PATH)) {
|
||||
return new NextResponse('Database file not found', { status: 404 })
|
||||
}
|
||||
|
||||
// Copy file
|
||||
fs.copyFileSync(DB_PATH, backupPath)
|
||||
|
||||
return NextResponse.json({ success: true, filename: `backup-${timestamp}.db` })
|
||||
} catch (error) {
|
||||
console.error('Create backup error:', error)
|
||||
return new NextResponse('Internal Server Error', { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { getDatabase } from '@/lib/database';
|
||||
// POST - Mark goal as complete
|
||||
export async function POST(
|
||||
req: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
|
||||
@@ -5,7 +5,7 @@ import { getDatabase } from '@/lib/database';
|
||||
// GET - Get specific goal
|
||||
export async function GET(
|
||||
req: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
@@ -40,7 +40,7 @@ export async function GET(
|
||||
// PUT - Update goal
|
||||
export async function PUT(
|
||||
req: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
@@ -82,7 +82,7 @@ export async function PUT(
|
||||
// DELETE - Delete goal
|
||||
export async function DELETE(
|
||||
req: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useUser } from "@clerk/nextjs";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
interface UserProfile {
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import axios from "axios";
|
||||
import { Database, Download, RefreshCw, AlertTriangle, Check, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface Backup {
|
||||
name: string;
|
||||
size: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
const [backups, setBackups] = useState<Backup[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [creatingBackup, setCreatingBackup] = useState(false);
|
||||
const [restoring, setRestoring] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
|
||||
|
||||
const fetchBackups = async () => {
|
||||
try {
|
||||
const response = await axios.get("/api/admin/backups");
|
||||
setBackups(response.data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch backups:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchBackups();
|
||||
}, []);
|
||||
|
||||
const handleCreateBackup = async () => {
|
||||
setCreatingBackup(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await axios.post("/api/admin/backups");
|
||||
await fetchBackups();
|
||||
setMessage({ type: 'success', text: 'Backup created successfully' });
|
||||
} catch (error) {
|
||||
console.error("Failed to create backup:", error);
|
||||
setMessage({ type: 'error', text: 'Failed to create backup' });
|
||||
} finally {
|
||||
setCreatingBackup(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestore = async (filename: string) => {
|
||||
if (!window.confirm(`Are you sure you want to restore from ${filename}? This will overwrite the current database.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRestoring(filename);
|
||||
setMessage(null);
|
||||
try {
|
||||
await axios.post("/api/admin/backups/restore", { filename });
|
||||
setMessage({ type: 'success', text: 'Database restored successfully' });
|
||||
// Optional: Refresh page or force re-login if session is invalidated
|
||||
} catch (error) {
|
||||
console.error("Failed to restore backup:", error);
|
||||
setMessage({ type: 'error', text: 'Failed to restore backup' });
|
||||
} finally {
|
||||
setRestoring(null);
|
||||
}
|
||||
};
|
||||
|
||||
const formatSize = (bytes: number) => {
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let size = bytes;
|
||||
let unitIndex = 0;
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex++;
|
||||
}
|
||||
return `${size.toFixed(2)} ${units[unitIndex]}`;
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleString();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-8 p-8">
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold text-slate-900">Settings</h2>
|
||||
<p className="text-slate-500 mt-2">Manage your application settings and database.</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-blue-50 rounded-lg">
|
||||
<Database className="w-6 h-6 text-blue-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-slate-900">Database Management</h3>
|
||||
<p className="text-sm text-slate-500">Create backups and restore your database</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleCreateBackup}
|
||||
disabled={creatingBackup}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{creatingBackup ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}
|
||||
Create Backup
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`p-4 rounded-lg mb-6 flex items-center gap-2 ${message.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
|
||||
}`}>
|
||||
{message.type === 'success' ? <Check className="w-5 h-5" /> : <AlertTriangle className="w-5 h-5" />}
|
||||
{message.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead className="bg-slate-50 border-b">
|
||||
<tr>
|
||||
<th className="px-6 py-4 font-semibold text-slate-900">Filename</th>
|
||||
<th className="px-6 py-4 font-semibold text-slate-900">Size</th>
|
||||
<th className="px-6 py-4 font-semibold text-slate-900">Created At</th>
|
||||
<th className="px-6 py-4 font-semibold text-slate-900 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="px-6 py-8 text-center text-slate-500">
|
||||
Loading backups...
|
||||
</td>
|
||||
</tr>
|
||||
) : backups.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="px-6 py-8 text-center text-slate-500">
|
||||
No backups found
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
backups.map((backup) => (
|
||||
<tr key={backup.name} className="hover:bg-slate-50 transition-colors">
|
||||
<td className="px-6 py-4 font-medium text-slate-900">{backup.name}</td>
|
||||
<td className="px-6 py-4 text-slate-600">{formatSize(backup.size)}</td>
|
||||
<td className="px-6 py-4 text-slate-600">{formatDate(backup.createdAt)}</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRestore(backup.name)}
|
||||
disabled={!!restoring}
|
||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||
>
|
||||
{restoring === backup.name ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
Restore
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user