Skip to content

MTS-Services/OmeshAPI_new

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

61 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

McCann & Curran Property Management API

A comprehensive, production-ready backend API for property management operations built with Node.js, Express, Prisma ORM, and PostgreSQL.

πŸ—οΈ Architecture Overview

This API follows Clean Architecture principles with strict separation of concerns:

  • πŸ“ Interface Layer: Controllers, Routes, DTOs, Middlewares
  • πŸ”§ Business Logic Layer: Services (no business logic in controllers)
  • πŸ’Ύ Data Access Layer: Repositories (using Repository pattern)
  • πŸ›‘οΈ Cross-cutting Concerns: Authentication, Authorization, Validation, Logging, Error Handling

🎯 Key Features

  • βœ… JWT Authentication with Access + Refresh token strategy
  • βœ… Role-based Authorization (Admin, Landlord, Tenant)
  • βœ… Dependency Injection pattern
  • βœ… Repository Pattern for database abstraction
  • βœ… Centralized Error Handling with consistent responses
  • βœ… Global Response Formatter for API consistency
  • βœ… Production-ready Logging (Winston)
  • βœ… Environment-based Configuration with validation
  • βœ… Request Validation (Joi schemas)
  • βœ… Rate Limiting and Security middleware
  • βœ… Health Check endpoints
  • βœ… Graceful Shutdown handling

πŸ“‹ Requirements

  • Node.js 18.0.0 or higher
  • PostgreSQL 12.0 or higher
  • npm or yarn

πŸš€ Quick Start

1. Clone and Install

# Clone the repository
git clone <repository-url>
cd property-management-api

# Install dependencies
npm install

# Install Prisma CLI globally (optional)
npm install -g prisma

2. Environment Setup

# Copy environment template
cp .env.example .env

# Edit .env file with your configuration
nano .env

Required Environment Variables:

DATABASE_URL="postgresql://username:password@localhost:5432/property_management"
JWT_SECRET="your-super-secure-jwt-secret-minimum-32-characters"
JWT_REFRESH_SECRET="your-refresh-secret-minimum-32-characters"

3. Database Setup

# Generate Prisma client
npx prisma generate

# Run database migrations
npx prisma migrate dev --name init

# (Optional) Seed database with sample data
npm run prisma:seed

# (Optional) Open Prisma Studio to view data
npm run prisma:studio

4. Start the Server

# Development mode with auto-restart
npm run dev

# Production mode
npm start

The API will be available at http://localhost:3000

πŸ—οΈ Project Structure

src/
β”œβ”€β”€ app.js                      # Express app configuration
β”œβ”€β”€ server.js                   # Server entry point with graceful shutdown
β”œβ”€β”€πŸ“ config/
β”‚   β”œβ”€β”€ index.js               # Environment-based configuration
β”‚   └── database.js            # Prisma client setup
β”œβ”€β”€ πŸ“ middlewares/
β”‚   β”œβ”€β”€ auth.js                # Authentication & authorization
β”‚   β”œβ”€β”€ errorHandler.js        # Global error handling
β”‚   └── responseFormatter.js   # Response formatting
β”œβ”€β”€ πŸ“ utils/
β”‚   β”œβ”€β”€ apiResponse.js         # Response helpers
β”‚   β”œβ”€β”€ jwt.js                 # JWT utilities
β”‚   └── logger.js              # Winston logger setup
β”œβ”€β”€ πŸ“ validators/
β”‚   β”œβ”€β”€ auth.validator.js      # Authentication validation schemas
β”‚   └── common.validator.js    # Reusable validation patterns
β”œβ”€β”€ πŸ“ routes/
β”‚   └── index.js               # Main API routes consolidation
└── πŸ“ modules/
    β”œβ”€β”€ πŸ“ auth/               # Authentication module
    β”‚   β”œβ”€β”€ auth.controller.js
    β”‚   β”œβ”€β”€ auth.dto.js
    β”‚   β”œβ”€β”€ auth.repository.js
    β”‚   β”œβ”€β”€ auth.routes.js
    β”‚   β”œβ”€β”€ auth.service.js
    β”‚   └── auth.test.http
    └── πŸ“ user/               # User management module
        β”œβ”€β”€ user.controller.js
        β”œβ”€β”€ user.dto.js
        β”œβ”€β”€ user.repository.js
        β”œβ”€β”€ user.routes.js
        β”œβ”€β”€ user.service.js
        └── user.test.http

πŸ“š API Endpoints

πŸ” Authentication (/api/v1/auth)

Method Endpoint Description Access
POST /register Register new user Public
POST /login User login Public
POST /refresh Refresh access token Public
POST /logout User logout Private
GET /me Get current user Private
GET /profile Get user profile Private
PUT /profile Update profile Private
POST /change-password Change password Private
DELETE /account Delete account Private
GET /stats User statistics Admin

πŸ‘₯ User Management (/api/v1/users)

Method Endpoint Description Access
GET / List users with pagination Admin
GET /search Search users Admin
GET /role/:role Get users by role Admin
POST / Create new user Admin
GET /:id Get user details Admin
PUT /:id Update user Admin
DELETE /:id Delete user Admin
POST /bulk-action Bulk operations Admin
GET /me/dashboard Current user dashboard Private
GET /:id/analytics User analytics Admin/Own

🏠 Additional Modules (Structure Ready)

