Skip to content

Devstein1365/unifyr_backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Unifyr Backend API

RESTful API for Multi-Service Platform

A robust Node.js/Express backend API supporting authentication, order management, and admin operations for a multi-service platform.

Node.js Express MongoDB JWT License


πŸš€ Features

  • πŸ” JWT Authentication - Secure token-based authentication with 30-day expiration
  • πŸ‘€ User Management - Registration, login, profile updates, password change
  • πŸ“¦ Order System - CRUD operations for orders with service-specific fields
  • πŸ‘¨β€πŸ’Ό Admin Panel - Dashboard statistics, order management, user management
  • πŸ—„οΈ MongoDB Integration - Mongoose ODM with schema validation
  • πŸ”’ Password Hashing - bcrypt with 10 rounds for secure password storage
  • 🌐 CORS Enabled - Ready for frontend integration
  • πŸ“„ Auto-generated Order IDs - Sequential order numbers (ORD-001, ORD-002, etc.)
  • πŸ–ΌοΈ Base64 File Upload - Support for profile pictures up to 50MB

πŸ› οΈ Tech Stack

Technology Version Purpose
Node.js 18+ Runtime Environment
Express 5.1.0 Web Framework
MongoDB Atlas Database
Mongoose 8.19.2 ODM
JWT 9.0.2 Authentication
bcryptjs 3.0.2 Password Hashing
CORS 2.8.5 Cross-Origin Requests
dotenv 17.2.3 Environment Variables

πŸ“‹ Prerequisites

Before running this project, make sure you have:

  • Node.js (v18 or higher)
  • npm or yarn
  • MongoDB Atlas account (or local MongoDB)

πŸ”§ Installation

  1. Clone the repository

    git clone <your-repo-url>
    cd Backend
  2. Install dependencies

    npm install
  3. Create environment file

    cp .env.example .env
  4. Configure environment variables

    PORT=3000
    MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/unifyr
    JWT_SECRET=your_super_secret_jwt_key_here
    NODE_ENV=development

🚦 Running the Application

Development Mode (with auto-restart)

npm run dev

Server will start at http://localhost:3000

Production Mode

node src/index.js

Create Admin User

node scripts/makeAdmin.js

Default admin credentials:

  • Email: admin@unifyr.com
  • Password: admin2025

πŸ“ Project Structure

Backend/
β”œβ”€β”€ config/
β”‚   └── db.js              # MongoDB connection
β”œβ”€β”€ controllers/
β”‚   β”œβ”€β”€ authController.js   # Authentication logic
β”‚   β”œβ”€β”€ orderController.js  # Order management
β”‚   └── adminController.js  # Admin operations
β”œβ”€β”€ middlewares/
β”‚   └── auth.js            # JWT verification & auth
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ User.js            # User schema
β”‚   └── Order.js           # Order schema
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ authRoutes.js      # Auth endpoints
β”‚   β”œβ”€β”€ orderRoutes.js     # Order endpoints
β”‚   └── adminRoutes.js     # Admin endpoints
β”œβ”€β”€ scripts/
β”‚   └── makeAdmin.js       # Create admin user
β”œβ”€β”€ src/
β”‚   └── index.js           # Server entry point
β”œβ”€β”€ .env                   # Environment variables
β”œβ”€β”€ .env.example           # Environment template
β”œβ”€β”€ package.json           # Dependencies
└── Readme.md             # This file

πŸ”Œ API Endpoints

πŸ“ Base URL

http://localhost:3000/api

πŸ”“ Authentication (Public)

Method Endpoint Description
POST /auth/register Register new user
POST /auth/login Login user
POST /auth/reset-password Reset password

πŸ”’ Authentication (Protected)

Method Endpoint Description
GET /auth/me Get current user
PUT /auth/profile Update profile
PUT /auth/password Change password

πŸ“¦ Orders (Protected)

Method Endpoint Description
GET /orders Get user's orders
POST /orders Create new order
GET /orders/:id Get single order
PUT /orders/:id Update order
DELETE /orders/:id Delete order
GET /orders/:id/invoice Get invoice data
POST /orders/bulk-invoices Get multiple invoices

πŸ‘¨β€πŸ’Ό Admin (Protected + Admin Role)

Method Endpoint Description
GET /admin/stats Dashboard statistics
GET /admin/orders Get all orders
PUT /admin/orders/:id Update any order
DELETE /admin/orders/:id Delete any order
GET /admin/users Get all users
PUT /admin/users/:id/role Update user role

πŸ₯ Health Check

Method Endpoint Description
GET / API status
GET /api/health Health check with uptime

πŸ“Š Database Schema

