You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

57 lines
1.7 KiB

const mysql = require('mysql2/promise');
require('dotenv').config();
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
/**
* Initialize the database and create necessary tables
*
*/
async function initDB() {
try {
const connection = await pool.getConnection();
// Create users table if it doesn't exist
await connection.query(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
role VARCHAR(20) DEFAULT 'user',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`);
// ajoute une autre table si necessaire
// add a default admin user if none exists
const [rows] = await connection.query(`SELECT COUNT(*) as count FROM users`);
if (rows[0].count === 0) {
const bcrypt = require('bcryptjs');
const hashedPassword = await bcrypt.hash('admin123', 10);
await connection.query(
'INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
['admin', hashedPassword, 'admin']
);
console.log('✅ Default admin user created: admin / admin123');
}
connection.release();
console.log('✅ Database initialized');
} catch (err) {
console.error('❌ Failed to initialize database:', err.message);
}
}
module.exports = {
pool,
initDB,
};