The following modules follow the same pattern and can be implemented:

  • Properties (/api/v1/properties) - Property management
  • Tenancies (/api/v1/tenancies) - Tenancy relationships
  • Maintenance (/api/v1/maintenance) - Maintenance requests
  • Documents (/api/v1/documents) - Document management
  • Conversations (/api/v1/conversations) - Messaging system
  • Payments (/api/v1/payments) - Rent payment tracking
  • Reports (/api/v1/reports) - Analytics and reporting

πŸ›‘οΈ Authentication Flow

Registration & Login

# 1. Register new user
POST /api/v1/auth/register
{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "SecurePassword123!",
  "role": "LANDLORD"
}

# 2. Login to get tokens
POST /api/v1/auth/login
{
  "email": "john@example.com",
  "password": "SecurePassword123!"
}

# Response includes access + refresh tokens
{
  "success": true,
  "data": {
    "user": {...},
    "tokens": {
      "accessToken": "eyJ...",
      "refreshToken": "eyJ...",
      "tokenType": "Bearer",
      "expiresIn": "15m"
    }
  }
}

Making Authenticated Requests

# Include Bearer token in Authorization header
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     http://localhost:3000/api/v1/auth/profile

Token Refresh

# When access token expires, use refresh token
POST /api/v1/auth/refresh
{
  "refreshToken": "YOUR_REFRESH_TOKEN"
}

πŸ‘¨β€πŸ’Ό User Roles & Permissions

πŸ”§ Admin

  • Full CRUD access to all resources
  • User management capabilities
  • System statistics and reporting
  • Audit log access

🏠 Landlord

  • Manage their own properties
  • View associated tenants and tenancies
  • Access property documents and maintenance
  • Communicate with tenants and admin

🏘️ Tenant

  • View their current property details
  • Submit maintenance requests
  • Access lease documents and statements
  • Make rent payments and view history
  • Communicate with landlord and admin

πŸ“‹ Testing

HTTP Test Files

Each module includes .test.http files for manual API testing with VS Code REST Client extension:

  • src/modules/auth/auth.test.http - Authentication endpoints
  • src/modules/user/user.test.http - User management endpoints

Sample Test Request

### Login as admin
POST http://localhost:3000/api/v1/auth/login
Content-Type: application/json

{
  "email": "admin@mccannandcurran.ie",
  "password": "AdminPassword123!"
}

### Get all users (requires admin token)
GET http://localhost:3000/api/v1/users?page=1&limit=10
Authorization: Bearer {{accessToken}}

πŸ” API Response Format

All API responses follow a consistent structure:

Success Response

{
  "success": true,
  "message": "Operation completed successfully",
  "statusCode": 200,
  "timestamp": "2024-03-02T10:30:00.000Z",
  "data": { ... },
  "meta": { 
    "pagination": { ... }
  }
}

Error Response

{
  "success": false,
  "message": "Error description",
  "statusCode": 400,
  "timestamp": "2024-03-02T10:30:00.000Z",
  "errors": [
    {
      "field": "email",
      "message": "Invalid email format",
      "value": "invalid-email"
    }
  ]
}

πŸ”’ Security Features

  • πŸ” JWT Authentication with secure token generation
  • πŸ›‘οΈ Password Hashing using bcrypt with configurable rounds
  • 🚫 Rate Limiting to prevent abuse
  • πŸ” Input Validation with Joi schemas
  • πŸ›‘οΈ Helmet.js security headers
  • 🌐 CORS configuration for cross-origin requests
  • πŸ“ Audit Logging for security events
  • ⚑ Graceful Error Handling without information leakage

πŸš€ Production Deployment

Environment Variables

Ensure these are set in production:

NODE_ENV=production
DATABASE_URL="postgresql://..."
JWT_SECRET="long-secure-random-string"
JWT_REFRESH_SECRET="another-long-secure-random-string"
ALLOWED_ORIGINS="https://yourdomain.com"
LOG_LEVEL=warn

Database Migration

# Deploy database changes
npx prisma migrate deploy

# Generate Prisma client
npx prisma generate

Process Management

Use PM2 or similar for process management:

# Install PM2
npm install -g pm2

# Start application
pm2 start src/server.js --name "property-api"

# Monitor
pm2 monit

# View logs
pm2 logs property-api

Health Checks

Monitor application health:

  • GET /health - Basic health check
  • GET /api/v1/health - Detailed API health
  • GET /api/v1/docs - API documentation

πŸ› Error Handling

The API uses centralized error handling with:

Custom Error Classes

const { AppError } = require('./middlewares/errorHandler');

// Throw operational errors
throw new AppError('Resource not found', 404);
throw new AppError('Validation failed', 422, validationErrors);

Automatic Error Handling

  • Prisma Errors - Database constraint violations, not found errors
  • JWT Errors - Token validation and expiration
  • Validation Errors - Joi schema validation failures
  • File Upload Errors - Multer file size and type errors

πŸ“Š Logging

Production-ready logging with Winston:

  • Development: Colorized console output with stack traces
  • Production: JSON format with file rotation
  • Audit Logging: User actions and security events
  • Request Logging: HTTP request/response logging

Log files (production):

  • logs/error.log - Error level logs
  • logs/combined.log - All logs

🀝 Contributing

  1. Follow the existing folder structure and patterns
  2. Each new module should include: DTO, Repository, Service, Controller, Routes, Tests
  3. Use TypeScript-style JSDoc comments for better documentation
  4. Add appropriate validation schemas
  5. Include comprehensive error handling
  6. Add audit logging for sensitive operations

πŸ“ž Support

For questions and support:


McCann & Curran Property Management Platform - Built with ❀️ using Node.js, Express, Prisma, and PostgreSQL# rpr2011_2500_api

OmeshAPI

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors