Part of series: MongoDB Roadmap
Mini Project: Secure Notes App
Welcome to the Week 5 Finale! π
We have learned:
- Schema Validation
- Authentication & RBAC
- Environment Management
- Backups
Now, letβs build a Secure Notes App backend.
1. Requirements
- Users must have valid data (Schema Validation).
- The
Notecontent must be Encrypted in the database (Client-Side Encryption logic). - The database user must have least-privilege access.
2. Schema Validation (The Rules)
db.createCollection("notes", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["owner", "title", "content", "isPrivate"],
properties: {
title: {
bsonType: "string",
maxLength: 100,
description: "Title is required and limited to 100 chars"
},
isPrivate: {
bsonType: "bool"
}
}
}
}
})
3. Application Side Encryption
We will use the crypto module in Node.js to encrypt the note content before it hits the database. Even if the DB Admin reads the notes collection, they will see garbage.
const crypto = require('crypto');
const algorithm = 'aes-256-ctr';
const secretKey = process.env.SECRET_KEY; // Never hardcode!
const encrypt = (text) => {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return {
iv: iv.toString('hex'),
content: encrypted.toString('hex')
};
};
// Saving to DB
const newNote = new Note({
owner: req.user._id,
title: "Secret Plans",
content: encrypt("Take over the world at dawn").content, // Encrypted!
isPrivate: true
});
await newNote.save();
4. Deployment Check
Before going live:
- Network: Is IP Whitelisting on?
- User: Is the app using a
readWriteuser, NOTroot? - Validation: Are schemas enforced?
- SSL: Is TLS/SSL enabled? (Default in Atlas).
5. Week 5 Wrap Up
Your database is now a Fortress. π° It validates data, rejects unauthorized users, and survives logical disasters.
Next Week: Week 6 - Scaling! π We reach the final frontier: Sharding, massive scale, and clustering.
Stay safe! π‘οΈ