Skip to content

A TypeScript/Node.js backend for a sophisticated AI image generation platform that integrates Stable Diffusion models with comprehensive user management, payment processing, Discord bot integration, and community features.

Notifications You must be signed in to change notification settings

MH-PAVEL/bashable-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

2 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŽจ Bashable AI - Advanced AI Image Generation Platform

A TypeScript/Node.js backend for a sophisticated AI image generation platform that integrates Stable Diffusion models with comprehensive user management, payment processing, Discord bot integration, and community features.

๐Ÿš€ What It Does

Bashable AI is a production-ready backend service that powers an AI image generation platform similar to Midjourney or DALL-E. It provides a complete ecosystem for users to generate, share, and monetize AI-generated images using various Stable Diffusion models. The platform includes user authentication, credit-based billing, community features, Discord integration, and comprehensive admin tools.

๐ŸŽฏ Key Features

Core Functionality

  • AI Image Generation: Integration with multiple Stable Diffusion models (SFW/NSFW)
  • Real-time Processing: WebSocket-based real-time image generation status updates
  • Multi-model Support: Support for 9+ different Stable Diffusion checkpoints
  • Image Upscaling: Advanced image enhancement capabilities
  • Prompt Validation: AI-powered content filtering and moderation

User Management & Authentication

  • Multi-provider OAuth: Google, Discord, Microsoft, Apple, and local authentication
  • Role-based Access Control: User, Moderator, and Admin roles with granular permissions
  • Email & Mobile Verification: Comprehensive user verification system
  • Profile Management: Avatar uploads, user profiles, and social features

Payment & Monetization

  • Credit System: Flexible credit-based billing with auto-recharge
  • Multiple Payment Gateways: Stripe and Coinbase Commerce integration
  • Subscription Management: Automated payment processing and webhook handling
  • Tipping System: User-to-user tipping functionality

Community & Social Features

  • Image Sharing: Public/private image sharing with social features
  • Community Models: User-submitted model submission and approval system
  • Discord Integration: Full Discord bot with moderation, polls, and sharing
  • User Discovery: Explore and follow other creators
  • Showcase System: Curated featured content

Advanced Features

  • API Access: RESTful API with API key management
  • Content Moderation: Automated illegal content detection and filtering
  • Analytics & Statistics: Comprehensive usage tracking and analytics
  • Admin Dashboard: Full administrative interface for platform management
  • Gradio Integration: Support for custom model deployment via Gradio

๐Ÿ›  Tech Stack & Skills Demonstrated

Backend Technologies

  • Runtime: Node.js with TypeScript
  • Framework: Express.js with custom middleware architecture
  • Database: MongoDB with Mongoose ODM and Typegoose decorators
  • Authentication: Passport.js with JWT tokens
  • Validation: Zod schema validation
  • Logging: Pino structured logging

AI & Machine Learning

  • Stable Diffusion: Integration with multiple SD models
  • Gradio: Custom model deployment framework
  • Content Filtering: AI-powered prompt validation and moderation

Cloud & Infrastructure

  • AWS S3: File storage and image hosting
  • Payment Processing: Stripe and Coinbase Commerce APIs
  • Email Services: Nodemailer with SMTP integration
  • SMS Services: Twilio integration for mobile verification

Real-time & Communication

  • Discord.js: Full Discord bot with slash commands
  • WebSockets: Server-Sent Events (SSE) for real-time updates
  • File Upload: Multer with image processing via Sharp

Development & DevOps

  • TypeScript: Full type safety with strict configuration
  • ESLint & Prettier: Code quality and formatting
  • Nodemon: Development hot-reloading
  • Module Aliases: Clean import paths with path mapping

Security & Performance

  • Rate Limiting: IP-based request throttling
  • Content Security: Multi-layer content filtering
  • Input Validation: Comprehensive request validation
  • Error Handling: Centralized error management

๐Ÿ“ฆ Installation & Setup

Prerequisites

  • Node.js 18+
  • MongoDB 6+
  • Python 3.8+ (for Gradio integration)
  • Git

