|
|
|
@ -8,4 +8,50 @@ const pool = mysql.createPool({ |
|
|
|
database: process.env.DB_NAME, |
|
|
|
}); |
|
|
|
|
|
|
|
module.exports = pool; |
|
|
|
/** |
|
|
|
* 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, |
|
|
|
}; |