Skip to content

sheikhsajid69/ProdManagementAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Product Management API

A comprehensive REST API for product management with Role-Based Access Control (RBAC), authentication, pagination, filtering, and comprehensive testing.

Features

  • 🔐 Authentication & Authorization: JWT-based authentication with role-based access control
  • 👥 User Management: Complete user management with different roles (Admin, Manager, User)
  • 📦 Product Management: Full CRUD operations for products with inventory tracking
  • 🔍 Advanced Search & Filtering: Search and filter products by various criteria
  • 📄 Pagination: Built-in pagination for all list endpoints
  • 🧪 Comprehensive Testing: Unit tests and integration tests with Jest
  • 📊 Statistics & Analytics: Product statistics and inventory insights
  • 🔒 Security: Input validation, error handling, and security best practices

Technology Stack

  • Backend: Node.js, Express.js
  • Authentication: JWT (JSON Web Tokens)
  • Password Hashing: bcrypt
  • Testing: Jest, Supertest
  • Validation: express-validator
  • Logging: Morgan
  • CORS: cors
  • Database: In-memory storage (easily replaceable)

User Roles

Admin

  • Full access to all endpoints
  • User management (create, read, update, delete, activate/deactivate users)
  • Product management (create, read, update, delete products)
  • Access to analytics and statistics

Manager

  • Product management (create, read, update products)
  • Stock management (update stock levels, view low stock)
  • Access to product statistics
  • Limited user management (view users only)

User

  • Read-only access to products
  • Profile management (view and update own profile)
  • Password change functionality

API Endpoints

Authentication

POST /api/v1/users/register    - Register new user
POST /api/v1/users/login       - Login user

User Management

GET    /api/v1/users/profile           - Get current user profile
PUT    /api/v1/users/profile           - Update current user profile
PUT    /api/v1/users/change-password   - Change password

GET    /api/v1/users                   - Get all users (Admin only)
GET    /api/v1/users/:id               - Get user by ID (Admin/Owner)
PUT    /api/v1/users/:id               - Update user (Admin/Owner)
DELETE /api/v1/users/:id               - Delete user (Admin only)
PATCH  /api/v1/users/:id/deactivate    - Deactivate user (Admin only)
PATCH  /api/v1/users/:id/reactivate    - Reactivate user (Admin only)

Product Management

GET    /api/v1/products                    - Get all products with pagination/filtering
GET    /api/v1/products/:id                - Get product by ID
POST   /api/v1/products                    - Create new product (Manager/Admin)
PUT    /api/v1/products/:id                - Update product (Manager/Admin)
DELETE /api/v1/products/:id                - Delete product (Admin only)
PATCH  /api/v1/products/:id/deactivate     - Deactivate product (Manager/Admin)
PATCH  /api/v1/products/:id/reactivate     - Reactivate product (Manager/Admin)
PATCH  /api/v1/products/:id/stock          - Update product stock (Manager/Admin)

GET    /api/v1/products/low-stock          - Get low stock products (Manager/Admin)
GET    /api/v1/products/category/:category - Get products by category
GET    /api/v1/products/stats              - Get product statistics (Manager/Admin)

Utility Endpoints

GET /health  - API health check
GET /        - API welcome endpoint

Installation

  1. Clone the repository

    git clone <repository-url>
    cd ProdManagementAPI
  2. Install dependencies

    npm install
  3. Start the development server

    npm run dev
  4. Start the production server

    npm start

Environment Variables

Create a .env file in the root directory:

NODE_ENV=development
PORT=3000
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_EXPIRES_IN=7d
BCRYPT_ROUNDS=12
DEFAULT_PAGE_SIZE=10
MAX_PAGE_SIZE=100
CORS_ORIGIN=*

Default Users

The application comes with pre-configured default users:

Admin User

  • Username: admin
  • Password: admin123
  • Email: admin@example.com
  • Role: admin

Manager User

  • Username: manager
  • Password: manager123
  • Email: manager@example.com
  • Role: manager

API Usage Examples

Authentication

Register a new user

curl -X POST http://localhost:3000/api/v1/users/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "johndoe",
    "email": "john@example.com",
    "password": "SecurePass123!",
    "firstName": "John",
    "lastName": "Doe"
  }'

Login

curl -X POST http://localhost:3000/api/v1/users/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin",
    "password": "admin123"
  }'

Product Management

Get all products (with pagination)

curl -X GET "http://localhost:3000/api/v1/products?page=1&limit=10" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Create a new product

curl -X POST http://localhost:3000/api/v1/products \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Laptop Pro",
    "description": "High-performance laptop for professionals",
    "price": 1299.99,
    "category": "Electronics",
    "sku": "LAP-PRO-001",
    "quantity": 50,
    "minStockLevel": 10,
    "maxStockLevel": 100
  }'

Update product stock

curl -X PATCH http://localhost:3000/api/v1/products/PRODUCT_ID/stock \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "quantity": 25,
    "operation": "subtract"
  }'

Query Parameters

Pagination

  • page: Page number (default: 1)
  • limit: Items per page (default: 10, max: 100)

Filtering

  • search: Search term for name, description, SKU
  • category: Filter by category
  • isActive: Filter by active status (true/false)
  • minPrice: Minimum price filter
  • maxPrice: Maximum price filter