Environment Setup

  1. Clone the repository

    git clone https://github.com/MH-PAVEL/bashable-backend.git
    cd bashable-backend
  2. Install dependencies

    npm install
    # or
    yarn install
  3. Environment Configuration Create a .env file with the following required variables:

    # Server Configuration
    SERVER_URL=http://localhost:1337
    CLIENT_URL=http://localhost:3000
    
    # Database
    MONGO_URI=mongodb://localhost:27017/bashable
    
    # Authentication
    JWT_SECRET=your-jwt-secret
    API_SECRET=your-api-secret
    
    # OAuth Providers
    GOOGLE_CLIENT_ID=your-google-client-id
    GOOGLE_CLIENT_SECRET=your-google-client-secret
    DISCORD_CLIENT_ID=your-discord-client-id
    DISCORD_CLIENT_SECRET=your-discord-client-secret
    MICROSOFT_CLIENT_ID=your-microsoft-client-id
    MICROSOFT_CLIENT_SECRET=your-microsoft-client-secret
    APPLE_CLIENT_ID=your-apple-client-id
    APPLE_TEAM_ID=your-apple-team-id
    APPLE_KEY_ID=your-apple-key-id
    APPLE_KEY_FILE=path/to/apple/key.p8
    
    # Discord Bot
    DISCORD_BOT_TOKEN=your-discord-bot-token
    DISCORD_GUILD_ID=your-discord-guild-id
    DISCORD_SFW_CHANNEL_ID=your-sfw-channel-id
    DISCORD_NSFW_CHANNEL_ID=your-nsfw-channel-id
    DISCORD_POLL_CHANNEL_ID=your-poll-channel-id
    DISCORD_RUN_BOT=true
    
    # AI Generation
    GENERATE_PROVIDER=your-ai-provider
    GENERATE_AUTH_KEY=your-ai-auth-key
    GENERATE_COST=0.2
    GENERATE_SERVER_URL=your-ai-server-url
    OPENAI_API_KEY=your-openai-api-key
    
    # Payment Processing
    STRIPE_SECRET_KEY=your-stripe-secret-key
    STRIPE_WEBHOOK_SECRET=your-stripe-webhook-secret
    COINBASE_API_KEY=your-coinbase-api-key
    COINBASE_WEBHOOK_SECRET=your-coinbase-webhook-secret
    
    # File Storage
    AWS_S3_ACCESS_KEY_ID=your-s3-access-key
    AWS_S3_SECRET_ACCESS_KEY=your-s3-secret-key
    AWS_S3_BUCKET_NAME=your-s3-bucket
    AWS_S3_REGION=your-s3-region
    IMAGES_DIR=./static/images
    
    # Email & SMS
    VERIFY_EMAIL=true
    SMTP_HOST=your-smtp-host
    SMTP_PORT=587
    SMTP_USER=your-smtp-user
    SMTP_PASS=your-smtp-password
    VERIFY_MOBILE=false
    TWILIO_ACCOUNT_SID=your-twilio-sid
    TWILIO_AUTH_TOKEN=your-twilio-token
    TWILIO_PHONE_NUMBER=your-twilio-phone
    
    # Admin
    ADMIN_PASSWORD=your-admin-password
  4. Database Setup

    # Start MongoDB (if using local instance)
    mongod
    
    # Run database migrations
    npm run migrate
  5. Development Server

    # Start development server with hot reload
    npm run dev
    
    # Or build and run production
    npm run build
    npm start

The server will start on http://localhost:1337

๐ŸŽฎ Usage Guide

API Endpoints

The platform provides a comprehensive REST API with the following main endpoints:

Image Generation

# Generate an image
POST /api/generate
{
  "prompt": "A beautiful landscape with mountains",
  "negative_prompt": "blurry, low quality",
  "width": 768,
  "height": 768,
  "steps": 20,
  "model": "dreamshaper_331BakedVae.safetensors"
}

# Get available models
GET /api/generate/checkpoints

# Estimate generation cost
POST /api/generate/cost

User Management

# User registration
POST /api/users/signup
{
  "username": "artist123",
  "email": "artist@example.com",
  "password": "securepassword"
}

# User authentication
POST /api/users/signin
{
  "email": "artist@example.com",
  "password": "securepassword"
}

API Key Management

# Create API key
POST /api/users/api-keys
Authorization: Bearer <jwt-token>

# Use API key for generation
POST /api/endpoints/generate-image
X-API-Key: <your-api-key>
{
  "prompt": "Your prompt here"
}

Discord Bot Commands

  • /generate <prompt> - Generate an image directly in Discord
  • /upscale <image> - Upscale an uploaded image
  • /status - Check your account status and credits
  • /link - Link your Discord account to your Bashable account

๐Ÿ— Architecture Overview

Project Structure