User Model

{
  name: String,
  email: String (unique),
  password: String (hashed),
  role: String (user/admin),
  profilePicture: String (base64),
  phone: String,
  address: String,
  city: String,
  country: String,
  bio: String,
  isActive: Boolean,
  createdAt: Date,
  updatedAt: Date
}

Order Model

{
  orderId: String (auto-generated: ORD-001),
  user: ObjectId (ref: User),
  customer: {
    name: String,
    email: String,
    phone: String
  },
  service: String (enum: 6 services),
  type: String,
  quantity: Number,
  price: Number,
  status: String (pending/in-progress/completed/cancelled),
  date: Date,
  notes: String,
  // Service-specific fields
  dimensions: String,
  material: String,
  cuisine: String,
  deliveryTime: String,
  // ... more fields
  createdAt: Date,
  updatedAt: Date
}

πŸ” Authentication Flow

  1. User Registration

    • Password hashed with bcrypt (10 rounds)
    • JWT token generated (30-day expiration)
    • Default role: user
  2. User Login

    • Email/password validation
    • Password comparison with bcrypt
    • JWT token returned on success
  3. Protected Routes

    • Token extracted from Authorization: Bearer <token>
    • Token verified with JWT_SECRET
    • User attached to req.user
  4. Admin Routes

    • Additional check: req.user.role === 'admin'
    • 403 Forbidden if not admin

πŸ”§ Configuration

Environment Variables

Variable Required Description Example
PORT No Server port 3000
MONGO_URI Yes MongoDB connection string mongodb+srv://...
JWT_SECRET Yes Secret key for JWT your_secret_key
NODE_ENV No Environment mode development/production

Body Parser Limits

  • JSON payload limit: 50MB (for base64 images)
  • URL-encoded limit: 50MB

πŸ§ͺ Testing

Manual Testing

Use the Thunder Client collection located in thunder-tests/ folder.

Testing Tools

  • Thunder Client (VS Code extension)
  • Postman
  • cURL

Example Request

# Login
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@unifyr.com","password":"admin2025"}'

# Get orders (with token)
curl -X GET http://localhost:3000/api/orders \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

πŸ“¦ Deployment

Option 1: Railway

  1. Connect Repository

    railway login
    railway link
  2. Set Environment Variables

    • Add all variables from .env
    • Railway auto-detects Node.js
  3. Deploy

    railway up

Option 2: Render

  1. Create new Web Service
  2. Connect GitHub repository
  3. Set build command: npm install
  4. Set start command: node src/index.js
  5. Add environment variables
  6. Deploy

Option 3: Fly.io

  1. Install Fly CLI

    curl -L https://fly.io/install.sh | sh
  2. Deploy

    fly launch
    fly deploy

πŸ› Troubleshooting

MongoDB Connection Issues

  • Verify MONGO_URI is correct
  • Check MongoDB Atlas IP whitelist (allow 0.0.0.0/0 for cloud deployment)
  • Ensure database user has proper permissions

JWT Token Errors

  • Verify JWT_SECRET is set
  • Check token expiration (30 days default)
  • Ensure Bearer token format: Bearer <token>

CORS Issues

  • Check frontend URL is allowed
  • Update CORS configuration in src/index.js if needed

Port Already in Use

# Find process using port 3000
lsof -i :3000

# Kill the process
kill -9 <PID>

πŸ”’ Security Features

  • βœ… Password hashing with bcrypt
  • βœ… JWT token authentication
  • βœ… Protected routes middleware
  • βœ… Role-based access control
  • βœ… Password validation (min 6 characters)
  • βœ… Email validation with regex
  • βœ… Mongoose schema validation
  • βœ… Error handling middleware
  • βœ… Active account check

Production Checklist

  • Change JWT_SECRET to strong random string
  • Update MONGO_URI to production database
  • Set NODE_ENV=production
  • Enable rate limiting (recommended)
  • Add helmet.js for security headers (recommended)
  • Set up monitoring/logging
  • Configure CORS for specific origins

πŸ“„ Scripts

Command Description
npm run dev Start development server with nodemon
node src/index.js Start production server
node scripts/makeAdmin.js Create admin user

πŸ“– API Documentation

For detailed API testing examples, see:

  • API_TESTING.md - Raw HTTP request examples
  • TESTING_GUIDE.md - Comprehensive testing guide
  • thunder-tests/ - Thunder Client collection

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


πŸ“„ License

This project is licensed under the MIT License.


πŸ“ž Support

For support, email your-email@example.com or open an issue in the repository.


Made with ❀️ by Your Team

Frontend Repo β€’ Documentation β€’ Report Bug

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published