Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TrustScan Backend API

A production-ready backend system for product authentication and supply chain tracking using QR codes.

Features

  • User Authentication & Authorization: JWT-based authentication with role-based access control
  • User Roles: Users, Suppliers, Manufacturers, and Admins
  • Product Management: Register products with unique QR codes, track ownership
  • Supply Chain Tracking: Transfer product ownership, view complete history
  • Product Scanning: Scan products and maintain scan history
  • Security: Rate limiting, Helmet security headers, CORS configuration
  • Validation: Zod schema validation for all requests
  • Logging: Winston logger for debugging and monitoring
  • Email Notifications: Production-ready email service with SMTP

Tech Stack

  • Runtime: Node.js with TypeScript
  • Framework: Express.js
  • Database: MongoDB with Mongoose ODM
  • Authentication: JWT (jsonwebtoken)
  • Validation: Zod
  • Security: Helmet, express-rate-limit, bcryptjs
  • Email: Nodemailer
  • QR Codes: qrcode library
  • Logging: Winston

Project Structure

src/
├── config/
│   └── database.ts          # MongoDB connection setup
├── controllers/
│   ├── authController.ts    # Authentication logic
│   ├── userController.ts    # User management
│   ├── productController.ts # Product management
│   └── scanController.ts    # Scanning functionality
├── middleware/
│   ├── auth.ts             # Authentication & authorization
│   ├── validate.ts         # Request validation
│   └── errorHandler.ts     # Error handling
├── models/
│   ├── User.ts             # User schema
│   ├── Product.ts          # Product schema
│   └── Scan.ts             # Scan schema
├── routes/
│   ├── authRoutes.ts       # Auth endpoints
│   ├── userRoutes.ts       # User endpoints
│   ├── productRoutes.ts    # Product endpoints
│   └── scanRoutes.ts       # Scan endpoints
├── schemas/
│   └── validation.ts       # Zod validation schemas
├── services/
│   └── emailService.ts     # Email service
├── utils/
│   ├── logger.ts           # Winston logger
│   ├── jwt.ts              # JWT utilities
│   └── qrCode.ts           # QR code generation
└── server.ts               # Main application file

Installation

  1. Clone the repository:
git clone <repository-url>
cd trustscan-backend
  1. Install dependencies:
npm install
  1. Set up environment variables: Create a .env file in the root directory:
cp .env.example .env
  1. Configure environment variables (see .env.example for all options):
PORT=5000
MONGODB_URI=mongodb://localhost:27017/trustscan
JWT_SECRET=your_super_secret_jwt_key_min_32_chars
CLIENT_URL=http://localhost:3000

# Admin User (for initial setup)
ADMIN_NAME=Admin User
ADMIN_EMAIL=admin@trustscan.com
ADMIN_PASSWORD=Admin@123456

# Email Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password
  1. Create logs directory:
mkdir logs
  1. Create Initial Admin Account:
npm run seed:admin

This will create an admin account with the credentials from your .env file. The default credentials are:

⚠️ IMPORTANT: Change the admin password immediately after first login!

Running the Application

Development Mode

npm run dev

Production Mode

npm run build
npm start

Utility Scripts

# Create initial admin account
npm run seed:admin

# Change user role (interactive)
npm run change:role

Quick Start

See QUICKSTART.md for a 5-minute setup guide!

API Documentation

Base URL

http://localhost:5000/api

Authentication Endpoints

Register User

POST /api/auth/register
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "password123",
  "company": "Acme Corp",
  "phone": "+1234567890"
}

Login

POST /api/auth/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "password123"
}

Get Current User

GET /api/auth/me
Authorization: Bearer <token>

User Management (Admin Only)

Create Manufacturer

POST /api/users/manufacturer
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "name": "Tech Manufacturing Co",
  "email": "manufacturer@techco.com",
  "password": "secure123",
  "company": "Tech Manufacturing Co"
}

Get All Users

GET /api/users?page=1&limit=10&role=manufacturer
Authorization: Bearer <admin-token>

Deactivate User

DELETE /api/users/:id/deactivate
Authorization: Bearer <admin-token>

Product Management

Create Product (Manufacturer Only)

POST /api/products
Authorization: Bearer <manufacturer-token>
Content-Type: application/json

{
  "name": "Premium Smartphone X1",
  "description": "Latest flagship smartphone",
  "sku": "PHONE-X1-2024",
  "category": "Electronics",
  "price": 999.99,
  "weight": 0.2,
  "batchNumber": "BATCH-2024-001"
}

Get All Products

GET /api/products?page=1&limit=10&status=manufactured&category=Electronics
Authorization: Bearer <token>

Get Product by QR Code (Public)

GET /api/products/qr/:qrCode

Transfer Product Ownership

