Files
FarmaFinder/backend/create-admin.js
2026-04-01 01:18:21 +02:00

89 lines
2.4 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import sqlite3 from 'sqlite3';
import { promisify } from 'util';
import bcrypt from 'bcrypt';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const dbPath = path.join(__dirname, 'database.sqlite');
const db = new sqlite3.Database(dbPath);
// Custom wrapper to get lastID from db.run
function dbRun(sql, params = []) {
return new Promise((resolve, reject) => {
db.run(sql, params, function(err) {
if (err) reject(err);
else resolve({ lastID: this.lastID, changes: this.changes });
});
});
}
const dbGet = promisify(db.get.bind(db));
// Initialize users table
async function initDatabase() {
try {
await dbRun(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
console.log('Database table initialized');
} catch (error) {
console.error('Error initializing database:', error);
throw error;
}
}
async function createAdmin() {
try {
// Initialize database tables first
await initDatabase();
// Default admin credentials
const username = process.env.ADMIN_USERNAME || 'admin';
const password = process.env.ADMIN_PASSWORD || 'admin123';
// Check if admin already exists
const existing = await dbGet(
'SELECT * FROM users WHERE username = ?',
[username]
);
if (existing) {
console.log(`Admin user '${username}' already exists.`);
console.log('To change the password, delete the user first and run this script again.');
db.close();
return;
}
// Hash password
const saltRounds = 10;
const passwordHash = await bcrypt.hash(password, saltRounds);
// Create admin user
await dbRun(
'INSERT INTO users (username, password_hash) VALUES (?, ?)',
[username, passwordHash]
);
console.log('✅ Admin user created successfully!');
console.log(`Username: ${username}`);
console.log(`Password: ${password}`);
console.log('\n⚠ IMPORTANT: Change the default password after first login!');
console.log(' You can set ADMIN_USERNAME and ADMIN_PASSWORD environment variables to customize.');
} catch (error) {
console.error('Error creating admin user:', error);
} finally {
db.close();
}
}
createAdmin();