diff --git a/src/lib/auth-actions.ts b/src/lib/auth-actions.ts index e0a3e74..4eb4190 100644 --- a/src/lib/auth-actions.ts +++ b/src/lib/auth-actions.ts @@ -3,6 +3,7 @@ import { redirect } from 'next/navigation'; import { compare } from 'bcryptjs'; import { SignJWT } from 'jose'; import { cookies } from 'next/headers'; +import { getDb } from './db'; const secretKey = process.env.JWT_SECRET_KEY; const key = new TextEncoder().encode(secretKey); @@ -17,12 +18,16 @@ export async function encrypt(payload: any) { export async function login(prevState: any, formData: FormData) { const password = formData.get('password') as string; + + // Ensure DB is initialized to get the hashed password + await getDb(); - if (!process.env.ADMIN_PASSWORD) { - return { message: 'Admin password is not set.' }; + if (!process.env.ADMIN_PASSWORD_HASH) { + console.error('ADMIN_PASSWORD_HASH is not set. Please check your environment variables and db setup.') + return { message: 'Application is not configured correctly. Please contact support.' }; } - const passwordsMatch = await compare(password, process.env.ADMIN_PASSWORD); + const passwordsMatch = await compare(password, process.env.ADMIN_PASSWORD_HASH); if (passwordsMatch) { // Create the session diff --git a/src/lib/db.ts b/src/lib/db.ts index 46b038c..ae5bfb3 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -20,20 +20,21 @@ async function seedDatabase(db: Awaited>) { } async function setupAdminPassword() { - if (process.env.ADMIN_PASSWORD) { - const plainPassword = process.env.ADMIN_PASSWORD; - // In a real app, you wouldn't log this. This is for demonstration. - console.log(`Hashing admin password: ${plainPassword}`); - process.env.ADMIN_PASSWORD = await hash(plainPassword, 10); - console.log(`Hashed admin password stored in environment.`); - } else { - console.warn("ADMIN_PASSWORD environment variable not set. Using default."); - process.env.ADMIN_PASSWORD = await hash('admin', 10); + // We hash the password and store the hash in an environment variable. + // This avoids storing the plaintext password and ensures it's consistent. + if (!process.env.ADMIN_PASSWORD_HASH) { + const adminPassword = process.env.ADMIN_PASSWORD || 'admin'; + console.log(`Admin password is not hashed. Hashing now. Default is 'admin' if not set in .env.local`); + process.env.ADMIN_PASSWORD_HASH = await hash(adminPassword, 10); } } export async function getDb() { if (!db) { + // This needs to run before the DB connection is established + // to ensure the hash is available for any part of the app that needs it. + await setupAdminPassword(); + const newDb = await open({ filename: './database.db', driver: sqlite3.Database, @@ -51,7 +52,6 @@ export async function getDb() { ); `); - await setupAdminPassword(); await seedDatabase(newDb); db = newDb;