POST /api/products/:id/transfer
Authorization: Bearer <token>
Content-Type: application/json

{
  "newOwnerId": "user_id_here",
  "location": "Distribution Center",
  "notes": "Transfer to distributor"
}

Get Product History

GET /api/products/:id/history
Authorization: Bearer <token>

Scanning

Scan Product

POST /api/scans
Authorization: Bearer <token>
Content-Type: application/json

{
  "qrCode": "TS-1234567890-uuid",
  "location": {
    "latitude": 40.7128,
    "longitude": -74.0060,
    "address": "New York, NY"
  }
}

Get Scan History

GET /api/scans?page=1&limit=10
Authorization: Bearer <token>

Get Scan Statistics

GET /api/scans/stats
Authorization: Bearer <token>

User Roles & Permissions

User (Default)

  • Register and login
  • Scan products
  • View scan history
  • View product details

Supplier

  • All User permissions
  • Transfer product ownership
  • View owned products

Manufacturer

  • All Supplier permissions
  • Create products
  • Update own products
  • Deactivate own products
  • View product scans

Admin

  • All permissions
  • Create manufacturer accounts
  • View all users
  • Deactivate/activate users
  • View all products
  • Deactivate any product

Creating Admin Accounts

Initial Admin Setup

Use the seed script (recommended for first admin):

npm run seed:admin

Manual Admin Creation (Alternative Method)

If you need to manually promote a user to admin or create additional admins:

  1. Via MongoDB Shell:
// Connect to your MongoDB
mongosh trustscan

// Find the user and update their role
db.users.updateOne(
  { email: "user@example.com" },
  { $set: { role: "admin" } }
)
  1. Via MongoDB Compass:
  • Connect to your database
  • Navigate to the users collection
  • Find the user you want to promote
  • Edit the document and change role to "admin"
  • Save changes
  1. Programmatically (add this to a temporary script):
import User, { UserRole } from "./src/models/User";

const makeAdmin = async (email: string) => {
  const user = await User.findOneAndUpdate(
    { email },
    { role: UserRole.ADMIN },
    { new: true }
  );
  console.log("User promoted to admin:", user);
};

makeAdmin("user@example.com");

Best Practices for Admin Accounts

  • ✅ Use strong, unique passwords
  • ✅ Enable 2FA if implementing it
  • ✅ Limit number of admin accounts
  • ✅ Regularly audit admin activities
  • ✅ Use separate admin accounts (don't share)
  • ✅ Change default admin password immediately

Security Features

  1. JWT Authentication: Secure token-based authentication
  2. Password Hashing: bcrypt with salt rounds
  3. Rate Limiting: Prevents brute force attacks
  4. Helmet: Sets security headers
  5. CORS: Configured for specific origins
  6. Input Validation: Zod schema validation
  7. Error Handling: Comprehensive error middleware

Email Configuration

Gmail Setup

  1. Enable 2-factor authentication on your Gmail account
  2. Generate an App Password: Google Account → Security → 2-Step Verification → App Passwords
  3. Use the generated password in SMTP_PASS

Other SMTP Providers

Update the following in .env:

  • SMTP_HOST: Your SMTP host
  • SMTP_PORT: Usually 587 (TLS) or 465 (SSL)
  • SMTP_SECURE: true for 465, false for 587
  • SMTP_USER: Your email username
  • SMTP_PASS: Your email password

MongoDB Setup

Local MongoDB

# Install MongoDB
# Start MongoDB service
mongod

# Connection URI in .env
MONGODB_URI=mongodb://localhost:27017/trustscan

MongoDB Atlas (Cloud)

  1. Create a cluster at https://cloud.mongodb.com
  2. Get connection string
  3. Update .env:
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/trustscan?retryWrites=true&w=majority

Testing with Postman

  1. Import the postman_collection.json file into Postman
  2. Create an environment with variable base_url = http://localhost:5000
  3. Test endpoints in order:
    • Register/Login to get token
    • Token is automatically saved for subsequent requests
    • Test other endpoints

Error Handling

All errors return a consistent format:

{
  "success": false,
  "message": "Error message",
  "errors": [
    {
      "field": "email",
      "message": "Invalid email address"
    }
  ]
}

Logging

Logs are written to:

  • logs/error.log - Error level logs
  • logs/combined.log - All logs
  • Console (development mode)

Production Deployment

  1. Set NODE_ENV=production
  2. Use strong JWT_SECRET (minimum 32 characters)
  3. Configure proper MongoDB connection
  4. Set up SSL/TLS certificates
  5. Use environment variables for all secrets
  6. Configure proper CORS origins
  7. Set up monitoring and logging
  8. Use PM2 or similar for process management

License

MIT

Support

For issues and questions, please create an issue in the repository.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages