A complete Two-Factor Authentication implementation using Node.js, Express, and MongoDB.
- Node.js v18+
- MongoDB v6.0+
- npm/yarn
- Google Authenticator or similar TOTP app
- Node.js & Express
- MongoDB with Prisma ORM
- TypeScript
- otplib for TOTP implementation
- QRCode for QR code generation
backend/
├── src/
│ ├── controllers/
│ │ └── auth.controller.ts
│ ├── services/
│ │ └── auth.service.ts
│ ├── prisma/
│ │ ├── schema.prisma
│ │ └── index.ts
│ └── server.ts
├── package.json
└── .env
- Install dependencies:
npm install- Create environment file (.env):
DATABASE_URL="mongodb://localhost:27017/2fa-demo?replicaSet=rs0"
PORT=5000
- Generate Prisma client:
npx prisma generate| Method | Endpoint | Description |
|---|---|---|
| POST | /api/auth/register |
Register new user |
| POST | /api/auth/login |
User login |
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/2fa/setup |
Setup 2FA |
| POST | /api/2fa/verify |
Verify and enable 2FA |
| POST | /api/2fa/validate |
Validate 2FA token |
| POST | /api/2fa/disable |
Disable 2FA |
curl -X POST http://localhost:5000/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "password123"
}'curl -X POST http://localhost:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "password123"
}'curl -X POST http://localhost:5000/api/2fa/setup \
-H "Content-Type: application/json" \
-d '{
"userId": "your_user_id"
}'curl -X POST http://localhost:5000/api/2fa/verify \
-H "Content-Type: application/json" \
-d '{
"userId": "your_user_id",
"token": "123456"
}'Start the server:
npm run dev- Use environment variables for sensitive data
- Implement rate limiting for API endpoints
- Sanitize user inputs
- Use secure session management
- Handle errors properly
- Store hashed passwords only
MIT License