src/
โ”œโ”€โ”€ app/                 # Express application setup
โ”‚   โ”œโ”€โ”€ index.ts        # Main app configuration
โ”‚   โ”œโ”€โ”€ routes.ts       # Route definitions
โ”‚   โ”œโ”€โ”€ middlewares.ts  # Middleware setup
โ”‚   โ””โ”€โ”€ error.ts        # Error handling
โ”œโ”€โ”€ controllers/        # Business logic controllers
โ”‚   โ”œโ”€โ”€ generate.ts     # Image generation logic
โ”‚   โ”œโ”€โ”€ users.ts        # User management
โ”‚   โ”œโ”€โ”€ admin.ts        # Admin functionality
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ models/             # MongoDB schemas (Typegoose)
โ”‚   โ”œโ”€โ”€ user.ts         # User model
โ”‚   โ”œโ”€โ”€ generation.ts   # Image generation model
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ middlewares/        # Custom middleware
โ”‚   โ”œโ”€โ”€ auth.ts         # Authentication middleware
โ”‚   โ”œโ”€โ”€ role.ts         # Role-based access control
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ bot/                # Discord bot implementation
โ”‚   โ”œโ”€โ”€ commands/       # Slash commands
โ”‚   โ””โ”€โ”€ index.ts        # Bot setup
โ”œโ”€โ”€ core/               # Core utilities
โ”‚   โ”œโ”€โ”€ database.ts     # Database connection
โ”‚   โ”œโ”€โ”€ env.ts          # Environment validation
โ”‚   โ””โ”€โ”€ logger.ts       # Logging setup
โ””โ”€โ”€ utils/              # Utility functions

Key Design Patterns

  1. Repository Pattern: Clean separation between data access and business logic
  2. Middleware Chain: Modular middleware for authentication, validation, and error handling
  3. Event-Driven Architecture: Event system for decoupled communication
  4. Type-Safe APIs: Full TypeScript implementation with Zod validation
  5. Modular Routing: Hierarchical route structure with automatic registration

Data Flow

  1. Request Processing: Middleware chain handles auth, validation, and rate limiting
  2. Business Logic: Controllers process requests and interact with models
  3. AI Integration: External AI services handle image generation
  4. Response: Structured responses with proper error handling
  5. Real-time Updates: SSE connections provide live status updates

๐Ÿงฉ Challenges & Solutions

Challenge 1: Real-time Image Generation Status

Problem: Users needed live updates on generation progress without polling. Solution: Implemented Server-Sent Events (SSE) for real-time status updates, reducing server load and improving user experience.

Challenge 2: Multi-provider Authentication

Problem: Supporting 5 different OAuth providers with consistent user experience. Solution: Created a unified authentication system using Passport.js with custom strategies, ensuring seamless user onboarding across all providers.

Challenge 3: Content Moderation at Scale

Problem: Preventing inappropriate content while maintaining generation speed. Solution: Implemented multi-layer content filtering with AI-powered prompt validation, user reputation systems, and automated moderation workflows.

Challenge 4: Payment Integration Complexity

Problem: Managing multiple payment gateways with different webhook formats and error handling. Solution: Built a unified payment abstraction layer with webhook validation, automatic retry logic, and comprehensive error handling for Stripe and Coinbase.

Challenge 5: Discord Bot Integration

Problem: Synchronizing Discord interactions with the main platform while maintaining data consistency. Solution: Created a modular Discord bot with slash commands, real-time moderation tools, and seamless account linking functionality.

๐Ÿš€ Future Improvements That Could be Done

Planned Enhancements

  • Microservices Architecture: Break down monolithic structure into microservices
  • Redis Caching: Implement Redis for session management and caching
  • GraphQL API: Add GraphQL endpoint for more flexible data querying
  • Docker Containerization: Full containerization with Docker Compose
  • Kubernetes Deployment: Production-ready K8s manifests
  • Real-time Chat: WebSocket-based chat system for user collaboration
  • Advanced Analytics: Machine learning-powered usage analytics
  • Mobile API: Optimized endpoints for mobile applications
  • Webhook System: Extensible webhook system for third-party integrations
  • A/B Testing Framework: Built-in experimentation platform

Scalability Improvements

  • Database Sharding: Horizontal scaling for MongoDB
  • CDN Integration: Global content delivery network
  • Load Balancing: Multi-instance deployment with load balancing
  • Queue System: Redis-based job queue for background processing
  • Monitoring & Alerting: Comprehensive observability stack

โญ Star this repository if you found it helpful! Your support helps us continue building amazing AI tools for creators worldwide.

Ready to build the future of AI-powered creativity? ๐Ÿš€

About

A TypeScript/Node.js backend for a sophisticated AI image generation platform that integrates Stable Diffusion models with comprehensive user management, payment processing, Discord bot integration, and community features.

Resources

Stars

Watchers

Forks

Languages