A secure Node.js/Express backend API for plant disease detection with two-factor authentication (2FA) support.
# Install dependencies
npm install
# Set up environment variables
cp .env.example .env
# Start development server
npm run dev
# Build for production
npm run build
# Start production server
npm start- Architecture Overview
- Application Flow
- Authentication System
- API Endpoints
- Project Structure
- Environment Setup
- Security Features
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Client App βββββΆβ Express API βββββΆβ MongoDB β
β β β β β β
β - React/Vue/etc β β - Routes β β - User Data β
β - HTTP Requests β β - Controllers β β - Auth Info β
β - Cookie Auth β β - Services β β - 2FA Secrets β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
- Runtime: Node.js with TypeScript
- Framework: Express.js
- Database: MongoDB with Mongoose
- Authentication: JWT + 2FA (TOTP)
- Security: Helmet, CORS, bcrypt
- Logging: Winston
- Validation: Joi
graph TD
A[App Start] --> B[Load Environment Variables]
B --> C[Connect to MongoDB]
C --> D[Setup Middlewares]
D --> E[Register Routes]
E --> F[Start HTTP Server]
F --> G[Server Ready on Port]
C --> C1[Connection Success?]
C1 -->|No| C2[Log Error & Exit]
C1 -->|Yes| D
graph TD
A[Incoming Request] --> B[CORS Check]
B --> C[Security Headers]
C --> D[Parse JSON/Cookies]
D --> E[Route Matching]
E --> F{Protected Route?}
F -->|No| G[Controller Handler]
F -->|Yes| H[Auth Middleware]
H --> I{Valid Token?}
I -->|No| J[401 Unauthorized]
I -->|Yes| K[Validate Auth Stage]
K --> L{Correct Stage?}
L -->|No| J
L -->|Yes| G
G --> M[Service Layer]
M --> N[Database Operation]
N --> O[Response]
O --> P[Error Handling]
The app uses a two-stage authentication system:
graph LR
A[Login Request] --> B[Validate Credentials]
B --> C[Generate JWT with 'password' stage]
C --> D[Set Cookie with 5min expiry]
D --> E[Return 2FA Status]
graph LR
A[2FA Setup Request] --> B[Generate TOTP Secret]
B --> C[Create QR Code]
C --> D[Generate Recovery Codes]
D --> E[Return QR & Codes]
F[2FA Verify Request] --> G[Validate TOTP]
G --> H[Generate JWT with '2fa' stage]
H --> I[Set Cookie with 1day expiry]
sequenceDiagram
participant C as Client
participant A as API
participant DB as Database
participant Auth as Auth Service
Note over C,Auth: Registration Flow
C->>A: POST /api/v1/auth/register
A->>DB: Check if user exists
A->>Auth: Hash password
A->>DB: Create new user
A->>C: Success response
Note over C,Auth: Login Flow
C->>A: POST /api/v1/auth/login
A->>DB: Find user by email
A->>Auth: Compare passwords
A->>Auth: Generate JWT (stage: password)
A->>C: Set cookie + return 2FA status
Note over C,Auth: 2FA Setup (if not activated)
C->>A: POST /api/v1/auth/activate-2fa
A->>Auth: Generate TOTP secret
A->>Auth: Create QR code
A->>Auth: Generate recovery codes
A->>DB: Save secret & recovery codes
A->>C: Return QR code & recovery codes
Note over C,Auth: 2FA Verification
C->>A: POST /api/v1/auth/verify-2fa
A->>Auth: Validate TOTP token
A->>DB: Activate 2FA (if first time)
A->>Auth: Generate JWT (stage: 2fa)
A->>C: Set cookie with full access
Note over C,Auth: Protected Resource Access
C->>A: GET /api/v1/auth/userInfo
A->>Auth: Verify JWT & stage
A->>DB: Fetch user data
A->>C: Return user information
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/v1/auth/register |
Register new user |
POST |
/api/v1/auth/login |
Login with email/password |
| Method | Endpoint | Description | Auth Stage |
|---|---|---|---|
POST |
/api/v1/auth/activate-2fa |
Setup 2FA | password |
POST |
/api/v1/auth/verify-2fa |
Verify 2FA code | password |
| Method | Endpoint | Description | Auth Stage |
|---|---|---|---|
GET |
/api/v1/auth/userInfo |
Get user profile | password + 2fa |
PUT |
/api/v1/auth/logout |
Logout user | password + 2fa |
| Method | Endpoint | Description |
|---|---|---|
GET |
/ |
API status check |
GET |
/health |
Health check |
src/
βββ app.ts # Main application entry point
βββ config/
β βββ index.ts # Environment configuration
β βββ db.ts # Database connection
βββ controller/
β βββ auth.controller.ts # Request handlers
βββ services/
β βββ auth.service.ts # Business logic
βββ repositories/
β βββ user.repository.ts # Database operations
βββ middlewares/
β βββ auth.middleware.ts # Authentication middleware
β βββ error.middleware.ts # Error handling
βββ routes/
β βββ index.ts # Route aggregator
β βββ auth.routes.ts # Authentication routes
βββ models/ # Database schemas
βββ validators/ # Input validation
βββ helpers/ # Utility functions
βββ utils/ # Common utilities
βββ types/ # TypeScript type definitions
βββ interfaces/ # TypeScript interfaces
Create a .env file in the root directory:
# Server Configuration
NODE_ENV=development
PORT=5000
API_PREFIX=/api/v1
# Database
MONGODB_URI=mongodb://localhost:27017/plant-disease-db
# JWT Secrets
JWT_SECRET=your-super-secret-jwt-key
JWT_REFRESH_SECRET=your-super-secret-refresh-key
# Client Configuration
CLIENT_URL=http://localhost:3000
CORS_ORIGIN=http://localhost:3000
# Logging
LOG_LEVEL=info
- JWT Tokens: Secure token-based authentication
- Two-Factor Authentication: TOTP-based 2FA with QR codes
- Recovery Codes: Backup codes for 2FA recovery
- Password Hashing: bcrypt with salt rounds
- Cookie Security: HttpOnly, Secure, SameSite cookies
- Helmet: Security headers protection
- CORS: Cross-origin request protection
- Input Validation: Joi schema validation
- Rate Limiting: Built-in Express rate limiting
- Error Handling: Centralized error management
- Connection Security: Secure MongoDB connection
- Data Validation: Mongoose schema validation
- Sensitive Data: Excluded from responses by default
- App loads environment variables
- Connects to MongoDB database
- Sets up security middlewares (CORS, Helmet)
- Registers API routes
- Starts HTTP server
Request β Security Checks β Route Matching β Auth Check β Controller β Service β Database β Response
- Stage 1 (password): Basic login, limited access (5 min)
- Stage 2 (2fa): Full access after 2FA verification (1 day)
- All errors are caught and processed by error middleware
- Consistent error response format
- Detailed logging for debugging
Client Request β Controller (validation) β Service (business logic) β Repository (database) β Response
Handle HTTP requests, validate input, and coordinate responses.
Contain business logic, authentication, and data processing.
Manage database operations and data access patterns.
Process requests before they reach controllers (auth, validation, etc.).
Provide reusable functions for encryption, JWT, logging, etc.
This backend provides a solid foundation for secure user authentication with modern security practices. The two-stage authentication system ensures both security and user experience are optimized.