feat: implement one-time admin token generation and upgrade process

This commit is contained in:
averel10
2026-03-13 08:11:40 +01:00
parent b9f6836f1a
commit cda21a60ec
6 changed files with 235 additions and 5 deletions

View File

@@ -88,6 +88,24 @@ Open [http://localhost:3000](http://localhost:3000) in your browser.
4. Review and run `npm run db:push` 4. Review and run `npm run db:push`
5. Update relevant server actions and components 5. Update relevant server actions and components
## Admin Signup System
The platform automatically generates a one-time admin token on startup if no admin exists in the database. This token is logged to the console and can only be used once.
### Upgrading to Admin Account
1. Sign in with your regular account
2. Try to access `/admin`
3. You'll see a form asking for the admin token
4. Paste the token from the console output
5. Click "Admin aktivieren" to upgrade your account
After successful upgrade:
- The token becomes invalid
- Your account gains full admin privileges
- No new token is generated (admin now exists)
- Trying to upgrade another account will fail (token is spent)
## Development Notes ## Development Notes
- Database schema is defined in `src/lib/model/` - Database schema is defined in `src/lib/model/`

View File

@@ -0,0 +1,30 @@
'use server';
import { auth } from '@/lib/auth';
import db from '@/lib/db';
import { user } from '@/lib/model/auth-schema';
import { eq } from 'drizzle-orm';
import { headers } from 'next/headers';
import { verifyAdminToken } from './verify-admin-token';
export async function setUserAsAdmin(email: string, adminToken: string): Promise<{ success: boolean; error?: string }> {
// Verify the token is valid
const tokenResult = await verifyAdminToken(adminToken);
if (!tokenResult.valid) {
return { success: false, error: 'Invalid or expired admin token' };
}
try {
// Update user admin flag
await db.update(user).set({ admin: true }).where(eq(user.email, email));
// Clear the token so it can't be used again
delete process.env.ADMIN_SIGNUP_TOKEN;
return { success: true };
} catch (error) {
console.error('Error setting admin:', error);
return { success: false, error: 'Failed to set admin status' };
}
}

View File

@@ -0,0 +1,14 @@
'use server';
export async function verifyAdminToken(token: string): Promise<{ valid: boolean }> {
const storedToken = process.env.ADMIN_SIGNUP_TOKEN;
// Token is invalid if:
// 1. No token exists (already used or no token was generated)
// 2. Provided token doesn't match
if (!storedToken || token !== storedToken) {
return { valid: false };
}
return { valid: true };
}

View File

@@ -1,5 +1,6 @@
import DatasetsList from "@/components/DatasetsList"; import DatasetsList from "@/components/DatasetsList";
import CreateDatasetModal from "@/components/CreateDatasetModal"; import CreateDatasetModal from "@/components/CreateDatasetModal";
import { AdminTokenForm } from "@/components/AdminTokenForm";
import { requireAdmin } from "@/lib/auth"; import { requireAdmin } from "@/lib/auth";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
@@ -12,7 +13,7 @@ export default async function AdminPage() {
} }
if (!result.admin) { if (!result.admin) {
redirect("/"); return <AdminTokenForm userEmail={result.session?.user.email || ""} />;
} }
return ( return (

View File

@@ -0,0 +1,139 @@
'use client';
import { useState } from 'react';
import { setUserAsAdmin } from '@/app/actions/set-user-admin';
import { useRouter } from 'next/navigation';
interface AdminTokenFormProps {
userEmail: string;
}
export function AdminTokenForm({ userEmail }: AdminTokenFormProps) {
const [adminToken, setAdminToken] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState(false);
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const result = await setUserAsAdmin(userEmail, adminToken);
if (result.success) {
setSuccess(true);
setAdminToken('');
// Refresh the page to verify admin status
setTimeout(() => {
router.refresh();
}, 1500);
} else {
setError(result.error || 'Invalid admin token');
}
} catch (err: any) {
setError(err.message || 'Ein Fehler ist aufgetreten');
} finally {
setLoading(false);
}
};
return (
<div className="flex items-center justify-center py-12">
<div className="w-full max-w-md">
<div className="bg-white rounded-lg shadow-lg overflow-hidden border border-gray-200">
{/* Header */}
<div className="bg-gradient-to-r from-amber-600 to-amber-700 px-6 py-8">
<h2 className="text-white text-xl font-bold">Admin-Zugriff erforderlich</h2>
<p className="text-amber-100 text-sm mt-2">
Sie benötigen Admin-Rechte, um diese Seite zu besuchen
</p>
</div>
{/* Form */}
<form onSubmit={handleSubmit} className="p-6 space-y-4">
{/* Success Message */}
{success && (
<div className="bg-green-50 border border-green-300 text-green-700 px-4 py-3 rounded-lg">
<p className="text-sm font-medium">
Admin-Status erfolgreich aktiviert! Seite wird aktualisiert...
</p>
</div>
)}
{/* Error Message */}
{error && (
<div className="bg-red-50 border border-red-300 text-red-700 px-4 py-3 rounded-lg flex items-start gap-3">
<svg
className="w-5 h-5 mt-0.5 flex-shrink-0"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fillRule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
clipRule="evenodd"
/>
</svg>
<span className="text-sm">{error}</span>
</div>
)}
{/* User Info */}
<div className="bg-gray-50 p-3 rounded-lg border border-gray-200">
<p className="text-sm text-gray-600">
<span className="font-semibold">Benutzer:</span> {userEmail}
</p>
</div>
{/* Admin Token Input */}
<div>
<label htmlFor="adminToken" className="block text-sm font-medium text-gray-700 mb-2">
Admin-Token
</label>
<input
id="adminToken"
type="password"
value={adminToken}
onChange={(e) => setAdminToken(e.target.value)}
placeholder="Admin-Token eingeben"
required
disabled={loading || success}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-transparent transition-colors disabled:bg-gray-100 disabled:text-gray-500"
/>
<p className="text-xs text-gray-500 mt-1">
Geben Sie den Admin-Token ein, um Admin-Rechte zu aktivieren
</p>
</div>
{/* Submit Button */}
<button
type="submit"
disabled={loading || success}
className="w-full bg-amber-600 hover:bg-amber-700 disabled:bg-gray-400 text-white font-semibold py-2 px-4 rounded-lg transition-colors mt-6 flex items-center justify-center gap-2"
>
{loading && (
<svg
className="w-5 h-5 animate-spin"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 4v16m8-8H4"
/>
</svg>
)}
{loading ? 'Wird überprüft...' : success ? 'Admin aktiviert ✓' : 'Admin aktivieren'}
</button>
</form>
</div>
</div>
</div>
);
}

