BorrowEase is a comprehensive peer-to-peer lending platform that connects borrowers and lenders in a secure, transparent, and user-friendly environment. Built with modern web technologies, it provides a complete ecosystem for loan management, credit scoring, real-time communication, and administrative oversight.
- Firebase Authentication with secure token-based system
- Multi-role Support: Borrowers, Lenders, and Administrators
- Profile Management with KYC verification
- Protected Routes with role-based access control
- Loan Requests: Borrowers can create detailed loan applications
- Loan Approval: Multi-stage approval process with admin oversight
- Funding System: Lenders can fund approved loans
- Repayment Tracking: Automated payment processing with Razorpay
- Interest Calculation: Dynamic interest rate calculations
- Loan History: Comprehensive tracking for all parties
- Comprehensive Dashboard with real-time statistics
- Loan Moderation: Review and approve/reject loan applications
- KYC Management: Verify user identities and documents
- User Management: Monitor all platform users
- Dispute Resolution: Handle user complaints and issues
- Credit Analytics: Platform-wide credit score insights
- Multi-factor Algorithm considering:
- Payment History (35%)
- Credit Utilization (30%)
- Credit History Length (15%)
- Loan Diversity (10%)
- Trust Factors (10%)
- Real-time Updates based on user activity
- Visual Dashboard with circular progress indicators
- Credit Improvement Tips and recommendations
- Lender Risk Assessment tools
- Socket.IO Integration for instant messaging
- Loan-based Chat Rooms between borrowers and lenders
- Real-time Notifications for important events
- Message History and chat persistence
- Multi-category Disputes: Payment, Communication, Fraud, Technical, Other
- Priority Levels: Low, Medium, High, Urgent
- Admin Resolution Interface with response tracking
- Status Management: Open โ In-Progress โ Resolved/Rejected
- User-friendly Reporting interface
- Real-time Notifications for loan updates
- Email Integration for important alerts
- In-app Notification Bell with unread counts
- Notification History and management
- Razorpay Integration for secure payments
- Multiple Payment Methods support
- Payment Tracking and history
- Automated Receipt Generation
- Comprehensive AI Dashboard with multiple analysis modules
- Real-time Risk Scoring using machine learning algorithms
- Intelligent Loan Recommendations for lenders
- Advanced Fraud Detection system
- AI-Powered Repayment Prediction
- Borrower Assessment Tools with multi-factor analysis
- Platform Analytics with AI-driven insights
-
Multi-Model AI System with different algorithms:
- Comprehensive Model: Overall risk assessment
- Quick Assessment: Fast evaluation for urgent decisions
- Conservative Model: Low-risk focused analysis
- Aggressive Model: High-return opportunity identification
-
Real-time Scoring Metrics:
- Loan-Specific Risk Score (0-100 scale)
- Borrower Trust Score with historical data
- Payment History Analysis with pattern recognition
- Income Verification through AI document analysis
- Credit Utilization intelligent monitoring
- Personalized Loan Matching based on lender preferences
- Risk Tolerance Configuration:
- Conservative (Low Risk)
- Balanced (Medium Risk)
- Aggressive (High Risk)
- Smart Filtering System:
- Minimum confidence thresholds
- Maximum risk limits
- Amount range preferences
- Only AI-approved loans option
- Expected Return Calculations with confidence intervals
- Timeline Predictions for loan processing and repayment
- Real-time Fraud Monitoring with multiple detection layers
- Fraud Type Classification:
- Identity Fraud Detection
- Income Manipulation Detection
- Document Forgery Recognition
- Pattern-based Anomaly Detection
- Risk Assessment Metrics:
- Fraud probability scoring
- Confidence levels for each detection
- Automated action recommendations
- Prevention Statistics:
- Total applications checked
- Fraud cases flagged
- Financial loss prevented
- AI accuracy rates
- Repayment Probability Analysis using historical data
- Timeline Predictions:
- Optimistic scenario (best case)
- Realistic scenario (most likely)
- Pessimistic scenario (worst case)
- Factor Analysis:
- Positive influencing factors with weight calculations
- Risk factors identification and mitigation
- Payment behavior pattern analysis
- Smart Recommendations:
- Early reminder scheduling
- Payment incentive suggestions
- Risk mitigation strategies
- Loan Performance Metrics with AI-driven analysis
- Borrower Behavior Patterns identification
- Market Trend Analysis and predictions
- Risk Distribution across the platform
- Success Rate Optimization recommendations
- Lender Portfolio Analysis with performance insights
- Real-time AI Assessment on every loan card
- Visual Risk Indicators with color-coded scoring
- AI Recommendation Badges:
- โ Fund (AI Approved) - Green
- โ Fund (AI Rejected) - Red
- Standard funding options
- Smart Details Display:
- Confidence percentages
- Suggested interest rates
- Key risk factors summary
- Top AI recommendations
- One-click AI Analysis with detailed breakdowns
- Multi-tab Interface for comprehensive analysis:
- Risk Assessment Tab: Overall platform risk analysis
- Borrower Analysis Tab: Individual borrower evaluation tools
- Platform Analytics Tab: System-wide performance metrics
- Fraud Detection Tab: Security monitoring dashboard
- AI Models Tab: Model performance and selection
- Live Risk Scoring as loans are created
- Dynamic Fraud Monitoring with instant alerts
- Automatic Model Updates based on new data
- Instant Recommendation Generation for new loan requests
- Real-time Dashboard Updates with WebSocket integration
- Continuous Learning from loan outcomes
- Model Performance Tracking with accuracy metrics
- Feedback Integration from lender decisions
- Historical Data Analysis for pattern improvement
- Adaptive Risk Thresholds based on market conditions
- Intelligent Loan Matching for optimal pairings
- Smart Notification System with AI-driven priorities
- Personalized Dashboard with relevant AI insights
- Predictive User Interface with proactive suggestions
- Context-aware Recommendations based on user behavior
Server/
โโโ config/
โ โโโ db.js # MongoDB connection
โโโ middleware/
โ โโโ adminAuth.js # Admin authentication
โโโ models/
โ โโโ userModel.js # User schema
โ โโโ loanModel.js # Loan schema
โ โโโ disputeModel.js # Dispute schema
โ โโโ chatModel.js # Chat message schema
โ โโโ notificationModel.js # Notification schema
โ โโโ auditLogModel.js # Audit trail schema
โโโ routes/
โ โโโ userRoutes.js # User management
โ โโโ loanroutes.js # Loan operations
โ โโโ disputeRoutes.js # Dispute handling
โ โโโ chatRoutes.js # Chat functionality
โ โโโ notificationRoutes.js # Notifications
โ โโโ paymentRoutes.js # Payment processing
โ โโโ kycRoutes.js # KYC verification
โ โโโ creditRoutes.js # Credit scoring
โ โโโ aiRoutes.js # AI features
โโโ utils/
โ โโโ auditLogger.js # Audit logging
โ โโโ interestCalculator.js # Interest calculations
โโโ firebase.js # Firebase configuration
โโโ server.js # Main server file
Client/
โโโ public/
โโโ src/
โ โโโ Components/
โ โ โโโ Home.jsx # Landing page
โ โ โโโ Login.jsx # Authentication
โ โ โโโ BorrowerDashboard.jsx # Borrower interface
โ โ โโโ LenderDashboard.jsx # Lender interface
โ โ โโโ AdminDashboard.jsx # Admin overview
โ โ โโโ AdminLoanModeration.jsx # Loan approval
โ โ โโโ AdminKYCManagement.jsx # KYC verification
โ โ โโโ AdminUsers.jsx # User management
โ โ โโโ DisputeModal.jsx # Dispute creation
โ โ โโโ DisputesManagement.jsx # Admin dispute handling
โ โ โโโ CreditScore.jsx # Credit dashboard
โ โ โโโ ChatRoom.jsx # Real-time messaging
โ โ โโโ NotificationBell.jsx # Notification system
โ โ โโโ ComprehensiveAIDashboard.jsx # AI analytics hub
โ โ โโโ EnhancedLoanCard.jsx # AI-powered loan cards
โ โ โโโ AILoanRecommendationEngine.jsx # Smart loan matching
โ โ โโโ AIFraudDetectionDashboard.jsx # Fraud monitoring
โ โ โโโ AIRepaymentPredictor.jsx # Repayment analysis
โ โ โโโ AIRiskAssessment.jsx # Risk evaluation
โ โ โโโ ...
โ โโโ api/
โ โ โโโ api.js # API client
โ โ โโโ loanApi.js # Loan operations
โ โ โโโ notificationApi.js # Notification API
โ โโโ contexts/
โ โ โโโ SocketContext.jsx # Socket.IO context
โ โโโ firebase.js # Firebase client
โ โโโ main.jsx # App entry point
โโโ index.html
โโโ vite.config.js
- Node.js (v16 or higher)
- MongoDB (v4.4 or higher)
- Firebase account
- Razorpay account (for payments)
-
Clone the repository
git clone https://github.com/Programmer60/BorrowEase.git cd BorrowEase -
Backend Setup
cd Server npm install -
Frontend Setup
cd ../Client npm install
- Firebase Setup
- Create a Firebase project at Firebase Console
- Enable Authentication (Email/Password)
- Create a Service Account key in Firebase โ Project Settings โ Service Accounts โ Generate new private key.
- Do NOT commit this file. Instead, set these environment variables on the server:
FIREBASE_PROJECT_IDFIREBASE_CLIENT_EMAIL- Either
FIREBASE_PRIVATE_KEY_BASE64(preferred; base64-encode the full private key) orFIREBASE_PRIVATE_KEY(escaped newlines as \n)
- For the client (web SDK), set the
VITE_FIREBASE_*values from your Firebase Web App settings inClient/.env.
-
MongoDB Setup
- Create MongoDB database (local or Atlas)
- Update connection string in
Server/config/db.js
-
Razorpay Setup
- Create Razorpay account
- Get API keys from dashboard
- Add to environment variables
-
Environment Variables
Copy the provided examples and fill in values (never commit real secrets):
- Server:
Server/.env.exampleโServer/.env - Client:
Client/.env.exampleโClient/.env
Minimal examples below (refer to the examples in the repo for the full list):
Server/.env
PORT=5000
# Database
MONGO_URI=your_mongodb_connection_string
# CORS allowlist (comma-separated)
CORS_ORIGIN=http://localhost:5173,https://your-frontend-domain.com
# Firebase Admin (server-side)
FIREBASE_PROJECT_ID=your_firebase_project_id
FIREBASE_CLIENT_EMAIL=your_service_account_email@your-project.iam.gserviceaccount.com
# Prefer base64 to avoid newline escaping issues
FIREBASE_PRIVATE_KEY_BASE64=base64_of_your_private_key
# Or use the raw key with \n newlines escaped
# FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
# Cloudinary (server-side signing)
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret
# Payments
RAZORPAY_KEY_ID=your_razorpay_key_id
RAZORPAY_KEY_SECRET=your_razorpay_key_secretClient/.env
VITE_FIREBASE_API_KEY=your_firebase_api_key
VITE_FIREBASE_AUTH_DOMAIN=your_project.firebaseapp.com
VITE_FIREBASE_PROJECT_ID=your_firebase_project_id
VITE_FIREBASE_STORAGE_BUCKET=your_project.appspot.com
VITE_FIREBASE_MESSAGING_SENDER_ID=your_sender_id
VITE_FIREBASE_APP_ID=your_app_id-
Start the Backend Server
cd Server npm start -
Start the Frontend Development Server
cd Client npm run dev -
Access the Application
- Frontend:
http://localhost:5173 - Backend API:
http://localhost:5000
- Frontend:
- Navigate to AI Dashboard: Available in navigation for lenders and admins
- Multi-tab Interface: Switch between different AI analysis modules
- Real-time Updates: All AI assessments update automatically
- Automatic Assessment: AI analysis runs automatically for lenders
- Manual Refresh: Click "Get AI Assessment" for on-demand analysis
- Color-coded Indicators:
- ๐ข Green: AI Approved (Low Risk)
- ๐ต Blue: Moderate Risk
- ๐ก Yellow: Higher Risk
- ๐ด Red: AI Rejected (High Risk)
- Set Preferences: Configure risk tolerance and amount ranges
- AI Matching: System finds optimal loan opportunities
- Confidence Filtering: Adjust minimum confidence levels
- One-click Investment: Direct funding from recommendations
- Real-time Alerts: Automatic fraud detection notifications
- Admin Actions: Resolve alerts with recommended actions
- Performance Tracking: Monitor system effectiveness
- Risk Trends: View borrower risk score evolution
- Timeline Forecasting: View optimistic, realistic, and pessimistic scenarios
- Factor Analysis: Understand what influences repayment probability
- Smart Reminders: AI suggests optimal reminder timing
- Risk Mitigation: Get recommendations to improve repayment likelihood
- Create and manage loan requests
- View loan history and status
- Make payments through integrated system
- Chat with lenders for funded loans
- Monitor personal credit score
- Submit disputes for issues
- Browse and filter loan requests
- View borrower credit scores
- Access AI loan recommendations with smart matching
- Real-time AI risk assessment on all loans
- Fund approved loans with AI guidance
- Track funded loan performance
- AI-powered repayment predictions for funded loans
Issue observed
- Clicking โFailureโ in Razorpay sometimes showed โCannot GET /api/payment/callbackโ, or redirected borrowers to /lender where a role-guard popped โAccess denied. You are not a lender.โ
What we changed (server)
- Added GET /api/payment/callback to handle Razorpay GET-style redirects on failure, mirroring the POST handler.
- Both POST and GET /api/payment/callback now render a small branded interstitial page and then auto-redirect back to the SPA with clear query params.
- POST /api/payment/create-order now returns checkoutUrl that points to the server-hosted checkout page and includes a fallback role parameter:
- Repayment โ ?fallback=borrower
- Funding โ ?fallback=lender
- Server-hosted checkout pages forward fallback into Razorpayโs callback_url so, even if orderId is missing, the callback knows which dashboard to return to.
- Callback picks destination by reading the orderโs notes.isRepayment; if unavailable, it falls back to the ?fallback value.
What we changed (client)
- BorrowerDashboard and LenderDashboard:
- Show a friendly banner after redirect based on ?payment=success|failed&reason=...
- Persist last_order_id and, if the user closes the gateway without redirect, poll GET /api/payment/status/:orderId once to resolve status.
- Clean the query string after showing the banner.
Expected behavior
- On cancel/failure: you briefly see an interstitial page, then land on /borrower or /lender with a banner and URL like:
- /borrower?payment=failed&order=order_...&code=...&reason=...
- /lender?payment=failed&order=order_...&code=...&reason=...
- On success: you land on the correct dashboard with ?payment=success and a success banner.
Endpoints involved
- POST /api/payment/create-order โ returns { id, amount, โฆ, checkoutUrl }
- GET /api/payment/checkout/:orderId[?fallback=role]
- POST /api/payment/callback (success/failure)
- GET /api/payment/callback (failure or when gateway uses GET)
- GET /api/payment/status/:orderId (dashboard polling fallback)
Quick test
- Start backend and frontend.
- As a borrower, initiate a repayment and click Failure in Razorpay โ you should be redirected to /borrower with a โPayment failedโ banner.
- As a lender, initiate funding and click Failure โ redirected to /lender with a โPayment failedโ banner.
- Close the gateway without redirect โ on next load, dashboard polls status for last_order_id and shows the proper banner.
Troubleshooting
- If you see โCannot GET /api/payment/callbackโ, ensure the API has the new GET route and has been restarted.
- If redirected to the wrong dashboard, check that checkoutUrl contains ?fallback=borrower or ?fallback=lender and that callback_url also includes the same fallback.
- See PAYMENT_DEBUG_GUIDE.md for deeper diagnostics.
- Communicate with borrowers
- Submit disputes for problems
- Complete platform oversight
- Approve/reject loan applications
- Manage KYC verification process
- Handle dispute resolution
- Comprehensive AI analytics dashboard access
- Advanced fraud detection monitoring
- AI model performance tracking
- Platform-wide risk assessment tools
- Monitor platform statistics
- Manage user accounts
- Access credit analytics
POST /api/users/register # User registration
POST /api/users/login # User login
GET /api/users/me # Get current user
PUT /api/users/profile # Update profile
POST /api/loans # Create loan request
GET /api/loans # Get all loans (admin)
GET /api/loans/my-loans # Get user's loans
GET /api/loans/funded # Get funded loans
PUT /api/loans/:id/approve # Approve loan (admin)
PUT /api/loans/:id/fund # Fund loan (lender)
PUT /api/loans/:id/repay # Repay loan (borrower)
GET /api/credit/score # Get user's credit score
GET /api/credit/score/:userId # Get specific user's score
GET /api/credit/history # Get credit history
GET /api/credit/admin/stats # Get platform credit stats
POST /api/disputes # Create dispute
GET /api/disputes # Get disputes
GET /api/disputes/loan/:id # Get loan disputes
PATCH /api/disputes/:id/resolve # Resolve dispute (admin)
GET /api/disputes/admin/stats # Get dispute statistics
GET /api/chat/:loanId # Get chat messages
POST /api/chat/:loanId # Send message
GET /api/notifications # Get notifications
PUT /api/notifications/:id/read # Mark as read
POST /api/ai/assess-borrower # AI borrower risk assessment
POST /api/ai/recommend-loans # Get AI loan recommendations
GET /api/ai/fraud-detection # Fraud detection analysis
GET /api/ai/risk-scores # Platform risk scoring
POST /api/ai/predict-repayment # Repayment probability prediction
GET /api/ai/platform-analytics # AI-driven platform insights
GET /api/ai/risk-assessment # Comprehensive risk analysis
POST /api/ai/fraud-alerts/:id/resolve # Resolve fraud alerts
GET /api/ai/model-performance # AI model accuracy metrics
POST /api/ai/borrower-analysis # Individual borrower evaluation
- JWT Token Authentication with Firebase
- Role-based Access Control (RBAC)
- Input Validation and sanitization
- SQL Injection Protection through MongoDB
- XSS Protection with proper data handling
- CORS Configuration for secure cross-origin requests
- Audit Logging for sensitive operations
- Secure Payment Processing through Razorpay
See SECURITY.md for public-repo readiness and a secrets hygiene checklist.
- Mobile-first Approach with Tailwind CSS
- Progressive Web App capabilities
- Cross-browser Compatibility
- Adaptive UI Components
- Touch-friendly Interface
// AI Risk Assessment Models
const aiModels = {
comprehensive: {
name: "Comprehensive Risk Model",
accuracy: 94.2,
factors: ["creditHistory", "paymentBehavior", "incomeStability", "loanPurpose"],
weightings: { creditHistory: 0.35, paymentBehavior: 0.30, income: 0.25, other: 0.10 }
},
quickAssessment: {
name: "Quick Assessment Model",
accuracy: 89.1,
speed: "< 1 second",
factors: ["creditScore", "paymentHistory", "basicVerification"]
},
fraudDetection: {
name: "Fraud Detection Model",
accuracy: 96.8,
detectionTypes: ["identity", "income", "document", "behavioral"]
}
};// Real-time AI Assessment
const fetchAIAssessment = async (borrowerData) => {
const response = await API.post('/ai/assess-borrower', {
borrowerId: borrowerData.id,
loanAmount: borrowerData.amount,
loanPurpose: borrowerData.purpose,
modelType: 'comprehensive'
});
return response.data;
};
// Fraud Detection
const checkFraud = async (applicationData) => {
const response = await API.post('/ai/fraud-detection', {
applicantData: applicationData,
documentImages: applicationData.documents,
behavioralMetrics: applicationData.behavior
});
return response.data;
};// Enhanced Loan Card with AI
const EnhancedLoanCard = ({ loan, showAIFeatures = true }) => {
const [aiAssessment, setAiAssessment] = useState(null);
const [loading, setLoading] = useState(false);
// Auto-fetch AI assessment for lenders
useEffect(() => {
if (showAIFeatures && userRole === 'lender') {
fetchAIAssessment();
}
}, [loan.borrowerId]);
// Real-time scoring with color-coded indicators
const getScoreColor = (score) => {
if (score >= 80) return 'text-green-600 bg-green-50';
if (score >= 60) return 'text-blue-600 bg-blue-50';
return 'text-red-600 bg-red-50';
};
};// Comprehensive AI Dashboard
const ComprehensiveAIDashboard = () => {
const [activeTab, setActiveTab] = useState('risk-assessment');
const [aiModels, setAiModels] = useState([]);
const [fraudAlerts, setFraudAlerts] = useState([]);
const [platformAnalytics, setPlatformAnalytics] = useState(null);
// Multi-tab AI interface
const tabs = [
{ id: 'risk-assessment', component: RiskAssessmentTab },
{ id: 'fraud-detection', component: FraudDetectionTab },
{ id: 'loan-recommendations', component: RecommendationEngine },
{ id: 'platform-analytics', component: AnalyticsTab }
];
};- ESLint Configuration for code standards
- Prettier Integration for formatting
- Component-based Architecture
- Modular API Design
- Error Handling throughout the application
- Lazy Loading for route components
- Image Optimization with modern formats
- Bundle Splitting with Vite
- Database Indexing for faster queries
- Caching Strategies for API responses
# Build for production
npm run build
# Set environment variables
# Deploy using platform-specific commands# Build for production
npm run build
# Deploy dist folder
# Configure environment variables- MongoDB Atlas for cloud database
- Proper indexing for performance
- Backup strategies for data protection
- AI-powered Risk Assessment with multiple machine learning models
- Intelligent Fraud Detection with real-time monitoring
- Smart Loan Recommendations based on lender preferences
- Repayment Prediction using historical data analysis
- Comprehensive AI Dashboard with multiple analysis modules
- Enhanced Loan Cards with real-time AI integration
- Platform Analytics with AI-driven insights
- Deep Learning Models for more accurate predictions
- Natural Language Processing for document analysis
- Computer Vision for ID and document verification
- Predictive Market Analysis for interest rate optimization
- Behavioral Analysis for enhanced fraud detection
- Automated Loan Approval with minimal human intervention
- Voice Recognition for customer verification
- Sentiment Analysis from chat communications
- Mobile Applications (React Native)
- Multi-currency Support for international users
- Integration with Banking APIs for verification
- Blockchain Integration for transparency
- Advanced Risk Assessment tools
- Regulatory Compliance modules
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Developer: Shivam Mishra
- Project Type: Full-stack Web Application
- Development Period: 2025
For support and questions:
- Create an issue in the GitHub repository
- Contact the development team
- Check the documentation for common solutions
Built with โค๏ธ by Shivam Mishra
BorrowEase - Making peer-to-peer lending simple, secure, and transparent.