🏆 Projet Final — Blog API REST

Full-stack Node.js avec auth JWT, CRUD complet, commentaires, pagination et sécurité production. Met en pratique tous les modules N01–N11 de la formation.

Node.js Express JWT bcryptjs helmet cors rate-limit dotenv

Fonctionnalités

🔑

Auth JWT

Register, Login, tokens signés, middleware verifyToken

📝

Articles CRUD

Création, lecture, mise à jour, suppression avec contrôle d'accès auteur/admin

💬

Commentaires

Commentaires imbriqués sous articles, suppression par auteur

📄

Pagination

?page= & ?limit= sur toutes les listes

🛡️

Sécurité

helmet, cors, rate-limit, dotenv, error handler production

🗄️

Persistance JSON

Classe JsonDB — données dans data/*.json survivent aux redémarrages

Architecture

blog-api/
├── server.js                  ← Point d'entrée (middleware + montage routes)
├── .env.example               ← Template variables d'environnement
├── package.json
│
├── routes/                    ← Définitions des routes par ressource
│   ├── auth.js                ← POST /auth/register, POST /auth/login
│   ├── articles.js            ← CRUD /articles
│   ├── users.js               ← GET /users/me, PATCH /users/me, GET /users/:id
│   └── comments.js            ← GET/POST/DELETE /articles/:id/comments
│
├── middleware/                ← Middlewares réutilisables
│   ├── auth.js                ← verifyToken (JWT)
│   └── validation.js          ← validateArticle, validateComment
│
├── lib/                       ← Utilitaires
│   └── db.js                  ← Classe JsonDB (persistance)
│
└── data/                      ← Fichiers de données JSON
    ├── users.json
    ├── articles.json
    └── comments.json

server.js → routes/ → middleware/ → lib/db.js → data/*.json

Endpoints API

Méthode URL Auth Description
AUTHENTIFICATION
POST /auth/register Créer un compte (username, email, password)
POST /auth/login Se connecter → retourne token JWT
ARTICLES
GET /articles Lister tous les articles (?page= &limit= &auteur=)
GET /articles/:id Récupérer un article
POST /articles 🔒 Créer un article (titre, contenu requis)
PUT /articles/:id 🔒 Modifier un article (auteur ou admin)
DELETE /articles/:id 🔒 Supprimer un article (auteur ou admin)
COMMENTAIRES
GET /articles/:id/comments Commentaires d'un article
POST /articles/:id/comments 🔒 Commenter un article (texte requis)
DELETE /articles/:id/comments/:cid 🔒 Supprimer son commentaire
UTILISATEURS
GET /users/me 🔒 Mon profil complet
PATCH /users/me 🔒 Modifier mon username
GET /users/:id Profil public d'un utilisateur
UTILITAIRE
GET /health Status du serveur (uptime, env)

🔒 = Requires Authorization: Bearer <token> header

Démarrage rapide

# 1. Installer les dépendances
npm install

# 2. Configurer l'environnement
cp .env.example .env
# Éditez .env et changez JWT_SECRET en production !

# 3. Lancer le serveur
node server.js
# → 🟢 Blog API — http://localhost:3000

# 4. Vérifier
curl http://localhost:3000/health

Exemples curl

1. S'inscrire

curl -X POST http://localhost:3000/auth/register \
  -H "Content-Type: application/json" \
  -d '{"username":"alice","email":"alice@example.com","password":"secret123"}'
# → { success: true, data: { user: {...}, token: "eyJhbG..." } }

2. Se connecter et récupérer le token

curl -X POST http://localhost:3000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"alice@example.com","password":"secret123"}'
# Copiez le token pour les appels suivants

3. Créer un article (avec token)

TOKEN="eyJhbGc..."

curl -X POST http://localhost:3000/articles \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"titre":"Node.js en pratique","contenu":"Un article complet sur Node.js et Express..."}'

4. Lister les articles (public)

curl "http://localhost:3000/articles?page=1&limit=5"

5. Commenter un article

curl -X POST http://localhost:3000/articles/1/comments \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"texte":"Excellent article !"}'

Technologies utilisées

PaquetRôle
expressFramework HTTP
jsonwebtokenCréation/vérification JWT
bcryptjsHachage mots de passe
helmetEn-têtes HTTP sécurisés
PaquetRôle
corsCross-origin resource sharing
express-rate-limitProtection DDoS
dotenvVariables d'environnement
morganLogger HTTP (dev)
← Accueil Formation 📚 Cheatsheet →