mirror of
https://github.com/R0m1k3/noteflow.git
synced 2026-10-20 13:48:20 +02:00
Création complète de l'application NoteFlow - Notes & Todo List
Application web Dockerisée moderne avec: - Backend Node.js + Express + SQLite - Frontend HTML/CSS/JavaScript vanilla - Authentification JWT + bcrypt - Gestion des notes avec images et todos intégrés - Sidebar todos globaux avec filtres - Interface utilisateur fluide avec animations CSS - Administration des utilisateurs - Sécurité production-ready (Helmet, rate limiting, validation) - Configuration Docker complète - Documentation README détaillée Stack technique: - Node.js 20 Alpine - SQLite3 avec indexes optimisés - Multer pour upload d'images - Winston pour logging - Express-validator pour validation - Architecture modulaire (routes, middleware, config) Fonctionnalités: - Notes: CRUD complet, recherche, images, todos intégrés - Todos globaux: création, toggle, filtres, suppression - Auth: JWT 24h, bcrypt 12 rounds - Admin: gestion utilisateurs complète - UI: masonry grid, modal animations, responsive Configuration Docker: - Healthcheck intégré - Volumes persistants pour data et uploads - Network nginx_default pour reverse proxy - Variables d'environnement configurables Prêt pour déploiement avec: docker-compose up -d
This commit is contained in:
22 files changed
+3414
-589
No files matched your search
+149
-93
@@ -1,119 +1,175 @@
|
||||
// Configuration et initialisation de la base de données SQLite
|
||||
const sqlite3 = require('sqlite3').verbose();
|
||||
const path = require('path');
|
||||
const bcrypt = require('bcrypt');
|
||||
const winston = require('winston');
|
||||
const fs = require('fs');
|
||||
const logger = require('./logger');
|
||||
|
||||
// Ensure data directory exists
|
||||
const dataDir = path.resolve(__dirname, '../data');
|
||||
if (!fs.existsSync(dataDir)) {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
const DB_PATH = process.env.DB_PATH || path.join(__dirname, '../data/notes.db');
|
||||
|
||||
// Configure logger
|
||||
const logger = winston.createLogger({
|
||||
level: 'info',
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.json()
|
||||
),
|
||||
transports: [
|
||||
new winston.transports.File({ filename: path.join(dataDir, 'app.log') }),
|
||||
new winston.transports.Console()
|
||||
]
|
||||
// Créer une connexion à la base de données
|
||||
const db = new sqlite3.Database(DB_PATH, (err) => {
|
||||
if (err) {
|
||||
logger.error('Erreur lors de la connexion à la base de données:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
logger.info(`Base de données connectée: ${DB_PATH}`);
|
||||
});
|
||||
|
||||
const dbPath = path.join(dataDir, 'notes.db');
|
||||
logger.info(`Using database at: ${dbPath}`);
|
||||
// Activer les clés étrangères
|
||||
db.run('PRAGMA foreign_keys = ON');
|
||||
|
||||
// Create database connection
|
||||
const db = new sqlite3.Database(dbPath, (err) => {
|
||||
if (err) {
|
||||
logger.error('Database connection error:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
logger.info('Connected to SQLite database');
|
||||
initializeDatabase();
|
||||
});
|
||||
|
||||
// Initialize database schema
|
||||
function initializeDatabase() {
|
||||
db.serialize(() => {
|
||||
// Create users table
|
||||
/**
|
||||
* Initialiser la base de données avec les tables nécessaires
|
||||
*/
|
||||
function initDatabase() {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.serialize(async () => {
|
||||
try {
|
||||
// Table users
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin BOOLEAN DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
|
||||
// Create notes table
|
||||
// Table notes
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS notes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
content TEXT,
|
||||
archived INTEGER DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
)
|
||||
CREATE TABLE IF NOT EXISTS notes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
content TEXT,
|
||||
image_filename TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)
|
||||
`);
|
||||
|
||||
// Create todos table
|
||||
// Table note_todos (todos dans les notes)
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS todos (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
note_id INTEGER NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
completed INTEGER DEFAULT 0,
|
||||
position INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (note_id) REFERENCES notes (id) ON DELETE CASCADE
|
||||
)
|
||||
CREATE TABLE IF NOT EXISTS note_todos (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
note_id INTEGER NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
completed BOOLEAN DEFAULT 0,
|
||||
position INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (note_id) REFERENCES notes(id) ON DELETE CASCADE
|
||||
)
|
||||
`);
|
||||
|
||||
// Create images table
|
||||
// Table global_todos (sidebar permanente)
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS images (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
note_id INTEGER NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (note_id) REFERENCES notes (id) ON DELETE CASCADE
|
||||
)
|
||||
CREATE TABLE IF NOT EXISTS global_todos (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
completed BOOLEAN DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)
|
||||
`);
|
||||
|
||||
// Check if admin user exists, create if not
|
||||
db.get('SELECT * FROM users WHERE username = ?', ['admin'], async (err, user) => {
|
||||
if (err) {
|
||||
logger.error('Error checking admin user:', err);
|
||||
return;
|
||||
}
|
||||
// Créer les index pour la performance
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_notes_user ON notes(user_id)');
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_note_todos ON note_todos(note_id)');
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_global_todos_user ON global_todos(user_id)');
|
||||
|
||||
if (!user) {
|
||||
try {
|
||||
const hash = await bcrypt.hash('admin', 10);
|
||||
db.run(
|
||||
'INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, ?)',
|
||||
['admin', hash, 1],
|
||||
(err) => {
|
||||
if (err) {
|
||||
logger.error('Error creating admin user:', err);
|
||||
return;
|
||||
}
|
||||
logger.info('Admin user created successfully');
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
logger.error('Error hashing admin password:', err);
|
||||
logger.info('✓ Tables de base de données créées avec succès');
|
||||
|
||||
// Créer l'utilisateur admin par défaut si la table est vide
|
||||
db.get('SELECT COUNT(*) as count FROM users', async (err, row) => {
|
||||
if (err) {
|
||||
logger.error('Erreur lors de la vérification des utilisateurs:', err);
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
if (row.count === 0) {
|
||||
// Créer l'utilisateur admin par défaut
|
||||
const defaultPassword = 'admin';
|
||||
const passwordHash = await bcrypt.hash(defaultPassword, 12);
|
||||
|
||||
db.run(
|
||||
'INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, ?)',
|
||||
['admin', passwordHash, 1],
|
||||
(err) => {
|
||||
if (err) {
|
||||
logger.error('Erreur lors de la création de l\'utilisateur admin:', err);
|
||||
reject(err);
|
||||
} else {
|
||||
logger.info('✓ Utilisateur admin créé (username: admin, password: admin)');
|
||||
logger.warn('⚠️ IMPORTANT: Changez le mot de passe admin en production!');
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
} else {
|
||||
logger.info('✓ Base de données déjà initialisée');
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Erreur lors de l\'initialisation de la base de données:', error);
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { db, logger };
|
||||
/**
|
||||
* Exécuter une requête avec promesse
|
||||
*/
|
||||
function runQuery(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(sql, params, function(err) {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve({ id: this.lastID, changes: this.changes });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupérer une seule ligne
|
||||
*/
|
||||
function getOne(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.get(sql, params, (err, row) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(row);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupérer toutes les lignes
|
||||
*/
|
||||
function getAll(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(sql, params, (err, rows) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(rows);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
db,
|
||||
initDatabase,
|
||||
runQuery,
|
||||
getOne,
|
||||
getAll
|
||||
};
|
||||
Reference in new issue
Block a user