Sorting

  • sortBy: Field to sort by (default: createdAt)
  • sortOrder: Sort order (asc/desc, default: desc)

Examples

# Search and filter
GET /api/v1/products?search=laptop&category=Electronics&minPrice=500&maxPrice=2000

# Sort by price descending
GET /api/v1/products?sortBy=price&sortOrder=desc&limit=20

# Get users with role filter (Admin only)
GET /api/v1/users?role=manager&isActive=true

Testing

The project includes a comprehensive testing suite with both unit and integration tests.

Running Tests

# Run all tests
npm test

# Run tests in watch mode (for development)
npm run test:watch

# Run tests with coverage report
npm run test:coverage

# Run specific test file
npm test -- tests/integration.test.js

# Run tests matching a pattern
npm test -- --testNamePattern="User Controller"

Test Structure

The test suite includes:

Unit Tests

  • Authentication Middleware (tests/unit.auth.test.js)

    • JWT token validation
    • Authentication flow testing
    • Error handling for invalid tokens
  • Role-Based Access Control (tests/unit.role.test.js)

    • Role permission testing
    • Permission hierarchy validation
    • Access control middleware testing
  • User Controller (tests/unit.userController.test.js)

    • User registration and login logic
    • Profile management operations
    • Password change functionality

Integration Tests

  • Complete API Workflows (tests/integration.test.js)
    • End-to-end user authentication
    • Role-based access validation
    • Product management operations
    • Pagination and filtering functionality
    • Error handling and response validation

Test Coverage

The project targets 80% code coverage across all components:

  • Branches: 80%
  • Functions: 80%
  • Lines: 80%
  • Statements: 80%

Test Utilities

The test suite includes custom utilities:

  • Database Reset: Automatic cleanup between tests
  • User Factory: Create test users with different roles
  • Product Factory: Generate test products for testing
  • Token Generation: Create JWT tokens for authentication testing
  • Custom Matchers: Validate user/product structure and pagination

Test Data

Tests use the following default test users:

  • Admin User: Full access to all endpoints
  • Manager User: Product management and statistics access
  • Regular User: Read-only access to products

Continuous Integration

The testing setup is configured for CI/CD pipelines:

  • Jest configuration with coverage thresholds
  • Test isolation and cleanup
  • Detailed error reporting
  • Support for parallel test execution

Example Test Output

PASS  tests/integration.test.js
  Product Management API Integration Tests
    ✓ Health Check - should return API health status (45ms)
    ✓ Authentication - should register new user (23ms)
    ✓ User Profile Management - should return user profile with valid token (18ms)
    ✓ Product Management - should return all products with pagination (25ms)
    ✓ Role-Based Access Control - should allow admin to access all endpoints (35ms)
    ✓ Pagination and Filtering - should support pagination (22ms)

Test Suites: 5 passed, 5 total
Tests:       45 passed, 45 total
Snapshots:   0 total
Time:        3.234s

Manual API Testing

For manual testing, you can use the provided test users:

Admin User:

curl -X POST http://localhost:3000/api/v1/users/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin123"}'

Manager User:

curl -X POST http://localhost:3000/api/v1/users/login \
  -H "Content-Type: application/json" \
  -d '{"username": "manager", "password": "manager123"}'

Use the returned token in subsequent requests:

curl -X GET http://localhost:3000/api/v1/products \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Project Structure

ProdManagementAPI/
├── src/
│   ├── config/
│   │   └── config.js           # Configuration settings
│   ├── controllers/
│   │   ├── userController.js   # User management logic
│   │   └── productController.js # Product management logic
│   ├── database/
│   │   └── memory.js           # In-memory database with CRUD operations
│   ├── middleware/
│   │   ├── auth.js            # JWT authentication middleware
│   │   ├── role.js            # Role-based access control
│   │   ├── logger.js          # Request logging
│   │   ├── errorHandler.js    # Global error handling
│   │   └── 404handler.js      # 404 error handling
│   ├── routes/
│   │   ├── userRoutes.js      # User routes
│   │   └── productRoutes.js   # Product routes
│   ├── app.js                 # Express app configuration
│   └── server.js              # Server entry point
├── tests/
│   ├── setup.js               # Test setup and utilities
│   ├── integration.test.js    # API integration tests
│   ├── unit.auth.test.js      # Authentication middleware tests
│   ├── unit.role.test.js      # Role-based access tests
│   └── unit.userController.test.js # User controller tests
├── jest.config.js             # Jest configuration
├── package.json
├── .gitignore
└── README.md

Security Features

  • Password Hashing: bcrypt with configurable rounds
  • JWT Authentication: Secure token-based authentication
  • Input Validation: express-validator for request validation
  • Role-Based Access Control: Fine-grained permissions
  • CORS Configuration: Configurable cross-origin resource sharing
  • Error Handling: Comprehensive error handling and logging
  • Request Logging: Detailed request/response logging

Error Handling

The API returns consistent error responses:

{
  "success": false,
  "error": {
    "message": "Error description",
    "details": "Additional error details (development only)"
  }
}

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For support and questions, please open an issue in the repository.


Note: This is a demonstration project using in-memory storage. For production use, consider integrating with a proper database (MongoDB, PostgreSQL, etc.) and implementing additional security measures."# ProdManagementAPI"

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published