Skip to content

meherunnesaenta/Micro-task-platform-server

Repository files navigation

🎯 Micro-Task Platform - Backend Server

A comprehensive MERN stack backend for a micro-tasking and earning platform where workers complete small tasks for payment and buyers create tasks for workers.

🌟 Features

Authentication & Authorization

  • βœ… User registration with email validation & password hashing
  • βœ… JWT-based login system
  • βœ… Role-based access control (Worker, Buyer, Admin)
  • βœ… Secure token storage
  • βœ… Profile management

Worker Features

  • βœ… View available tasks with pagination
  • βœ… Submit task work with details
  • βœ… Track submission status (Pending/Approved/Rejected)
  • βœ… View earnings from approved submissions
  • βœ… Request withdrawals (with 20 coins = $1 rate)
  • βœ… Minimum withdrawal requirement (200 coins = $10)
  • βœ… Withdrawal history tracking

Buyer Features

  • βœ… Create tasks with detailed requirements
  • βœ… View task submissions from workers
  • βœ… Approve/Reject submissions
  • βœ… Automatic coin deduction on task creation
  • βœ… Purchase coins using 4 different packages
  • βœ… Payment history tracking
  • βœ… Update and delete tasks
  • βœ… Refund coins for deleted uncompleted tasks

Admin Features

  • βœ… Dashboard with platform statistics
  • βœ… User management (view, update roles, delete)
  • βœ… Task management (view, delete)
  • βœ… Withdrawal request management
  • βœ… Approve/Reject withdrawals

Notification System

  • βœ… Real-time notifications for all major actions
  • βœ… Notifications for task submissions, approvals, rejections
  • βœ… Withdrawal notifications
  • βœ… Read/Unread status tracking
  • βœ… Notification history

Business Logic

  • βœ… Intelligent coin management system
  • βœ… Worker receives 10 coins on registration
  • βœ… Buyer receives 50 coins on registration
  • βœ… Task cost calculation: required_workers Γ— payable_amount
  • βœ… Automatic coin updates on transactions
  • βœ… Withdrawal percentage (Platform: 50%, Workers: 50%)

πŸš€ Quick Start

1. Prerequisites

  • Node.js (v14+)
  • npm or yarn
  • MongoDB Atlas account (free tier available)

2. Installation

# Clone repository
cd server

# Install dependencies
npm install

# Create .env file
cp .env.example .env
# Edit .env with your MongoDB URI and JWT_SECRET

# Start development server
npm run dev

3. Verify Server

curl http://localhost:5000/api/health

Response:

{
  "status": "OK",
  "message": "Server is running"
}

πŸ“š Documentation

Document Purpose
QUICK_START.md 5-minute setup guide with testing examples
API_DOCUMENTATION.md Complete API reference with all endpoints
BACKEND_SETUP.md Detailed installation & configuration
ENV_VARIABLES.md Environment variable reference

πŸ—οΈ Project Structure

server/
β”œβ”€β”€ index.js                          # Main application entry point
β”œβ”€β”€ package.json                      # Dependencies & scripts
β”œβ”€β”€ .env                              # Environment variables (create this)
β”œβ”€β”€ .env.example                      # Example env file
β”‚
β”œβ”€β”€ middleware/
β”‚   └── auth.js                       # JWT authentication & role authorization
β”‚
β”œβ”€β”€ models/                           # Database schemas
β”‚   β”œβ”€β”€ User.js                       # User schema
β”‚   β”œβ”€β”€ Task.js                       # Task schema
β”‚   β”œβ”€β”€ Submission.js                 # Submission schema
β”‚   β”œβ”€β”€ Withdrawal.js                 # Withdrawal schema
β”‚   β”œβ”€β”€ Payment.js                    # Payment schema
β”‚   └── Notification.js               # Notification schema
β”‚
β”œβ”€β”€ routes/                           # API endpoints
β”‚   β”œβ”€β”€ auth.js                       # /api/auth (register, login, profile)
β”‚   β”œβ”€β”€ tasks.js                      # /api/tasks (CRUD, viewing)
β”‚   β”œβ”€β”€ submissions.js                # /api/submissions (submit, review)
β”‚   β”œβ”€β”€ withdrawals.js                # /api/withdrawals (request, manage)
β”‚   β”œβ”€β”€ payments.js                   # /api/payments (purchase coins)
β”‚   β”œβ”€β”€ notifications.js              # /api/notifications (manage)
β”‚   └── admin.js                      # /api/admin (statistics, management)
β”‚
└── docs/
    β”œβ”€β”€ QUICK_START.md                # Quick start guide
    β”œβ”€β”€ API_DOCUMENTATION.md          # Full API docs
    β”œβ”€β”€ BACKEND_SETUP.md              # Setup guide
    └── ENV_VARIABLES.md              # Env variables reference

