Skip to content

DeepVasoya08/Ciphrix-assignment

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

Request Management Application

A full-stack Request Management Web Application built with Node.js, Express, PostgreSQL, and React. This application provides a comprehensive system for managing requests with role-based access control, allowing employees to create and manage requests while managers oversee approval workflows.

Features

  • User Authentication: Secure sign up and sign in with JWT-based authentication
  • Role-Based Access Control: Two distinct roles - Employee and Manager
  • Request Management:
    • Employees can create requests and assign them to other employees
    • Managers can approve/reject requests assigned to their employees
    • Employees can take action and close approved requests
  • Business Rules Enforcement:
    • Only managers can approve/reject requests
    • Only assigned employees can action/close requests
    • Requests must be approved before action can be taken
  • Logging & Monitoring: Winston logger with file-based logging and metrics endpoint
  • Rate Limiting: Express rate limiting for API protection
  • Clean Architecture: MVC pattern with separation of concerns
  • Responsive Design: Modern, mobile-friendly user interface

Tech Stack

Backend

  • Node.js with Express.js - Web framework
  • PostgreSQL - Relational database
  • JWT (jsonwebtoken) - Token-based authentication
  • Winston - Logging library
  • Express Validator - Input validation middleware
  • Bcryptjs - Password hashing
  • CORS - Cross-origin resource sharing
  • Express Rate Limit - API rate limiting
  • dotenv - Environment variable management

Frontend

  • React 18 - UI library
  • React Router DOM - Client-side routing
  • Vite - Build tool and development server
  • Axios - HTTP client for API calls
  • Modern CSS - Responsive design with clean styling

Project Structure

.
├── backend/
│   ├── config/
│   │   └── database.js          # Database configuration
│   ├── controllers/
│   │   ├── auth.controller.js   # Authentication logic
│   │   ├── request.controller.js # Request management logic
│   │   └── user.controller.js    # User management logic
│   ├── middleware/
│   │   ├── auth.js               # JWT authentication middleware
│   │   ├── errorHandler.js       # Global error handler
│   │   └── logger.js             # Request logging middleware
│   ├── models/
│   │   ├── User.model.js         # User data model
│   │   └── Request.model.js      # Request data model
│   ├── routes/
│   │   ├── auth.routes.js        # Authentication routes
│   │   ├── request.routes.js     # Request routes
│   │   └── user.routes.js        # User routes
│   ├── scripts/
│   │   ├── migrate.js            # Database migration script
│   │   └── assign-manager.js     # Helper script to assign managers to employees
│   ├── utils/
│   │   ├── logger.js             # Winston logger configuration
│   │   └── metrics.js            # Application metrics
│   ├── validators/
│   │   ├── auth.validator.js      # Auth input validation
│   │   └── request.validator.js  # Request input validation
│   ├── .env.example              # Environment variables template
│   ├── .gitignore
│   ├── package.json
│   └── server.js                 # Application entry point
├── frontend/
│   ├── index.html                # Main HTML file
│   ├── src/
│   │   ├── main.jsx              # React entry point
│   │   ├── App.jsx               # Main React component
│   │   ├── components/           # Reusable React components
│   │   ├── pages/                # Page components
│   │   ├── contexts/             # React contexts (Auth)
│   │   └── utils/                # Utility functions
│   ├── style.css                 # Styling
│   ├── vite.config.js            # Vite configuration
│   ├── package.json
│   └── .gitignore
└── README.md

Prerequisites

  • Node.js (v18 or higher)
  • PostgreSQL (v12 or higher)
  • npm or yarn

Quick Start

For a detailed step-by-step guide, see QUICKSTART.md.

Setup Instructions

1. Clone the Repository

git clone <repository-url>
cd Ciphrix

2. Database Setup

  1. Install and start PostgreSQL
  2. Create a new database:
CREATE DATABASE request_management;

3. Backend Setup

  1. Navigate to the backend directory:
cd backend
  1. Install dependencies:
npm install
  1. Create a .env file (copy from .env.example):
# On Windows (PowerShell)
Copy-Item .env.example .env

# On Linux/Mac
cp .env.example .env
  1. Update the .env file with your database credentials:
PORT=3000
NODE_ENV=development
DB_HOST=localhost
DB_PORT=5432
DB_NAME=request_management
DB_USER=postgres
DB_PASSWORD=your_password
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_EXPIRES_IN=7d
FRONTEND_URL=http://localhost:5173
  1. Run database migration:
npm run migrate
  1. Create logs directory:
# On Windows (PowerShell)
New-Item -ItemType Directory -Path logs

# On Linux/Mac
mkdir logs
  1. Start the backend server:
# Development mode (with auto-reload)
npm run dev

# Production mode
npm start

The backend server will run on http://localhost:3000

4. Frontend Setup

  1. Open a new terminal and navigate to the frontend directory:
cd frontend
  1. Install dependencies:
npm install
  1. Start the development server:
npm run dev

The frontend will run on http://localhost:5173

API Endpoints

Authentication

  • POST /api/auth/signup - Register a new user
  • POST /api/auth/signin - Sign in
  • GET /api/auth/profile - Get current user profile (requires auth)

Requests

  • POST /api/requests - Create a new request (requires auth)
  • GET /api/requests - Get all requests (requires auth)
  • GET /api/requests/:id - Get a specific request (requires auth)
  • POST /api/requests/:id/approve - Approve a request (manager only)
  • POST /api/requests/:id/reject - Reject a request (manager only)
  • POST /api/requests/:id/action - Take action on a request (employee only)
  • POST /api/requests/:id/close - Close a request (employee only)

Users

  • GET /api/users - Get all users (requires auth)
  • GET /api/users/employees - Get all employees (manager only)
  • POST /api/users/manager - Assign manager to user (manager only)

System

  • GET /health - Health check endpoint
  • GET /metrics - Application metrics

Business Rules

  1. Request Creation: Any authenticated user can create a request and assign it to another employee
  2. Request Approval: Only the manager of the assigned employee can approve/reject a request
  3. Request Action: Only the assigned employee can take action on an approved request
  4. Request Closure: Only the assigned employee can close a request that is approved or in progress
  5. Status Flow:
    • pendingapproved/rejected (by manager)
    • approvedin_progress (by employee action)
    • approved/in_progressclosed (by employee)

Testing the Application

Initial Setup

  1. Create Users:

  2. Set Manager-Employee Relationship:

    • Use the helper script: node scripts/assign-manager.js <employee_id> <manager_id>
    • Or use the API endpoint: POST /api/users/manager
    • Or directly via SQL (see QUICKSTART.md for details)

Workflow Testing

  1. Create a Request:

    • Login as Employee 1
    • Navigate to "Create Request" tab
    • Create a request and assign it to Employee 2
  2. Approve Request:

    • Logout and login as Employee 2's Manager
    • View the request in "My Requests" tab
    • Click "Approve" on the request
  3. Action Request:

    • Logout and login as Employee 2
    • View the approved request
    • Click "Take Action" and enter an action note
  4. Close Request:

    • As Employee 2
    • Click "Close" to close the request

Development

Backend Development

  • The backend uses ES6 modules (type: "module" in package.json)
  • Nodemon is configured for auto-reload in development mode
  • Logs are stored in backend/logs/ directory:
    • combined.log - All logs
    • error.log - Error logs only
  • Winston logger is configured for different log levels (info, warn, error)
  • Express Rate Limiting is enabled to protect API endpoints
  • Environment variables are loaded from .env file

Frontend Development

  • Vite provides hot module replacement (HMR) for fast development
  • The frontend uses React 18 with React Router for client-side routing
  • API calls are made using Axios with interceptors for:
    • Automatic JWT token attachment
    • Error handling and redirects
  • React Context API is used for global authentication state management
  • Responsive design with modern CSS styling

Helper Scripts

  • scripts/migrate.js - Creates database tables and initial schema
  • scripts/assign-manager.js - Assigns a manager to an employee
    node scripts/assign-manager.js <employee_id> <manager_id>

Production Deployment

Backend

  1. Set NODE_ENV=production in .env
  2. Update JWT_SECRET to a strong, random value (use a secure random generator)
  3. Update database credentials to production database
  4. Ensure PostgreSQL is properly configured and accessible
  5. Run migrations: npm run migrate
  6. Start server: npm start (or use a process manager like PM2)

Frontend

  1. Build the frontend: cd frontend && npm run build
  2. The build output will be in frontend/dist/
  3. Serve the build files using:
    • A static file server (nginx, Apache)
    • A CDN
    • Or integrate with the backend Express server

Security Considerations

  • Use HTTPS in production
  • Set secure CORS origins
  • Use environment-specific .env files (never commit .env to version control)
  • Regularly update dependencies for security patches
  • Configure proper database backups
  • Set up monitoring and alerting for production logs

Troubleshooting

Common Issues

Database Connection Error

  • Verify PostgreSQL is running
  • Check database credentials in .env
  • Ensure database request_management exists
  • Verify network connectivity to database server

Port Already in Use

  • Backend: Change PORT in .env
  • Frontend: Change port in vite.config.js or use npm run dev -- --port <port>

CORS Errors

  • Ensure FRONTEND_URL in backend .env matches frontend URL
  • Default is http://localhost:5173
  • Check browser console for specific CORS error messages

Migration Errors

  • Ensure database exists
  • Check user has proper permissions
  • Drop and recreate database if needed:
    DROP DATABASE request_management;
    CREATE DATABASE request_management;

Authentication Issues

  • Verify JWT_SECRET is set in .env
  • Check token expiration settings
  • Clear browser localStorage if tokens are corrupted

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

ISC

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors