Skip to content

CodeSmithsLab/moneymitra-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

21 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Money Mitra Backend API

A Next.js-based backend API for Money Mitra, a financial management platform that provides AI-powered financial advice, user authentication, and personalized financial tracking.

πŸ“‹ Project Description

Money Mitra Backend is a RESTful API built with Next.js App Router that serves as the core backend infrastructure for the Money Mitra financial management application. The platform combines secure user authentication with AI-powered financial advisory capabilities using Google's Gemini AI.

Key Features

  • User Authentication System

    • JWT-based session management
    • Secure password hashing with bcrypt
    • Sign up, sign in, and sign out endpoints
    • HTTP-only cookie authentication
  • User Management

    • Role-based access control (student, teacher, admin)
    • User profiles with financial tracking metrics (points, rank, accuracy)
    • Subscription plans (free, pro)
    • Two-factor authentication support
  • AI Financial Advisor

    • Powered by Google Gemini 2.5 Flash
    • Specialized financial advice on budgeting, saving, and investing
    • Real-time chat-based interactions
  • Database Integration

    • MongoDB with Mongoose ODM
    • Connection pooling and caching
    • Optimized query performance

πŸ› οΈ Tech Stack

  • Framework: Next.js 16.1.1 (App Router)
  • Runtime: Node.js
  • Database: MongoDB
  • ODM: Mongoose 9.1.3
  • Authentication: JWT (jsonwebtoken)
  • Password Security: bcrypt 6.0.0
  • AI Integration: Google Generative AI (Gemini 2.5 Flash)
  • Additional: Ollama support

πŸ“ Project Structure

backend/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ route.js                 # Root API route
β”‚   β”‚   └── api/
β”‚   β”‚       β”œβ”€β”€ route.js             # API index
β”‚   β”‚       β”œβ”€β”€ ai/
β”‚   β”‚       β”‚   └── route.js         # AI chat endpoint
β”‚   β”‚       β”œβ”€β”€ auth/
β”‚   β”‚       β”‚   β”œβ”€β”€ sign-in/
β”‚   β”‚       β”‚   β”‚   └── route.js     # User login
β”‚   β”‚       β”‚   β”œβ”€β”€ sign-out/
β”‚   β”‚       β”‚   β”‚   └── route.js     # User logout
β”‚   β”‚       β”‚   └── sign-up/
β”‚   β”‚       β”‚       └── route.js     # User registration
β”‚   β”‚       └── user/
β”‚   β”‚           └── route.js         # User profile endpoint
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   └── dbConnect.js             # MongoDB connection handler
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   └── userModel.js             # User schema definition
β”‚   └── utils/
β”‚       β”œβ”€β”€ bcryptUtils.js           # Password hashing utilities
β”‚       └── getUserSession.js        # Session verification helper
β”œβ”€β”€ .env.local                       # Environment variables (create this)
β”œβ”€β”€ next.config.mjs                  # Next.js configuration
β”œβ”€β”€ jsconfig.json                    # JavaScript configuration
β”œβ”€β”€ package.json                     # Project dependencies
└── README.md                        # This file

πŸš€ Getting Started

Prerequisites

Before setting up the project locally, ensure you have the following installed:

  • Node.js (v18.0.0 or higher) - Download here
  • npm, yarn, or pnpm package manager
  • MongoDB (local instance or MongoDB Atlas account)
  • Google Gemini API Key - Get one here

Installation

1. Clone the Repository

git clone <repository-url>
cd backend

2. Install Dependencies

npm install
# or
yarn install
# or
pnpm install

3. Set Up MongoDB

Choose one of the following options:

Option A: Local MongoDB Installation

Linux (Ubuntu/Debian):

sudo apt-get update
sudo apt-get install -y mongodb
sudo systemctl start mongodb
sudo systemctl enable mongodb

macOS (using Homebrew):

brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community

Windows:

  • Download MongoDB Community Server from MongoDB Download Center
  • Run the installer and follow the setup wizard
  • MongoDB will start automatically as a Windows Service

Verify MongoDB is running:

mongosh

Option B: MongoDB Atlas (Cloud)

  1. Visit MongoDB Atlas
  2. Create a free account and cluster
  3. Whitelist your IP address
  4. Create a database user
  5. Get your connection string

4. Configure Environment Variables

Create a .env.local file in the project root:

touch .env.local

Add the following environment variables:

# MongoDB Connection
MONGODB_URI=mongodb://localhost:27017/money-mitra
# or for MongoDB Atlas:
# MONGODB_URI=mongodb+srv://<username>:<password>@<cluster>.mongodb.net/money-mitra

# JWT Secret (use a strong random string)
JWT_SECRET=your-super-secret-jwt-key-here

# Google Gemini API Key
GEMINI_API_KEY=your-gemini-api-key-here

# Frontend URL (for CORS)
FRONTEND_URL=http://localhost:3000

# Environment
NODE_ENV=development

Generate a secure JWT secret:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

5. Start the Development Server

npm run dev

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

Building for Production

# Build the application
npm run build

# Start the production server
npm start

πŸ”Œ API Endpoints

Authentication

Endpoint Method Description Request Body Response
/api/auth/sign-up POST Register a new user { firstName, lastName, email, password, role } JWT token in HTTP-only cookie
/api/auth/sign-in POST Authenticate existing user { email, password } JWT token in HTTP-only cookie
/api/auth/sign-out POST Invalidate user session - Clears authentication cookie

User

Endpoint Method Description Auth Required Response
/api/user GET Get authenticated user profile Yes (cookie) User data (password excluded)

AI Assistant

Endpoint Method Description Request Body Response
/api/ai POST Get financial advice from AI { message: "your question" } { success, reply }

πŸ” Authentication Flow

  1. User registers via /api/auth/sign-up with credentials
  2. Password is hashed using bcrypt (10 salt rounds)
  3. JWT token is generated with user ID, email, and role
  4. Token is stored in HTTP-only cookie (expires in 1 day)
  5. Subsequent requests automatically include cookie
  6. Protected routes verify token using getUserSession utility

πŸ—ƒοΈ Database Schema

User Model

Field Type Required Default Description
firstName String Yes - User's first name
lastName String No "" User's last name
email String Yes - Unique email address
plan String No "free" Subscription plan (free, pro)
points Number No 0 User points/credits
rank Number No 0 User ranking
accuracy Number No 0 Performance accuracy metric
twoFactorEnabled Boolean No false 2FA status
hashedPassword String Yes - bcrypt hashed password
role String No "student" User role (student, teacher, admin)
createdAt Date Auto - Account creation timestamp
updatedAt Date Auto - Last update timestamp

πŸ”§ Configuration

CORS Setup

The API is configured to accept requests from the frontend URL specified in FRONTEND_URL. CORS headers are set in next.config.mjs:

  • Credentials: Enabled
  • Origin: Value from FRONTEND_URL env variable
  • Methods: GET, DELETE, PATCH, POST, PUT
  • Headers: Accept, Content-Type

MongoDB Connection

The database uses connection pooling and caching to optimize performance:

  • Connection is established on first request
  • Cached globally and reused across invocations
  • Prevents connection pooling issues in serverless environments

πŸ§ͺ Testing the API

Sign Up Example

curl -X POST http://localhost:3000/api/auth/sign-up \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com",
    "password": "securePassword123",
    "role": "student"
  }'

Sign In Example

curl -X POST http://localhost:3000/api/auth/sign-in \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "securePassword123"
  }' \
  -c cookies.txt

Get User Profile Example

curl -X GET http://localhost:3000/api/user \
  -b cookies.txt

AI Chat Example

curl -X POST http://localhost:3000/api/ai \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What are some tips for saving money?"
  }'

πŸ”’ Security Best Practices

  • βœ… Passwords hashed with bcrypt (never stored in plain text)
  • βœ… JWT tokens in HTTP-only cookies (XSS protection)
  • βœ… Secure cookies in production (HTTPS only)
  • βœ… CORS restricted to trusted frontend origin
  • βœ… Environment variables for sensitive credentials
  • βœ… Server-side validation on all inputs
  • ⚠️ Ensure .env.local is in .gitignore
  • ⚠️ Use strong, random JWT_SECRET in production
  • ⚠️ Enable HTTPS in production environments

πŸ“¦ Dependencies

Core Dependencies

  • next@16.1.1 - Next.js framework
  • mongoose@9.1.3 - MongoDB ODM
  • jsonwebtoken@9.0.3 - JWT token management
  • bcrypt@6.0.0 - Password hashing
  • @google/generative-ai@0.24.1 - Google Gemini AI integration
  • ollama@0.6.3 - Local LLM support

πŸ› Troubleshooting

MongoDB Connection Error

Error: Please define the MONGODB_URI environment variable in .env.local

Solution: Create .env.local file and add MONGODB_URI variable.

MongoDB Server Not Running

Check Status:

mongosh --eval "db.adminCommand('ping')"

Start MongoDB:

# Linux
sudo systemctl start mongodb

# macOS
brew services start mongodb-community

Port Already in Use

npm run dev -- -p 3001

JWT Verification Fails

Ensure JWT_SECRET in .env.local matches the secret used to sign tokens.

CORS Errors

Verify FRONTEND_URL environment variable matches your frontend's origin.

πŸš€ Deployment

Environment Variables

Ensure the following are set in your production environment:

MONGODB_URI=<your-production-mongodb-uri>
JWT_SECRET=<strong-random-secret>
GEMINI_API_KEY=<your-gemini-api-key>
FRONTEND_URL=<your-frontend-production-url>
NODE_ENV=production

Deploy to Vercel

The easiest way to deploy is using Vercel:

npm install -g vercel
vercel

Or connect your repository on the Vercel dashboard for automatic deployments.

🀝 Contributing

  1. Fork the repository
  2. Create a 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

πŸ“ Additional Resources

πŸ“„ License

This project is private and proprietary.

πŸ‘₯ Support

For issues and questions, please contact the development team.


Built with ❀️ for Money Mitra

About

Backend

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published