πŸ“‹ API Endpoints

Authentication (/api/auth)

POST   /register              Register new user
POST   /login                 Login user
GET    /me                    Get current user profile
PUT    /profile               Update user profile

Tasks (/api/tasks)

GET    /                      Get all available tasks
GET    /:id                   Get task details
POST   /                      Create task (Buyer only)
PUT    /:id                   Update task (Buyer only)
DELETE /:id                   Delete task (Buyer only)
GET    /buyer/my-tasks        Get buyer's tasks
GET    /admin/top-workers     Get top 6 workers

Submissions (/api/submissions)

POST   /                      Submit task (Worker only)
GET    /worker/my-submissions Get worker's submissions
GET    /buyer/review          Get submissions to review (Buyer only)
PUT    /:id/approve           Approve submission (Buyer only)
PUT    /:id/reject            Reject submission (Buyer only)
GET    /worker/approved       Get approved submissions (Worker)

Withdrawals (/api/withdrawals)

POST   /                      Request withdrawal (Worker only)
GET    /worker/history        Get withdrawal history (Worker)
GET    /admin/pending         Get pending withdrawals (Admin only)
PUT    /:id/approve           Approve withdrawal (Admin only)
PUT    /:id/reject            Reject withdrawal (Admin only)

Payments (/api/payments)

GET    /packages              Get coin packages
POST   /create-payment        Create payment (Buyer only)
PUT    /confirm/:paymentId    Confirm payment (Buyer only)
POST   /dummy-payment         Dummy payment for testing
GET    /history               Get payment history (Buyer only)

Notifications (/api/notifications)

GET    /                      Get user notifications
GET    /unread/count          Get unread count
PUT    /:id/read              Mark as read
PUT    /read-all              Mark all as read
DELETE /:id                   Delete notification

Admin (/api/admin)

GET    /stats                 Get dashboard statistics
GET    /users                 Get all users
PUT    /users/:id/role        Update user role
DELETE /users/:id             Delete user
GET    /tasks                 Get all tasks
DELETE /tasks/:id             Delete task

πŸ’° Coin System

Registration Bonuses

  • Workers: 10 coins
  • Buyers: 50 coins

Coin Packages (Purchase)

  • 10 coins = $1
  • 150 coins = $10
  • 500 coins = $20
  • 1000 coins = $35

Withdrawal

  • 20 coins = $1
  • Minimum withdrawal: 200 coins = $10
  • Maximum: User's available balance

Business Model

  • Buy Rate: 10 coins = $1
  • Sell Rate: 20 coins = $1
  • Platform Margin: 50%

πŸ” Security Features

  • βœ… Password Hashing: bcryptjs with salt rounds
  • βœ… JWT Authentication: Secure token-based auth
  • βœ… Role-Based Access: Protect sensitive operations
  • βœ… Input Validation: Email format, password strength
  • βœ… Error Handling: Safe error messages without exposing internals
  • βœ… CORS Enabled: Configured for all origins
  • βœ… MongoDB Security: Connection string in environment variables

πŸ§ͺ Testing API

With Postman

  1. Import endpoints from API_DOCUMENTATION.md
  2. Create environment variables for token and URLs
  3. Set Authorization header: Bearer <token>

With cURL

# Register
curl -X POST http://localhost:5000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name":"John","email":"john@example.com","password":"Pass123","role":"worker"}'

# Login
curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"john@example.com","password":"Pass123"}'

