Skip to content

Ishu6129/LedgerFlow

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

LedgerFlow

Live Demo API Status

A production-ready banking API with ACID compliance, immutable ledger tracking, and enterprise-grade security

Getting Started β€’ API Reference β€’ Live Demo

πŸ“‹ Table of Contents

🌐 Live API

The API is publicly accessible at: https://ledgerflow-x3iq.onrender.com/

API Base URL

https://ledgerflow-x3iq.onrender.com/api

Note: This is a free Render.com instance, so it may take a few seconds to wake up if it's been inactive. First request might have a slight delay.

✨ Core Features

πŸ” Security

  • JWT authentication with token blacklist
  • Password hashing with bcrypt
  • Dual middleware (user + system auth)
  • 3-day auto-expiry blacklist (TTL index)

πŸ’° Accounts

  • Multi-account per user support
  • ACTIVE status enforcement
  • Balance from immutable ledger
  • Full transaction history

πŸ’Έ Transactions

  • User-to-user money transfers
  • Idempotent operations (UUID v4)
  • 7-second delay for concurrency
  • Email notifications (OAuth2 Gmail)

πŸ“Š Ledger

  • Immutable audit trail
  • DEBIT/CREDIT entries only
  • Pre-hooks prevent modification
  • Balance = Credits - Debits

πŸ”’ Data Integrity

  • ACID compliant transactions
  • Race condition prevention
  • Unique idempotencyKey constraint
  • Atomic operations with rollback

πŸ“§ Notifications

  • Registration welcome emails
  • Transaction confirmation alerts
  • OAuth2 Gmail integration
  • Async email delivery

πŸš€ Quick Start

Option 1: Use the Live API (No Setup Required)

Simply use the base URL: https://ledgerflow-x3iq.onrender.com/api

Option 2: Run Locally

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB (v4.0+ for transactions)

Installation

# Clone the repository
git clone https://github.com/Ishu6129/LedgerFlow.git
cd LedgerFlow

# Install dependencies
npm install

# Create .env file with required variables (see Environment Variables section)

# Start the server
npm start

# Server runs on http://localhost:3000
# Visit http://localhost:3000 for API documentation

First API Calls (Using Live API)

# 1. Register a user
curl -X POST https://ledgerflow-x3iq.onrender.com/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name":"John Doe","email":"john@example.com","password":"secure123"}'

# 2. Login to get JWT token
curl -X POST https://ledgerflow-x3iq.onrender.com/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"john@example.com","password":"secure123"}'
# Save the token from response

# 3. Create an account (use token from login)
curl -X POST https://ledgerflow-x3iq.onrender.com/api/accounts \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json"

# 4. Check balance
curl -X GET https://ledgerflow-x3iq.onrender.com/api/accounts/balance \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

πŸ“š API Reference

πŸ” Authentication Endpoints

Method Endpoint Description Auth
POST /api/auth/register Create new user None
POST /api/auth/login Login & get JWT None
POST /api/auth/logout Logout & blacklist token βœ… JWT
Register Example

Request:

POST /api/auth/register
{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "SecurePass123!"
}

Response:

{
  "success": true,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "507f1f77bcf86cd799439011",
    "name": "John Doe",
    "email": "john@example.com",
    "role": "user"
  }
}

πŸ’° Account Endpoints

Method Endpoint Description Auth
POST /api/accounts Create bank account βœ… JWT
GET /api/accounts Get all accounts βœ… JWT
GET /api/accounts/balance Check balance βœ… JWT
GET /api/accounts/history Transaction history βœ… JWT

πŸ’Έ Transaction Endpoints

Method Endpoint Description Auth Notes
POST /api/transactions Transfer money (user-to-user) βœ… JWT Requires idempotencyKey (UUID v4)
POST /api/transactions/system/initial-fund Admin funding only πŸ”‘ System Creates initial account funds
Transfer Money Example

Request:

POST /api/transactions
Authorization: Bearer <your_jwt_token>
{
  "fromUserAccount": "acc_123456",
  "toUserAccount": "acc_789012",
  "amount": 5000,
  "idempotencyKey": "550e8400-e29b-41d4-a716-446655440000"
}

Response:

{
  "success": true,
  "transaction": {
    "id": "txn_987654",
    "fromAccount": "acc_123456",
    "toAccount": "acc_789012",
    "amount": 5000,
    "status": "COMPLETED",
    "timestamp": "2024-01-15T10:35:00Z"
  }
}

πŸ”’ ACID Compliance

Property Implementation Benefit
Atomicity MongoDB sessions with commit/rollback All-or-nothing execution
Consistency Unique constraints, ledger immutability Data integrity maintained
Isolation Session isolation, 7-second delay Concurrent ops don't interfere
Durability Write-after-commit, replica sets Data persists forever

πŸ› οΈ Tech Stack

Category Technology
Backend Node.js + Express.js
Database MongoDB + Mongoose ODM
Authentication JWT + bcryptjs
Email Nodemailer + OAuth2 Gmail
Transactions MongoDB Sessions
Security Token Blacklist + TTL
Deployment Render.com + MongoDB Atlas

πŸ”§ Environment Variables

MONGO_URI=mongodb://localhost:27017/ledgerflow
# MongoDB Atlas example: mongodb+srv://user:password@cluster.mongodb.net/ledgerflow

JWT_SECRET_KEY=your-super-secret-jwt-key-change-in-production

# Gmail OAuth2 Configuration (from Google Cloud Console)
EMAIL_USER=your-email@gmail.com
CLIENT_ID=your-google-oauth-client-id
CLIENT_SECRET=your-google-oauth-client-secret
REFRESH_TOKEN=your-google-refresh-token

Setting up Gmail OAuth2:

  1. Go to Google Cloud Console
  2. Create OAuth 2.0 credentials (Desktop Application)
  3. Download credentials and use in .env
  4. Enable Gmail API for your project
  5. Replace CLIENT_ID, CLIENT_SECRET, and REFRESH_TOKEN with your credentials

πŸ“ Code Examples

Node.js (Using Live API)

const axios = require('axios');

const API_BASE_URL = 'https://ledgerflow-x3iq.onrender.com/api';

async function example() {
  // Register
  const register = await axios.post(`${API_BASE_URL}/auth/register`, {
    name: 'Jane Smith',
    email: 'jane@example.com',
    password: 'SecurePass123!'
  });
  
  const token = register.data.token;
  
  // Transfer money
  const transfer = await axios.post(`${API_BASE_URL}/transactions`, 
    {
      fromUserAccount: 'acc_123456',
      toUserAccount: 'acc_789012',
      amount: 1000,
      idempotencyKey: crypto.randomUUID()
    },
    { headers: { Authorization: `Bearer ${token}` } }
  );
}

πŸ“Š Database Schema

Users Collection

{
  _id: ObjectId,
  name: String,
  email: { type: String, unique: true },
  password: String (bcrypt hashed),
  role: { type: String, enum: ['user', 'system'], default: 'user' },
  createdAt: Date,
  updatedAt: Date
}

Accounts Collection

{
  _id: ObjectId,
  user: ObjectId (ref: User),
  status: { type: String, enum: ['ACTIVE'], default: 'ACTIVE' },
  currency: { type: String, default: 'INR' },
  createdAt: Date,
  updatedAt: Date
}

Transactions Collection

{
  _id: ObjectId,
  from: ObjectId (ref: Account),
  to: ObjectId (ref: Account),
  amount: Number,
  status: { type: String, enum: ['PENDING', 'COMPLETED', 'FAILED', 'REVERSED'] },
  idempotencyKey: { type: String, unique: true },
  createdAt: Date
}

Ledger Collection (Immutable)

{
  _id: ObjectId,
  account: ObjectId (ref: Account),
  type: { type: String, enum: ['DEBIT', 'CREDIT'] },
  amount: Number,
  transaction: ObjectId (ref: Transaction),
  createdAt: Date
  // NOTE: Cannot be updated or deleted after creation (pre-hooks prevent this)
}

Token Blacklist Collection

{
  _id: ObjectId,
  token: { type: String, unique: true },
  createdAt: Date
  // NOTE: Auto-deletes after 3 days (TTL index)
}

πŸ§ͺ Testing

# Run all tests
npm test

🚒 Deployment Information

This API is deployed on Render.com (free tier) with the following configuration:

  • Platform: Node.js
  • Database: MongoDB Atlas (cloud)
  • Auto-deploy: Enabled on push to main branch
  • Region: Automatic (closest to users)

Note for Users

  • The free tier spins down after 15 minutes of inactivity
  • First request after inactivity may take 20-30 seconds to respond
  • Subsequent requests will be fast
Made with ❀️ by Ishu6129

About

A secure banking API with ACID compliance, immutable ledger tracking, JWT authentication, and idempotent transactions built with Node.js and MongoDB.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors