A production-ready backend system for product authentication and supply chain tracking using QR codes.
- 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
- 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
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
- Clone the repository:
git clone <repository-url>
cd trustscan-backend- Install dependencies:
npm install- Set up environment variables:
Create a
.envfile in the root directory:
cp .env.example .env- Configure environment variables (see
.env.examplefor 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- Create logs directory:
mkdir logs- Create Initial Admin Account:
npm run seed:adminThis will create an admin account with the credentials from your .env file. The default credentials are:
- Email: admin@trustscan.com
- Password: Admin@123456
npm run devnpm run build
npm start# Create initial admin account
npm run seed:admin
# Change user role (interactive)
npm run change:roleSee QUICKSTART.md for a 5-minute setup guide!
http://localhost:5000/api
POST /api/auth/register
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"password": "password123",
"company": "Acme Corp",
"phone": "+1234567890"
}POST /api/auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "password123"
}GET /api/auth/me
Authorization: Bearer <token>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 /api/users?page=1&limit=10&role=manufacturer
Authorization: Bearer <admin-token>DELETE /api/users/:id/deactivate
Authorization: Bearer <admin-token>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 /api/products?page=1&limit=10&status=manufactured&category=Electronics
Authorization: Bearer <token>GET /api/products/qr/:qrCodePOST /api/products/:id/transfer
Authorization: Bearer <token>
Content-Type: application/json
{
"newOwnerId": "user_id_here",
"location": "Distribution Center",
"notes": "Transfer to distributor"
}GET /api/products/:id/history
Authorization: Bearer <token>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 /api/scans?page=1&limit=10
Authorization: Bearer <token>GET /api/scans/stats
Authorization: Bearer <token>- Register and login
- Scan products
- View scan history
- View product details
- All User permissions
- Transfer product ownership
- View owned products
- All Supplier permissions
- Create products
- Update own products
- Deactivate own products
- View product scans
- All permissions
- Create manufacturer accounts
- View all users
- Deactivate/activate users
- View all products
- Deactivate any product
Use the seed script (recommended for first admin):
npm run seed:adminIf you need to manually promote a user to admin or create additional admins:
- 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" } }
)- Via MongoDB Compass:
- Connect to your database
- Navigate to the
userscollection - Find the user you want to promote
- Edit the document and change
roleto"admin" - Save changes
- 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");- ✅ 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
- JWT Authentication: Secure token-based authentication
- Password Hashing: bcrypt with salt rounds
- Rate Limiting: Prevents brute force attacks
- Helmet: Sets security headers
- CORS: Configured for specific origins
- Input Validation: Zod schema validation
- Error Handling: Comprehensive error middleware
- Enable 2-factor authentication on your Gmail account
- Generate an App Password: Google Account → Security → 2-Step Verification → App Passwords
- Use the generated password in
SMTP_PASS
Update the following in .env:
SMTP_HOST: Your SMTP hostSMTP_PORT: Usually 587 (TLS) or 465 (SSL)SMTP_SECURE: true for 465, false for 587SMTP_USER: Your email usernameSMTP_PASS: Your email password
# Install MongoDB
# Start MongoDB service
mongod
# Connection URI in .env
MONGODB_URI=mongodb://localhost:27017/trustscan- Create a cluster at https://cloud.mongodb.com
- Get connection string
- Update
.env:
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/trustscan?retryWrites=true&w=majority- Import the
postman_collection.jsonfile into Postman - Create an environment with variable
base_url=http://localhost:5000 - Test endpoints in order:
- Register/Login to get token
- Token is automatically saved for subsequent requests
- Test other endpoints
All errors return a consistent format:
{
"success": false,
"message": "Error message",
"errors": [
{
"field": "email",
"message": "Invalid email address"
}
]
}Logs are written to:
logs/error.log- Error level logslogs/combined.log- All logs- Console (development mode)
- Set
NODE_ENV=production - Use strong
JWT_SECRET(minimum 32 characters) - Configure proper MongoDB connection
- Set up SSL/TLS certificates
- Use environment variables for all secrets
- Configure proper CORS origins
- Set up monitoring and logging
- Use PM2 or similar for process management
MIT
For issues and questions, please create an issue in the repository.