# Get profile (with token)
curl -X GET http://localhost:5000/api/auth/me \
  -H "Authorization: Bearer <token>"

πŸ—„οΈ Database Collections

Users

  • Stores user profiles, roles, and available coins
  • Indexed by email for faster lookups
  • Password stored as bcrypt hash

Tasks

  • Task listings created by buyers
  • Tracks required workers and payable amount
  • Automatically manages status and worker count

Submissions

  • Worker task submissions for review
  • Tracks submission status and dates
  • Links worker to task and buyer

Withdrawals

  • Worker withdrawal requests
  • Tracks coin amount and dollar equivalent
  • Manages withdrawal status and payment method

Payments

  • Records all coin purchases
  • Tracks transaction IDs and payment status
  • Links purchases to buyer accounts

Notifications

  • System-generated notifications
  • Supports read/unread status
  • Soft delete through archiving

πŸ”„ Transaction Flow

Task Completion Flow

  1. Buyer creates task β†’ Coins deducted from buyer
  2. Worker submits β†’ Notification sent to buyer
  3. Buyer reviews β†’ Can approve or reject
  4. If approved β†’ Coins credited to worker, task worker count reduced
  5. If rejected β†’ Worker count increased, refund available workers

Withdrawal Flow

  1. Worker requests withdrawal β†’ Creates pending withdrawal
  2. Admin reviews β†’ Can approve or reject
  3. If approved β†’ Coins deducted, worker notified
  4. If rejected β†’ Coins remain, worker notified

Payment Flow

  1. Buyer selects package β†’ Payment created (pending)
  2. Payment confirmed β†’ Transaction ID stored
  3. Status updated β†’ Coins added to buyer account
  4. Notification sent β†’ Logged in payment history

βš™οΈ Environment Setup

MongoDB Atlas

  1. Create free account at mongodb.com/cloud/atlas
  2. Create cluster (M0 free tier)
  3. Create database user
  4. Whitelist IP address (0.0.0.0/0 for development)
  5. Get connection string
  6. Update MONGODB_URI in .env

JWT Secret

node -e "//(require('crypto').randomBytes(32).toString('hex'))"

Add result to JWT_SECRET in .env


πŸ“Š Coin Audit

Monitor coin flow with these queries:

// Total coins in system
db.users.aggregate([{ $group: { _id: null, total: { $sum: "$coins" } } }])

// Coins by role
db.users.aggregate([{ $group: { _id: "$role", count: { $sum: 1 }, totalCoins: { $sum: "$coins" } } }])

// Most paid tasks
db.tasks.find().sort({payable_amount: -1}).limit(10)

// Pending withdrawals
db.withdrawals.find({status: "pending"})

πŸš€ Deployment Checklist

  • Set NODE_ENV=production
  • Use strong JWT_SECRET (32+ chars)
  • Configure MongoDB IP whitelist
  • Enable HTTPS
  • Set specific CORS origins
  • Add rate limiting
  • Set up logging/monitoring
  • Enable database backups
  • Test all critical flows
  • Document admin credentials
  • Set up error alerts

🀝 Contributing

When adding new features:

  1. Follow existing code structure
  2. Add proper error handling
  3. Validate all inputs
  4. Add relevant notifications
  5. Update API documentation
  6. Test with multiple roles

πŸ“ž Support

If you encounter issues:

  1. Check QUICK_START.md for common problems
  2. Review API_DOCUMENTATION.md for endpoint details
  3. Check MongoDB connection in .env
  4. Verify role permissions
  5. Look at console error messages

πŸ“ License

This project is part of a job assessment for Junior MERN Stack Developer position.


🎯 Next Steps

  1. βœ… Backend setup complete
  2. ⏭️ Build React frontend
  3. ⏭️ Connect frontend to API
  4. ⏭️ Add Stripe payment integration
  5. ⏭️ Deploy to production

Last Updated: January 2024
Status: βœ… Production Ready for Assessment

About

Backend API for Micro Task Earning Platform. Handles authentication, tasks, submissions, payments, withdrawals. Built with Node.js, Express, MongoDB.

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors