Skip to content

akashkhedar/Echo-Backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

72 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Echo - Social Media Platform (Backend API)

Echo Backend

A robust, scalable Node.js backend API for the Echo social media platform, providing real-time chat, video calling, post management, and user authentication features. Built with Express.js, MongoDB, Socket.io, and Redis for optimal performance.

πŸš€ Live API

🌟 Key Features

πŸ” Authentication & Security

  • JWT-based Authentication with access & refresh tokens
  • Password Encryption using bcrypt
  • Email Verification system
  • Password Reset functionality
  • Rate Limiting for API protection
  • CORS Configuration for secure cross-origin requests
  • Cookie-based Session Management

πŸ’¬ Real-time Chat System

  • Socket.io Integration for instant messaging
  • Message Encryption/Decryption for privacy
  • Real-time Notifications for new messages
  • Group Conversations support
  • Online/Offline Status tracking
  • Message Read Receipts
  • File/Media Sharing capabilities

πŸ“ž Video & Audio Calling

  • WebRTC Signaling Server for peer-to-peer connections
  • Call Management (initiate, accept, decline, end)
  • Audio/Video Call Support
  • Call Notifications and status updates
  • ICE Candidate Exchange for connectivity

πŸ“± Social Media Features

  • Post Creation & Management with media upload
  • Like/Unlike functionality
  • Comment System with threaded replies
  • User Following/Followers system
  • Feed Generation based on connections
  • User Search with advanced filtering
  • Profile Management with customizable information

πŸ—„οΈ Data Management

  • MongoDB with Mongoose ODM
  • Redis for session storage and caching
  • Cloudinary for media storage and optimization
  • MeiliSearch for advanced search capabilities
  • Node-Cache for in-memory caching

πŸ—οΈ Technical Architecture

Core Technologies

  • Node.js - Runtime environment
  • Express.js 4.21.1 - Web framework
  • MongoDB 8.8.3 - NoSQL database
  • Mongoose - MongoDB object modeling
  • Socket.io 4.8.1 - Real-time communication
  • Redis 4.7.0 - In-memory data store
  • JWT - Authentication tokens

Security & Middleware

  • Helmet 8.0.0 - Security headers
  • CORS 2.8.5 - Cross-origin resource sharing
  • Express Rate Limit 7.4.1 - Request rate limiting
  • Express Validator 7.2.0 - Input validation
  • Cookie Parser 1.4.7 - Cookie handling

File & Media Handling

  • Multer 1.4.5 - File upload middleware
  • Cloudinary 2.5.1 - Cloud media storage
  • Node-Cache 5.1.2 - Memory caching

Communication & Search

  • Nodemailer 6.9.16 - Email service
  • MeiliSearch 0.50.0 - Full-text search engine
  • BCrypt 5.1.1 - Password hashing

πŸ“ Project Structure

Backend/
β”œβ”€β”€ index.js                 # Main server entry point
β”œβ”€β”€ package.json             # Dependencies and scripts
β”œβ”€β”€ .env                     # Environment variables
β”œβ”€β”€ controllers/             # Business logic controllers
β”‚   β”œβ”€β”€ AdminController/     # Admin operations
β”‚   β”‚   └── uploadAll.js     # Bulk data upload
β”‚   β”œβ”€β”€ AuthControllers/     # Authentication logic
β”‚   β”‚   β”œβ”€β”€ userLogin.js     # User login
β”‚   β”‚   β”œβ”€β”€ userRegister.js  # User registration
β”‚   β”‚   β”œβ”€β”€ userLogout.js    # User logout
β”‚   β”‚   β”œβ”€β”€ verifyUser.js    # Email verification
β”‚   β”‚   β”œβ”€β”€ forgetPassword.js # Password reset request
β”‚   β”‚   β”œβ”€β”€ verifyResetToken.js # Reset token validation
β”‚   β”‚   β”œβ”€β”€ updatePassword.js # Password update
β”‚   β”‚   └── loggedPassword.js # Logged-in password change
β”‚   β”œβ”€β”€ ChatControllers/     # Chat functionality
β”‚   β”‚   β”œβ”€β”€ chatList.js      # Get user conversations
β”‚   β”‚   └── fetchChats.js    # Fetch chat messages
β”‚   β”œβ”€β”€ PostControllers/     # Post management
β”‚   β”‚   β”œβ”€β”€ uploadPost.js    # Create new post
β”‚   β”‚   β”œβ”€β”€ feedPost.js      # Get user feed
β”‚   β”‚   β”œβ”€β”€ fetchPosts.js    # Fetch user posts
β”‚   β”‚   β”œβ”€β”€ fetchComments.js # Get post comments
β”‚   β”‚   β”œβ”€β”€ likePost.js      # Like/unlike posts
β”‚   β”‚   β”œβ”€β”€ postComment.js   # Add comments
β”‚   β”‚   └── deletePost.js    # Delete posts
β”‚   └── UserControllers/     # User management
β”‚       β”œβ”€β”€ userProfile.js   # Get user profile
β”‚       β”œβ”€β”€ userAbout.js     # Get user details
β”‚       β”œβ”€β”€ userBasic.js     # Basic user info
β”‚       β”œβ”€β”€ updateProfile.js # Update profile
β”‚       β”œβ”€β”€ searchUser.js    # Search users
β”‚       β”œβ”€β”€ followUser.js    # Follow users
β”‚       β”œβ”€β”€ unfollowUser.js  # Unfollow users
β”‚       β”œβ”€β”€ fetchFollowers.js # Get followers
β”‚       β”œβ”€β”€ fetchFollowing.js # Get following
β”‚       β”œβ”€β”€ removeFollower.js # Remove follower
β”‚       β”œβ”€β”€ checkExistingUser.js # Check user existence
β”‚       └── deleteAccount.js # Delete user account
β”œβ”€β”€ models/                  # Database schemas
β”‚   β”œβ”€β”€ user.js             # User model
β”‚   β”œβ”€β”€ post.js             # Post model
β”‚   β”œβ”€β”€ comment.js          # Comment model
β”‚   β”œβ”€β”€ conversation.js     # Conversation model
β”‚   └── message.js          # Message model
β”œβ”€β”€ routes/                  # API route definitions
β”‚   β”œβ”€β”€ authRoutes.js       # Authentication routes
β”‚   β”œβ”€β”€ userRoutes.js       # User management routes
β”‚   β”œβ”€β”€ postRoutes.js       # Post-related routes
β”‚   β”œβ”€β”€ chatRoutes.js       # Chat functionality routes
β”‚   └── adminRoute.js       # Admin operations routes
β”œβ”€β”€ middlewares/            # Custom middleware
β”‚   β”œβ”€β”€ cookieAuthentication.js # JWT auth middleware
β”‚   └── limiter.js          # Rate limiting middleware
β”œβ”€β”€ sockets/                # Socket.io event handlers
β”‚   β”œβ”€β”€ onConnection.js     # Main socket connection handler
β”‚   └── events/             # Individual socket events
β”‚       β”œβ”€β”€ online.js       # User online status
β”‚       β”œβ”€β”€ offline.js      # User offline status
β”‚       β”œβ”€β”€ sendMessage.js  # Send chat messages
β”‚       β”œβ”€β”€ readMsg.js      # Mark messages as read
β”‚       β”œβ”€β”€ joinAllRooms.js # Join chat rooms
β”‚       β”œβ”€β”€ callUser.js     # Initiate calls
β”‚       β”œβ”€β”€ callAccepted.js # Accept calls
β”‚       β”œβ”€β”€ declinedCall.js # Decline calls
β”‚       β”œβ”€β”€ cancelCall.js   # Cancel calls
β”‚       β”œβ”€β”€ endCall.js      # End calls
β”‚       β”œβ”€β”€ sendOffer.js    # WebRTC offer
β”‚       β”œβ”€β”€ sendAnswer.js   # WebRTC answer
β”‚       β”œβ”€β”€ sendNewOffer.js # New WebRTC offer
β”‚       β”œβ”€β”€ sendNewAnswer.js # New WebRTC answer
β”‚       β”œβ”€β”€ sendIceCandidate.js # ICE candidates
β”‚       β”œβ”€β”€ newPost.js      # New post notifications
β”‚       β”œβ”€β”€ deletePost.js   # Post deletion events
β”‚       β”œβ”€β”€ offlineMessages.js # Handle offline messages
β”‚       β”œβ”€β”€ removeOfflineMessages.js # Remove offline messages
β”‚       β”œβ”€β”€ redirectConvo.js # Redirect conversations
β”‚       └── leaveChat.js    # Leave chat rooms
β”œβ”€β”€ Utils/                  # Utility functions
β”‚   β”œβ”€β”€ mongoConnect.js     # MongoDB connection
β”‚   β”œβ”€β”€ redis.js           # Redis configuration
β”‚   β”œβ”€β”€ cloudinary.js      # Cloudinary setup
β”‚   β”œβ”€β”€ mail.js            # Email service
β”‚   β”œβ”€β”€ cookie.js          # JWT token utilities
β”‚   β”œβ”€β”€ cache.js           # Caching utilities
β”‚   β”œβ”€β”€ io.js              # Socket.io setup
β”‚   β”œβ”€β”€ sockets.js         # Socket configuration
β”‚   β”œβ”€β”€ encryptdecryptMsg.js # Message encryption
β”‚   β”œβ”€β”€ getRoomId.js       # Chat room ID generation
β”‚   └── meilisearchConnect.js # Search engine setup
└── public/                # Static files
    β”œβ”€β”€ temp/              # Temporary file storage
    └── templates/         # Email templates
        β”œβ”€β”€ verifyEmail.html # Email verification template
        └── forgetPassword.html # Password reset template

πŸ—„οΈ Database Schema

User Model

{
  email: String (unique, required),
  isVerified: Boolean (default: false),
  profileStatus: Boolean (default: false),
  password: String (hashed),
  username: String (unique, lowercase),
  fullname: String,
  dob: String,
  gender: String,
  bio: String,
  website: String,
  interests: String,
  follower: [ObjectId] (ref: 'user'),
  following: [ObjectId] (ref: 'user'),
  profileImage: String (default URL),
  coverImage: String (default URL),
  timestamps: true
}

Post Model

{
  userId: ObjectId (ref: 'user', required),
  caption: String,
  media: String (required),
  ratio: String (required),
  likes: [ObjectId] (ref: 'user'),
  comments: [ObjectId] (ref: 'comment'),
  timestamps: true
}

Conversation Model

{
  participants: [ObjectId] (ref: 'user', required),
  roomId: String,
  messages: [ObjectId] (ref: 'message'),
  timestamps: true
}

Message Model

{
  sender: ObjectId (ref: 'user', required),
  receiver: ObjectId (ref: 'user', required),
  conversationId: ObjectId (ref: 'conversation', required),
  message: String (encrypted, required),
  iv: String (encryption vector),
  read: Boolean (default: false),
  timestamps: true
}

Comment Model

{
  userId: ObjectId (ref: 'user', required),
  postId: ObjectId (ref: 'post', required),
  comment: String (required),
  timestamps: true
}

πŸ”Œ API Endpoints

Authentication Routes (/api/auth)

POST   /create                    # Register new user
POST   /verify                    # Verify email
POST   /login                     # User login
POST   /logout                    # User logout
POST   /forget-password           # Request password reset
GET    /verify-reset-token/:token # Verify reset token
POST   /update-password/:token    # Update password with token
POST   /update/logged/password    # Update password (logged in)

User Routes (/api/user)

GET    /profile/:username         # Get user profile
GET    /about                     # Get current user details
GET    /basic/:username           # Get basic user info
PUT    /update                    # Update user profile
GET    /search/:query             # Search users
POST   /follow                    # Follow user
POST   /unfollow                  # Unfollow user
GET    /followers/:username       # Get user followers
GET    /following/:username       # Get user following
POST   /remove/follower           # Remove follower
GET    /check/:username           # Check if user exists
DELETE /delete                    # Delete user account

Post Routes (/api/post)

POST   /upload                    # Create new post
GET    /feed                      # Get user feed
GET    /user/:username            # Get user posts
GET    /comments/:postId          # Get post comments
POST   /like                      # Like/unlike post
POST   /comment                   # Add comment to post
DELETE /:postId                   # Delete post

Chat Routes (/api/chat)

GET    /list/:userId              # Get user conversations
GET    /fetch/msg/:conversationId # Fetch chat messages

Admin Routes (/api/admin)

POST   /upload/all                # Bulk upload data

πŸ”„ Socket.io Events

Connection Events

// User Status
"online"; // User comes online
"offline"; // User goes offline

// Chat Events
"joinAllRooms"; // Join multiple chat rooms
"sendMessage"; // Send chat message
"receiveMsg"; // Receive chat message
"readMsg"; // Mark message as read
"offlineMessage"; // Handle offline messages
"rmOfflineMsg"; // Remove offline messages
"redirectConvo"; // Redirect to conversation

// Calling Events
"callUser"; // Initiate call
"receiveCall"; // Receive incoming call
"acceptedCall"; // Accept call
"callAccepted"; // Call accepted notification
"declinedCall"; // Decline call
"cancelledCall"; // Call cancelled
"CancelCall"; // Cancel ongoing call
"endCall"; // End call

// WebRTC Signaling
"sendOffer"; // Send WebRTC offer
"getOffer"; // Receive WebRTC offer
"sendAnswer"; // Send WebRTC answer
"getAnswer"; // Receive WebRTC answer
"sendNewOffer"; // Send new offer (renegotiation)
"sendNewAnswer"; // Send new answer (renegotiation)
"sendIceCandidate"; // Send ICE candidate
"getIceCandidate"; // Receive ICE candidate

// Post Events
"newPost"; // New post notification
"deletePost"; // Post deletion notification

πŸš€ Getting Started

Prerequisites

  • Node.js 16+
  • MongoDB
  • Redis
  • Cloudinary account
  • MeiliSearch (optional)

Installation

  1. Clone the repository

    git clone https://github.com/akashkhedar/Echo-Backend.git
    cd Echo-Backend
  2. Install dependencies

    npm install
  3. Environment Variables Create a .env file with the following variables:

    PORT=5000
    NODE_ENV=development
    
    # Database
    MONGODB_URI=mongodb://localhost:27017/echo
    
    # Redis
    REDIS_URL=redis://localhost:6379
    
    # JWT Secrets
    JWT_ACCESS_SECRET=your_access_secret
    JWT_REFRESH_SECRET=your_refresh_secret
    
    # Cloudinary
    CLOUDINARY_CLOUD_NAME=your_cloud_name
    CLOUDINARY_API_KEY=your_api_key
    CLOUDINARY_API_SECRET=your_api_secret
    
    # Email Service
    EMAIL_HOST=smtp.gmail.com
    EMAIL_PORT=587
    EMAIL_USER=[email protected]
    EMAIL_PASS=your_app_password
    
    # MeiliSearch
    MEILISEARCH_HOST=http://localhost:7700
    MEILISEARCH_API_KEY=your_meilisearch_key
  4. Start the server

    npm start

Development

# Start with nodemon for development
npx nodemon index.js

πŸ”§ Configuration

CORS Settings

const allowedOrigins = [
  "http://localhost:3000", // Development frontend
  "https://app.echo.linkpc.net", // Production frontend
];

Cookie Configuration

  • Access Token: 1 hour expiry, HTTP-only
  • Refresh Token: 7 days expiry, HTTP-only
  • Secure: True in production
  • SameSite: "None" in production, "Lax" in development

Rate Limiting

  • Auth Routes: Limited to prevent brute force attacks
  • General API: Standard rate limiting applied

πŸ›‘οΈ Security Features

Authentication Security

  • Password Hashing: BCrypt with salt rounds
  • JWT Tokens: Separate access and refresh tokens
  • Token Rotation: Automatic token refresh
  • Session Management: Redis-based session storage

Data Protection

  • Message Encryption: End-to-end message encryption
  • Input Validation: Express-validator for all inputs
  • SQL Injection: MongoDB's natural protection
  • XSS Protection: Helmet security headers

API Security

  • Rate Limiting: Prevents API abuse
  • CORS: Controlled cross-origin access
  • Cookie Security: HTTP-only, secure cookies
  • Environment Variables: Sensitive data protection

πŸ“Š Performance Optimizations

Caching Strategy

  • Node-Cache: In-memory caching for frequently accessed data
  • Redis: Session storage and distributed caching
  • MongoDB Indexing: Optimized database queries

File Management

  • Cloudinary: Optimized media storage and delivery
  • Multer: Efficient file upload handling
  • Temporary Storage: Automatic cleanup of temp files

Database Optimization

  • Connection Pooling: MongoDB connection management
  • Index Strategy: Optimized queries with proper indexing
  • Population: Efficient data fetching with Mongoose

πŸ§ͺ Testing

API Testing

  • Use Postman collection for comprehensive API testing
  • Authentication flow testing
  • Socket.io event testing
  • File upload testing

Load Testing

  • WebRTC signaling performance
  • Concurrent user handling
  • Database query optimization

πŸ“¦ Deployment

Production Setup

  1. Environment Configuration

    NODE_ENV=production
  2. Database Setup

    • MongoDB Atlas or self-hosted MongoDB
    • Redis Cloud or self-hosted Redis
  3. Media Storage

    • Cloudinary for image/video storage
    • CDN configuration for optimal delivery
  4. SSL Certificate

    • HTTPS required for WebRTC
    • Secure cookie configuration

Docker Deployment

FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 5000
CMD ["npm", "start"]

πŸ” Monitoring & Logging

Application Monitoring

  • Error logging and tracking
  • Performance metrics
  • Socket connection monitoring
  • Database query performance

Health Checks

  • Database connectivity
  • Redis connection status
  • External service availability

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Development Guidelines

  • Follow REST API conventions
  • Implement proper error handling
  • Add input validation for all endpoints
  • Write comprehensive tests
  • Document new features

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.

πŸ”— Related Projects

πŸ“ž Support

For support, email [email protected] or create an issue on GitHub.

πŸ™ Acknowledgments

  • Express.js - Fast, unopinionated web framework
  • Socket.io - Real-time communication
  • MongoDB - Flexible NoSQL database
  • Cloudinary - Media management platform
  • Redis - In-memory data structure store

Built with ❀️ by Akash Khedar

Echo Backend - Powering real-time social connections

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published