View File

@@ -1,9 +1,15 @@
import { migrate } from 'drizzle-orm/better-sqlite3/migrator'; import { eq } from 'drizzle-orm';
import db from '@/lib/db';
import { join } from 'path';
export async function register() { export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') { if (process.env.NEXT_RUNTIME === 'nodejs') {
// Import nodejs-only modules dynamically
const { migrate } = await import('drizzle-orm/better-sqlite3/migrator');
const { join } = await import('path');
const { randomBytes } = await import('crypto');
const { count } = await import('drizzle-orm');
const db = (await import('@/lib/db')).default;
const { user } = await import('@/lib/model/auth-schema');
try { try {
console.log('Running database migrations...'); console.log('Running database migrations...');
@@ -13,8 +19,30 @@ export async function register() {
migrate(db, { migrationsFolder }); migrate(db, { migrationsFolder });
console.log('✓ Database migrations completed successfully'); console.log('✓ Database migrations completed successfully');
// Check if any admin exists
const adminCount = await db.select({ count: count() }).from(user).where(eq(user.admin, true));
const hasAdmin = adminCount.length > 0 && adminCount[0].count > 0;
// If no admin exists, generate a one-time token
if (!hasAdmin) {
const token = randomBytes(32).toString('hex');
process.env.ADMIN_SIGNUP_TOKEN = token;
console.log('\n╔════════════════════════════════════════════════════════════════╗');
console.log('║ ADMIN TOKEN GENERATED ║');
console.log('╠════════════════════════════════════════════════════════════════╣');
console.log(`║ Token: ${token}`);
console.log('║ ║');
console.log('║ This token can be used ONCE to upgrade a user to admin. ║');
console.log('║ After the first use, it will become invalid. ║');
console.log('║ ║');
console.log('║ 1. Sign in with your account ║');
console.log('║ 2. Try to access /admin ║');
console.log('║ 3. Enter this token when prompted ║');
console.log('╚════════════════════════════════════════════════════════════════╝\n');
}
} catch (error) { } catch (error) {
console.error('Failed to run database migrations:', error); console.error('Failed to initialize app:', error);
process.exit(1); process.exit(1);
} }
} }