Skip to content

MettaChain/PropChain-BackEnd

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

920 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PropChain - Blockchain-Powered Real Estate Platform

A modern, scalable backend API for real estate transactions built with NestJS and PostgreSQL

πŸš€ Features

  • User Management - Registration, authentication, and profile management
  • Property Listings - Create, manage, and search property listings
  • Transaction Tracking - Record and track real estate transactions
  • Tax Strategy Suggestions - Store informational, non-binding tax structuring suggestions for transactions
  • Document Management - Store and manage property-related documents
  • Role-Based Access Control - USER, AGENT, ADMIN roles with route protection
  • Clean Architecture - Modular, testable, and maintainable code structure
  • CI/CD Ready - Automated testing and deployment pipeline

πŸ” Role-Based Access Control (RBAC)

The application implements comprehensive RBAC with three user roles:

User Roles

  • USER: Default role for registered users. Can create properties and manage their own data.
  • AGENT: Can manage properties and assist with transactions.
  • ADMIN: Full system access including user management, property administration, and system configuration.

Route Protection

Routes are protected using decorators:

@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@Get('admin/users')
getAllUsers() {
  // Only admins can access
}

Default Role Assignment

New users are automatically assigned the USER role upon registration.

οΏ½ Password Reset

The application provides secure password reset functionality via email:

Password Reset Flow

  1. Request Reset: User submits email address
  2. Token Generation: Secure reset token created (expires in 1 hour)
  3. Email Delivery: Reset link sent to user's email
  4. Token Validation: Token verified on password reset
  5. Password Update: New password hashed and stored

API Endpoints

# Request password reset
POST /auth/password-reset/request
{
  "email": "user@example.com"
}

# Reset password with token
POST /auth/password-reset/reset
{
  "token": "reset-token-here",
  "newPassword": "NewSecurePassword123!"
}

Security Features

  • Token Expiration: Reset tokens expire after 1 hour
  • Single Use: Tokens can only be used once
  • Password History: Prevents reuse of recent passwords
  • Rate Limiting: Previous tokens invalidated on new request
  • Blocked User Protection: No emails sent to blocked accounts

οΏ½πŸ“‹ Prerequisites

  • Node.js >= 18.0.0
  • PostgreSQL >= 14
  • npm >= 8.0.0

πŸ› οΈ Installation

# Install dependencies
npm install

# Copy environment file
cp .env.example .env

# Set up your database URL in .env file

βš™οΈ Configuration

The application uses environment variables for configuration. Copy .env.example to .env and adjust the values as needed.

Environment Variables

Variable Description Default
DATABASE_URL PostgreSQL connection string Required
PORT Server port 3000
NODE_ENV Environment mode development
FRONTEND_URL Frontend application URL for email links http://localhost:3000
JWT_SECRET JWT signing secret Required
JWT_REFRESH_SECRET JWT refresh token secret Required
JWT_ACCESS_EXPIRES_IN Access token expiration 15m
JWT_REFRESH_EXPIRES_IN Refresh token expiration 7d
BCRYPT_ROUNDS Password hashing rounds 12
PASSWORD_HISTORY_LIMIT Password history limit 5
PASSWORD_MIN_LENGTH Minimum password length 8
PASSWORD_REQUIRE_UPPERCASE Require uppercase in password true
PASSWORD_REQUIRE_LOWERCASE Require lowercase in password true
PASSWORD_REQUIRE_DIGIT Require digit in password true
PASSWORD_REQUIRE_SPECIAL Require special char in password true
PASSWORD_SPECIAL_CHARS Allowed special characters !@#$%^&*()_+-=...
FRONTEND_URL Frontend application URL for email links http://localhost:3000
RECAPTCHA_SECRET Google reCAPTCHA v3 private key Required
CAPTCHA_THRESHOLD Minimum reCAPTCHA score to pass 0.5
BASE_URL Root URL of this API server http://localhost:3000
API_URL Full API base URL for email links http://localhost:3000/api
AVATAR_UPLOAD_DIR Directory for user avatar uploads ./uploads/avatars
AVATAR_MAX_FILE_SIZE Max avatar file size in bytes 5242880
CORS_ORIGINS Comma-separated allowed origins http://localhost:3000
DEBUG_PII Enable PII debugging in auth logs false
EMAIL_VERIFICATION_EXPIRES_IN Email verification token TTL 24h
GOOGLE_CLIENT_ID Google OAuth2 client ID β€”
GOOGLE_CLIENT_SECRET Google OAuth2 client secret β€”
GOOGLE_CALLBACK_URL Google OAuth2 callback URL /api/auth/google/callback
BLOCKCHAIN_ENABLED Enable blockchain integration true
BLOCKCHAIN_NETWORK Ethereum network sepolia
BLOCKCHAIN_RPC_URL Ethereum RPC endpoint β€”
BLOCKCHAIN_CONTRACT_ADDRESS Smart contract address β€”
BLOCKCHAIN_PRIVATE_KEY Wallet private key for signing β€”
BACKUP_STORAGE_PATH Directory for DB backup files ./backups
PG_DUMP_PATH Path to pg_dump binary pg_dump
PSQL_PATH Path to psql binary psql
PROPERTY_IMAGES_UPLOAD_DIR Directory for property images ./uploads/properties
PROPERTY_IMAGE_MAX_SIZE Max property image size in bytes 10485760
PROPERTY_IMAGE_MAX_PER_PROPERTY Max images per property 30
GEOCODING_PROVIDER Geocoding provider (nominatim/google) nominatim
NOMINATIM_BASE_URL Nominatim API base URL https://nominatim.openstreetmap.org
GEOCODING_USER_AGENT User agent for geocoding requests PropChain-Backend/1.0
GEOCODING_TIMEOUT_MS Geocoding request timeout (ms) 5000
GOOGLE_GEOCODING_API_KEY Google Geocoding API key (optional) β€”
FRAUD_ALERT_RECIPIENTS Comma-separated fraud alert emails β€”
CACHE_WARMING_ENABLED Enable cache warming on startup false
CACHE_WARMING_INTERVAL Cache warming interval (ms) β€”
TEST_DATABASE_URL PostgreSQL URL for integration tests β€”

πŸ—„οΈ Database Setup

# Generate Prisma Client
npm run db:generate

# Run migrations
npm run migrate

# (Optional) Seed database
npm run db:seed

πŸƒ Running the App

# Development mode
npm run start:dev

# Production mode
npm run build
npm run start:prod

πŸ§ͺ Testing

# Unit tests
npm test

# Test coverage
npm run test:cov

# Watch mode
npm run test:watch

For database-backed integration tests, set TEST_DATABASE_URL to a dedicated test database. Helper utilities are available in test/database/prisma-test-helpers.ts to clean fixtures and reset seeded state between suites.

πŸ“ Project Structure

src/
β”œβ”€β”€ database/           # Database configuration and Prisma service
β”œβ”€β”€ users/              # User management module
β”œβ”€β”€ properties/         # Property listings module
β”œβ”€β”€ app.module.ts       # Main application module
β”œβ”€β”€ app.controller.ts   # App controller with health check
└── main.ts             # Application entry point

prisma/
β”œβ”€β”€ schema.prisma       # Database schema
└── seed.ts             # Database seeding

πŸ”§ Available Scripts

Command Description
npm run build Build the application
npm run start:dev Start in development mode with watch
npm run start:prod Start in production mode
npm run lint Run ESLint with auto-fix
npm run format Format code with Prettier
npm test Run tests
npm run test:cov Run tests with coverage
npm run migrate Run database migrations
npm run migrate:deploy Deploy migrations to production
npm run db:generate Generate Prisma Client
npm run db:studio Open Prisma Studio

πŸ“Š Database Schema

Core Models

  • User - Platform users (buyers, sellers, agents, admins)
  • Property - Real estate listings with detailed information
  • Transaction - Property transactions with blockchain integration
  • Document - Property-related documents and files

Module Docs

πŸ” Environment Variables

Create a .env file based on .env.example:

DATABASE_URL=postgresql://user:password@localhost:5432/propchain
PORT=3000
JWT_SECRET=your-secret-key

🚒 Deployment

The CI/CD pipeline is configured in .github/workflows/ci.yml:

  • Develop branch β†’ Deploys to staging
  • Main branch β†’ Deploys to production

Manual Deployment

# Build for production
npm run build

# Run migrations
npm run migrate:deploy

# Start application
npm run start:prod

πŸ“ API Endpoints

Health Check

  • GET /api/health - Application health status

Users

  • POST /api/users - Create user
  • GET /api/users - List all users
  • GET /api/users/:id - Get user by ID
  • PUT /api/users/:id - Update user
  • DELETE /api/users/:id - Delete user

Properties

  • POST /api/properties - Create property
  • GET /api/properties - List all properties
  • GET /api/properties/:id - Get property by ID
  • PUT /api/properties/:id - Update property
  • DELETE /api/properties/:id - Delete property

Tax Strategy Suggestions

  • GET /api/transactions/:transactionId/tax-strategies - List tax strategy suggestions for a transaction
  • POST /api/transactions/:transactionId/tax-strategies - Create a tax strategy suggestion
  • PATCH /api/transactions/:transactionId/tax-strategies/:strategyId - Update a tax strategy suggestion

Tax strategy suggestions are informational only and are not legal or tax advice. See docs/Tax_Strategy_Suggestions.md for usage details.

🀝 Contributing

See CONTRIBUTING.md for contribution guidelines, branch naming conventions, PR expectations, and local test/lint instructions.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add 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.

πŸ‘₯ Support

For support, email support@propchain.com or join our Slack channel

Developer Requirements β€” TypeScript & Linting

  • TypeScript strict mode: The project now enables strict TypeScript checks. The base config is in tsconfig.json.
  • Key compiler flags enforced: noImplicitAny, strictNullChecks and related strict checks are enabled for app builds via tsconfig.app.json.
  • ESLint rules: @typescript-eslint/no-explicit-any is set to error and explicit boundary/return types are encouraged via @typescript-eslint/explicit-module-boundary-types and @typescript-eslint/explicit-function-return-type (set to warn). See .eslintrc.js.

Local checks before committing/pushing:

# Install
npm ci

# Run linter (auto-fixable issues)
npm run lint

# Build to verify TypeScript strict checks
npm run build

CI: A GitHub Actions workflow (.github/workflows/ci.yml) now runs npm run lint and npm run build on pushes and PRs to main to validate the stricter compilation and linting rules.

About

No description, website, or topics provided.

Resources

Contributing

Security policy

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages