Skip to content

surajthedev/Scalable-REST-API-with-Authentication

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

⚑ TaskFlow API

A production-ready REST API with JWT Authentication, Role-Based Access Control, and a React frontend β€” built for the PrimeTrade Backend Developer Intern assignment.

Node.js Express MongoDB React JWT Swagger


πŸ“‹ Table of Contents


✨ Features

Backend

  • πŸ” JWT Authentication β€” Access + Refresh token pair
  • πŸ‘₯ Role-Based Access Control β€” user and admin roles
  • βœ… Full CRUD β€” Tasks with filters, search, pagination, sorting
  • πŸ›‘οΈ Security β€” bcrypt hashing, helmet, rate limiting, NoSQL injection prevention, input sanitization
  • πŸ“„ Swagger Docs β€” Auto-generated interactive API docs at /api-docs
  • πŸ“Š Admin Dashboard β€” Manage users, view system stats
  • πŸ”’ Account Locking β€” Auto-lock after 5 failed login attempts
  • πŸ“ Logging β€” Winston logger with file + console output
  • ⚑ API Versioning β€” /api/v1/...

Frontend

  • βš›οΈ React 18 + Vite β€” Fast modern frontend
  • 🎨 Tailwind CSS β€” Dark theme, responsive design
  • πŸ”„ Auto token refresh β€” Axios interceptor silently refreshes expired tokens
  • πŸ“Š Dashboard β€” Task stats, priority breakdown, recent tasks
  • πŸ“ Task Manager β€” Full CRUD with modal forms, filters, search, pagination
  • πŸ›‘οΈ Admin Panel β€” User management, role toggle, activate/deactivate
  • βœ… Client-side validation β€” Real-time form feedback

πŸ›  Tech Stack

Layer Technology
Runtime Node.js 20
Framework Express 4
Database MongoDB + Mongoose
Auth JWT (jsonwebtoken) + bcryptjs
Validation express-validator
Security helmet, express-rate-limit, mongo-sanitize
Logging Winston
API Docs Swagger (swagger-jsdoc + swagger-ui-express)
Frontend React 18 + Vite + Tailwind CSS
HTTP Client Axios (with interceptors)
Deployment Docker + Docker Compose

πŸ“ Project Structure

taskflow-api/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ app.js                  # Express entry point
β”‚   β”‚   β”œβ”€β”€ seed.js                 # Demo data seeder
β”‚   β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”‚   β”œβ”€β”€ database.js         # MongoDB connection
β”‚   β”‚   β”‚   └── swagger.js          # Swagger spec config
β”‚   β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.controller.js  # Register, login, refresh, logout
β”‚   β”‚   β”‚   β”œβ”€β”€ task.controller.js  # CRUD + stats for tasks
β”‚   β”‚   β”‚   └── admin.controller.js # User management, dashboard
β”‚   β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.js             # JWT protect + restrictTo
β”‚   β”‚   β”‚   β”œβ”€β”€ errorHandler.js     # Global error handler
β”‚   β”‚   β”‚   └── validate.js         # express-validator runner
β”‚   β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”‚   β”œβ”€β”€ User.js             # User schema + methods
β”‚   β”‚   β”‚   └── Task.js             # Task schema + hooks
β”‚   β”‚   β”œβ”€β”€ routes/v1/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth.routes.js      # /api/v1/auth/*
β”‚   β”‚   β”‚   β”œβ”€β”€ task.routes.js      # /api/v1/tasks/*
β”‚   β”‚   β”‚   β”œβ”€β”€ user.routes.js      # /api/v1/users/*
β”‚   β”‚   β”‚   └── admin.routes.js     # /api/v1/admin/*
β”‚   β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”‚   β”œβ”€β”€ jwt.js              # Token generation/verification
β”‚   β”‚   β”‚   β”œβ”€β”€ logger.js           # Winston logger
β”‚   β”‚   β”‚   └── apiResponse.js      # Standardized response helpers
β”‚   β”‚   └── validators/
β”‚   β”‚       β”œβ”€β”€ auth.validator.js   # Auth input rules
β”‚   β”‚       └── task.validator.js   # Task input rules
β”‚   β”œβ”€β”€ logs/                       # Log files (gitignored)
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ package.json
β”‚   └── .env.example
β”‚
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ App.jsx                 # Router + protected routes
β”‚   β”‚   β”œβ”€β”€ main.jsx
β”‚   β”‚   β”œβ”€β”€ index.css               # Tailwind + custom classes
β”‚   β”‚   β”œβ”€β”€ context/
β”‚   β”‚   β”‚   └── AuthContext.jsx     # Global auth state
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   └── api.js              # Axios instance + all API calls
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   └── Layout.jsx          # Sidebar navigation
β”‚   β”‚   └── pages/
β”‚   β”‚       β”œβ”€β”€ LoginPage.jsx
β”‚   β”‚       β”œβ”€β”€ RegisterPage.jsx
β”‚   β”‚       β”œβ”€β”€ DashboardPage.jsx
β”‚   β”‚       β”œβ”€β”€ TasksPage.jsx       # Full CRUD UI
β”‚   β”‚       └── AdminPage.jsx       # Admin user management
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ nginx.conf
β”‚   └── package.json
β”‚
β”œβ”€β”€ docker-compose.yml
└── README.md

πŸš€ Quick Start

Prerequisites

1. Clone the repository

git clone https://github.com/YOUR_USERNAME/taskflow-api.git
cd taskflow-api

2. Setup Backend

cd backend

# Install dependencies
npm install

# Configure environment
cp .env.example .env
# Edit .env and set your MONGODB_URI and JWT secrets

# Seed demo data (optional)
node src/seed.js

# Start development server
npm run dev

Backend runs at: http://localhost:5000 API Docs at: http://localhost:5000/api-docs

3. Setup Frontend

cd ../frontend

# Install dependencies
npm install

# Start development server
npm run dev

Frontend runs at: http://localhost:3000

4. Demo Credentials (after seeding)

Role Email Password
Admin admin@demo.com Admin@1234
User user@demo.com Demo@1234
User jane@demo.com Demo@1234

πŸ“š API Documentation

Interactive Swagger docs are available at: http://localhost:5000/api-docs

Auth Endpoints

Method Endpoint Access Description
POST /api/v1/auth/register Public Register new user
POST /api/v1/auth/login Public Login & get tokens
POST /api/v1/auth/refresh Public Refresh access token
POST /api/v1/auth/logout Private Invalidate refresh token
GET /api/v1/auth/me Private Get current user
PUT /api/v1/auth/change-password Private Change password

Task Endpoints

Method Endpoint Access Description
GET /api/v1/tasks Private Get tasks (filter/page)
POST /api/v1/tasks Private Create task
GET /api/v1/tasks/stats Private Task statistics
GET /api/v1/tasks/:id Private Get single task
PUT /api/v1/tasks/:id Private Update task
DELETE /api/v1/tasks/:id Private Delete task

Admin Endpoints

Method Endpoint Access Description
GET /api/v1/admin/dashboard Admin System stats
GET /api/v1/admin/users Admin All users (paginated)
GET /api/v1/admin/users/:id Admin User by ID
PATCH /api/v1/admin/users/:id/role Admin Change user role
PATCH /api/v1/admin/users/:id/toggle-status Admin Activate/deactivate
DELETE /api/v1/admin/users/:id Admin Delete user + tasks
GET /api/v1/admin/tasks Admin All tasks in system

Query Parameters (GET /api/v1/tasks)

Param Type Values Description
page number 1+ Page number
limit number 1–50 Items per page
status string todo, in-progress, completed Filter status
priority string low, medium, high Filter priority
sortBy string createdAt, dueDate, priority, title Sort field
order string asc, desc Sort direction
search string any Search title/description

Response Format

All responses follow this standard shape:

{
  "success": true,
  "message": "Human readable message",
  "data": { ... },
  "meta": {
    "total": 42,
    "page": 1,
    "limit": 10,
    "totalPages": 5,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}

Error responses:

{
  "success": false,
  "message": "Validation failed",
  "errors": [
    { "field": "email", "message": "Valid email is required" }
  ]
}

βš™οΈ Environment Variables

# Server
PORT=5000
NODE_ENV=development

# MongoDB
MONGODB_URI=mongodb://localhost:27017/taskflow

# JWT (use long random strings in production)
JWT_SECRET=your_jwt_secret_min_32_characters
JWT_EXPIRES_IN=7d
JWT_REFRESH_SECRET=your_refresh_secret_min_32_characters
JWT_REFRESH_EXPIRES_IN=30d

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000   # 15 minutes
RATE_LIMIT_MAX=100            # max requests per window

# CORS
FRONTEND_URL=http://localhost:3000

πŸ—„οΈ Database Schema

User Collection

{
  name:          String,     // 2–50 chars
  email:         String,     // unique, indexed
  password:      String,     // bcrypt hashed, hidden from output
  role:          String,     // 'user' | 'admin'
  isActive:      Boolean,    // default: true
  refreshToken:  String,     // stored for refresh validation
  lastLogin:     Date,
  loginAttempts: Number,     // for brute-force protection
  lockUntil:     Date,       // account lock expiry
  createdAt:     Date,
  updatedAt:     Date
}

Indexes: { email: 1 }, { role: 1 }

Task Collection

{
  title:       String,     // 3–100 chars, required
  description: String,     // max 1000 chars
  status:      String,     // 'todo' | 'in-progress' | 'completed'
  priority:    String,     // 'low' | 'medium' | 'high'
  dueDate:     Date,       // must be future date
  tags:        [String],   // max 10 tags
  owner:       ObjectId,   // ref: User
  completedAt: Date,       // auto-set when status β†’ completed
  createdAt:   Date,
  updatedAt:   Date
}

Indexes: { owner: 1, status: 1 }, { owner: 1, priority: 1 }, { owner: 1, createdAt: -1 }


πŸ”’ Security Practices

Practice Implementation
Password hashing bcrypt with salt rounds = 12
JWT security Short-lived access tokens (7d) + long-lived refresh (30d)
Refresh token storage Server-side validation + rotation on each refresh
Account locking Auto-lock after 5 failed login attempts (2 hours)
Rate limiting 100 req/15min global, 10 req/15min on auth routes
Input sanitization express-mongo-sanitize prevents NoSQL injection
Input validation express-validator on all request bodies
HTTP security headers helmet sets X-XSS-Protection, HSTS, CSP, etc.
CORS Restricted to configured frontend origin
Payload limit JSON body limited to 10kb
Password never returned .select('-password') on all user queries
Principle of least privilege Role checks on every protected route

πŸ“ˆ Scalability Notes

Current Architecture

The app is structured for easy horizontal scaling. Each layer (API, DB) is independent and stateless (JWT is stateless by design).

Scaling Strategies

1. Horizontal Scaling (Load Balancing)

                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    Users ──────▢   β”‚   Load Balancer  β”‚  (Nginx / AWS ALB)
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”
          β”‚ API Pod β”‚  β”‚ API Pod β”‚  β”‚ API Pod β”‚   (Docker / K8s)
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                             β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚  MongoDB Atlas  β”‚  (Replica Set)
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

2. Caching (Redis)

  • Cache task list responses per user (TTL: 60s)
  • Cache user profile lookups (TTL: 5min)
  • Store refresh token allowlist in Redis for fast revocation

3. Microservices Migration Path The modular structure makes service extraction easy:

  • auth-service β†’ handles login, token management
  • task-service β†’ handles CRUD operations
  • notification-service β†’ email/push for due dates
  • admin-service β†’ analytics and management

4. Database Optimisation

  • All queries use compound indexes (owner + status, owner + priority)
  • Pagination prevents large data fetches
  • MongoDB Atlas supports auto-scaling and global clusters

5. API Gateway Add an API Gateway (Kong / AWS API Gateway) in front for:

  • Centralised rate limiting
  • SSL termination
  • Request routing to microservices

6. CI/CD Pipeline

Push to main β†’ GitHub Actions β†’ Run tests β†’ Build Docker images β†’ Deploy to K8s

🐳 Docker Deployment

# Build and start all services
docker-compose up --build

# Run in background
docker-compose up -d

# Seed demo data inside container
docker-compose exec backend node src/seed.js

# View logs
docker-compose logs -f backend

# Stop
docker-compose down

Services:

  • Frontend: http://localhost:3000
  • Backend API: http://localhost:5000
  • API Docs: http://localhost:5000/api-docs
  • MongoDB: mongodb://localhost:27017

πŸ§ͺ Running Tests

cd backend
npm test

πŸ“ Log Files

backend/logs/
β”œβ”€β”€ combined.log    # All log levels
└── error.log       # Error level only

πŸ‘€ Author

Built for the PrimeTrade Backend Developer Intern assignment.


πŸ“„ License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages