Skip to content

Latest commit

History

161 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TopicsFlow App

📚 Comprehensive Documentation: Check out the Project Wiki for detailed guides on Architecture, API, Deployment, and more.

Overview

TopicsFlow is a comprehensive chat and topic discussion platform designed to facilitate focused conversations and community interactions.

🔐 Security & Authentication

  • Passwordless Authentication: Users log in via email/username + 6-digit TOTP code.
  • TOTP-based 2FA: Full compatibility with Google Authenticator, Microsoft Authenticator, and Authy.
  • Robust Account Recovery: Multi-step recovery using email verification and original TOTP secrets.
  • Backup Codes: 10 high-entropy emergency access codes provided during setup.
  • Secure Sessions: Encrypted session storage in Redis (Azure/Docker) or filesystem (local) with proper cookie security (HttpOnly).
  • Intelligent Caching: Redis-based caching system for database queries with automatic cache invalidation. Dramatically improves performance (50-90% faster response times) while ensuring data consistency.
  • Advanced Banning: Global banning system targeting IP addresses, emails, and phone numbers.

💬 Real-time Communication

  • Hybrid Platform: Seamless integration between Reddit-style forums and instant chat rooms.
  • WebSocket Foundation: Built on Socket.IO for sub-100ms latency.
  • Presence System: Real-time "online" status and typing indicators across the entire app.
  • Group Chat Rooms: Unlimited rooms per Topic with customizable profile/background images.
  • Direct Messaging (DMs): Private 1-on-1 conversations with encryption-ready architecture.
  • Voice Communication (VOIP): Integrated voice rooms with participant lists and active speaker detection.
  • Media Engine: Instant sharing of GIFs (Tenor), images, videos, and files with secure cloud storage.
  • Anonymous Mode: Per-topic identity masking with custom aliases to encourage open discussion.

📝 Content Management (The "Publications" System)

  • Dynamic Topics: Hierarchical community spaces for high-level categorization.
  • Publications (Posts): Reddit-style nested posts with rich text (Markdown) support.
  • Voting Mechanism: Positive/Negative reputation system for quality control.
  • Threaded Comments: Deeply nested conversations with @mentions and reply tracking.
  • Navigation Controls: Advanced sorting (Hot, New, Top) and tag-based discovery.
  • Search Engine: Rapid indexing of topics and posts for easy discovery.

🛡️ Moderation & Support

  • Admin Dashboard: Centralized command center for platform-wide oversight.
  • Integrated Ticket System: Direct communication channel between users and administrators for help requests.
  • Report Lifecycle: Comprehensive reporting for users/messages/posts with automated context attachment.
  • Role-based Access Control (RBAC): Granular permissions system (Owner -> Moderator -> Member).
  • Content Filtering: Integrated profanity filters and link sanitization.

🎨 Design & Accessibility

  • Responsive Architecture: Pixel-perfect layouts for Mobile, Tablet, and Desktop.
  • Modern Theme Engine: Dynamic Dark/Light mode switching with cohesive HSL color palettes.
  • Internationalization (i18n): Native-level support for English and Portuguese.
  • PWA Capabilities: Installable web app with push notifications and offline caching.
  • Accessibility: ARIA-compliant components and keyboard-friendly navigation.

Technology Stack

Backend

  • Flask (Python web framework)
  • Flask-SocketIO (real-time WebSocket communication)
  • MongoDB (NoSQL database)
  • PyOTP (TOTP authentication)
  • Redis (session storage and intelligent database caching with automatic invalidation)

Frontend

  • Next.js with TypeScript
  • Socket.IO Client (real-time communication)
  • Tailwind CSS (styling with theme variables)
  • React Hot Toast (notifications)
  • PWA capabilities with service workers and native install prompts
  • Image Viewer Modal: Full-screen image viewing with download controls
  • Enhanced Video Player: Fullscreen support, download, and right-click context menu
  • Context Menus: Right-click menus for posts, messages, chatrooms, and users

Infrastructure

  • Docker with multi-stage builds
  • Docker Compose for orchestration
  • Nginx reverse proxy (production)
  • Environment-based configuration

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local development)
  • Python 3.11+ (for local development)
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>cd RINTEP2
  2. Start the application

    ./START.sh

    This will:

    • Check prerequisites
    • Set up environment variables
    • Create necessary directories
    • Start all services (MongoDB, Redis, Backend, Frontend)
    • Wait for services to be healthy
  3. Access the application

Manual Setup (Alternative)

If you prefer to set up manually:

  1. Set up environment variables

    # Backend
    cp backend/env.example backend/.env
    # Frontend
    cp frontend/env.local.example frontend/.env.local
    # Edit the copied files with your configuration
  2. Start services with Docker Compose

    docker-compose up --build
  3. Or run locally for development

    Backend:

    cd backend
    python -m venv venv
    source venv/bin/activate # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python app.py

    Frontend:

    cd frontend
    npm install
    npm run dev

Configuration

Environment Variables

The application uses environment variables for configuration. You can set them up automatically or manually.

Automatic Setup (Recommended)

Windows:

setup-env.bat

Linux/Mac:

chmod +x setup-env.sh
./setup-env.sh

PowerShell:

powershell -ExecutionPolicy Bypass -File setup-env.ps1

Manual Setup

Create a .env file in the backend/ directory:

# Database ConfigurationDATABASE_URL=mongodb://localhost:27017/TopicsFlowREDIS_URL=redis://localhost:6379/0# Application ConfigurationSECRET_KEY=your_super_secret_key_hereFRONTEND_URL=http://localhost:3000TOTP_ISSUER=TopicsFlowAPP_NAME=TopicsFlow# Email Service (Resend)RESEND_API_KEY=your_resend_api_keyFROM_EMAIL=noreply@topicsflow.me# External ServicesTENOR_API_KEY=your_tenor_api_key# File Storage (Optional - for Azure deployments)USE_AZURE_STORAGE=falseAZURE_STORAGE_CONNECTION_STRING=your_azure_storage_connection_stringAZURE_STORAGE_CONTAINER=uploadsFILE_ENCRYPTION_KEY=your_file_encryption_key# Optional, defaults to SECRET_KEY# ImgBB (Optional - for large chatroom images)USE_IMGBB=falseIMGBB_API_KEY=your_imgbb_api_keyIMGBB_EXPIRATION_SECONDS=600IMGBB_MAX_BASE64_SIZE_BYTES=2097152# CORS (Development)CORS_ALLOW_ALL=true

Environment variables reference (Local + Azure)

You can use these example templates:

  • backend/env.example → copy to backend/.env
  • frontend/env.local.example → copy to frontend/.env.local

Backend (local development)

VariableDescriptionRequired
SECRET_KEYFlask secret key✅ Yes
ENVIRONMENTdevelopment/production (affects cookie security)Recommended
DATABASE_URLMongoDB connection string✅ Yes
DB_NAMEMongoDB database nameRecommended
REDIS_URLRedis connection string (sessions/rate limit)Recommended
FRONTEND_URLFrontend origin (CORS + passkeys)✅ Yes
CORS_ALLOW_ALLAllow all origins in devOptional
RESEND_API_KEYResend email API key✅ Yes
FROM_EMAILVerified sender email✅ Yes
APP_NAMEApp name used in emailsRecommended
TENOR_API_KEYTenor API key for GIF searchOptional
TENOR_CLIENT_KEYTenor client key (defaults to topicsflow_app)Optional
PASSKEY_RP_IDWebAuthn RP ID (defaults to localhost)Optional
LOG_LEVELLogging levelOptional

Backend storage (attachments)

VariableDescriptionRequired
USE_AZURE_STORAGEUse Azure Blob Storage for attachmentsOptional
AZURE_STORAGE_CONNECTION_STRINGAzure Storage connection stringRequired if USE_AZURE_STORAGE=true
AZURE_STORAGE_CONTAINERBlob container name (use uploads)Required if USE_AZURE_STORAGE=true
API_BASE_URLUsed to build attachment URLsRecommended
FILE_ENCRYPTION_KEYOptional encryption key for attachment URLs (defaults to SECRET_KEY)Optional

Backend ImgBB (recomended)

VariableDescriptionRequired
USE_IMGBBEnable ImgBB uploads for large imagesOptional
IMGBB_API_KEYImgBB API keyRequired if USE_IMGBB=true
IMGBB_EXPIRATION_SECONDSOptional ImgBB expirationOptional
IMGBB_MAX_BASE64_SIZE_BYTESThreshold to upload to ImgBBOptional

Backend (Azure/CosmosDB Mongo API)

VariableDescriptionRequired
AZURE_COSMOS_CONNECTIONSTRINGCosmosDB (Mongo API) connection string✅ Yes (Azure)
AZURE_COSMOS_DATABASECosmos database name✅ Yes (Azure)
COSMOS_DB_URI / COSMOS_DB_NAMEAlternative Cosmos env names supported by configOptional
AZURE_DEPLOYMENTSet to true to force Azure modeOptional
FORCE_AZURE_MODE / FORCE_LOCAL_MODEForce environment detectionOptional

Backend (Redis - Azure/Docker only)

VariableDescriptionRequired
AZURE_REDIS_CONNECTIONSTRINGAzure Redis Cache connection string (format: host:port,password=...,ssl=True)Optional (Azure only)
REDIS_URLRedis connection string (format: redis://password@host:port/0)Optional (Docker/Azure)
REDIS_PASSWORDRedis password (used in Docker Compose)Optional (Docker)
SESSION_TYPESession backend: filesystem (local) or redis (Docker/Azure)Auto-detected

Note: Redis is automatically disabled for local development (non-Docker). The application uses filesystem sessions and direct database queries when running locally without Docker.

Frontend

VariableDescriptionRequired
NEXT_PUBLIC_API_URLBackend base URL✅ Yes
NEXT_PUBLIC_APP_NAMEApp nameOptional
NEXT_PUBLIC_TENOR_API_KEYTenor API key (only if frontend uses it directly)Optional

Email Service Setup (Resend)

  1. Get your API key from Resend Dashboard
  2. Verify your domain in Resend Domains
  3. Add DNS records provided by Resend to your domain
  4. Set FROM_EMAIL to use your verified domain

Tenor API Setup

  1. Go to Tenor Developer Portal
  2. Sign in with Google account
  3. Create a new API key
  4. Add TENOR_API_KEY to your .env file

Passwordless Authentication

The application uses passwordless authentication with TOTP (Time-based One-Time Password):

  • No passwords - Users authenticate with username/email + 6-digit authenticator code
  • Email verification - Required during registration (6-digit codes)
  • TOTP 2FA - Industry-standard authenticator apps (Google Authenticator, Authy, etc.)
  • Backup codes - Emergency access codes for account recovery
  • Secure recovery - Requires email verification + original TOTP secret

User Registration Flow:

  1. Enter username and email
  2. Verify email with 6-digit code
  3. Setup authenticator app (scan QR code or manual entry)
  4. Verify TOTP code
  5. Save backup codes

User Login Flow:

  1. Enter username/email
  2. Enter 6-digit code from authenticator app

Account Recovery:

  1. Enter email → receive verification code
  2. Verify email code
  3. Enter original TOTP secret (saved during registration)
  4. Setup new authenticator
  5. Get new backup codes

⚠️ Important: Users must save their TOTP secret during registration for account recovery!

Caching System

TopicsFlow includes an intelligent Redis-based caching system that dramatically improves performance:

Features:

  • Automatic Caching: All database queries are automatically cached with appropriate TTLs
    • Static data (users, topics): 1 hour cache
    • Dynamic data (posts, comments, messages): 5 minutes cache
  • Automatic Invalidation: Cache is automatically invalidated when data is updated, ensuring consistency
  • Graceful Fallback: If Redis is unavailable, the application automatically falls back to direct database queries
  • Zero Configuration: Works automatically in Docker/Azure deployments with Redis

Local Development:

  • Redis cache is disabled by default on local machines
  • Uses filesystem sessions and direct database queries
  • No Redis installation required for local development

Docker/Azure Deployments:

  • Redis is automatically used for both sessions and caching
  • Provides 50-90% faster response times for cached queries
  • Automatic cache invalidation ensures data consistency
  • Docker: Redis is configured with password authentication (matches Azure approach)
  • Azure: Uses Azure Redis Cache with SSL and connection string format (host:port,password=...,ssl=True)

Cache Invalidation Strategy:

  • Direct updates invalidate the entity and related entities
  • Cascading invalidation ensures all dependent data is refreshed
  • Pattern-based invalidation for list queries

Production Deployment

For production deployment:

  1. Update environment variables with secure values
  2. Set up SSL certificates for HTTPS
  3. Use production Docker Compose file:
    ./START.sh prod
  4. Configure Nginx for reverse proxy and SSL termination

See Azure Deployment section for cloud deployment options.

API Documentation

Authentication Endpoints

Passwordless Registration (Step 1: Start Registration)

POST /api/auth/register-passwordlessContent-Type: application/json
{
"username": "username",
"email": "user@example.com"
}
Response 201:
{
"success": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Verification code sent to your email"
}

Verify Email (Step 2)

POST /api/auth/verify-emailContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}
Response 200:
{
"success": true,
"totp_qr_data": "otpauth://totp/TopicsFlow:username?secret=...",
"totp_secret": "JBSWY3DPEHPK3PXP",
"user_id": "507f1f77bcf86cd799439011"
}

Complete TOTP Setup (Step 3)

POST /api/auth/complete-totp-setupContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"totp_code": "123456"
}
Response 200:
{
"success": true,
"backup_codes": ["12345678", "23456789", ...]
}

Passwordless Login

POST /api/auth/login-passwordlessContent-Type: application/json
{
"identifier": "username", // username or email"totp_code": "123456"
}
Response 200:
{
"success": true,
"user": {
"id": "507f1f77bcf86cd799439011",
"username": "username",
"email": "user@example.com"
}
}

Response 200 (Email 2FA Required):

{
"success": false,
"require_email_2fa": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Please check your email for the verification code"
}

Verify Login Email 2FA

POST /api/auth/verify-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}

Resend Login Email 2FA Code

POST /api/auth/resend-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011"
}
Response 200:
{
"success": true,
"message": "Verification code sent.",
"cooldown": 60
}

Account Recovery

POST /api/auth/recovery/initiate-passwordlessContent-Type: application/json
{
"email": "user@example.com"
}
POST /api/auth/recovery/verify-email-codeContent-Type: application/json
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/recovery/reset-totpContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"original_secret": "JBSWY3DPEHPK3PXP"// Saved during registration
}

Topic Endpoints

Get Topics

GET /api/topics?sort_by=last_activity&limit=20&offset=0&tags=chat,gaming&search=gaming

Create Topic

POST /api/topicsContent-Type: application/jsonAuthorization: Session cookie
{
"title": "Topic Title",
"description": "Topic description",
"tags": ["chat", "gaming"],
"allow_anonymous": true,
"require_approval": false
}

Message Endpoints

Get Topic Messages

GET /api/messages/topic/{topic_id}?limit=50&before_message_id={message_id}

Send Message

POST /api/messages/topic/{topic_id}Content-Type: application/jsonAuthorization: Session cookie
{
"content": "Hello, world!",
"message_type": "text",
"use_anonymous": false,
"gif_url": "https://example.com/gif.gif"
}

Database Schema

Users Collection

{_id: ObjectId,username: String(unique,validated),email: String(unique),phone: String(optional,forrecovery),password_hash: String,totp_secret: String(encrypted),totp_enabled: Boolean,security_questions: [Array],is_banned: Boolean,ban_reason: String,ban_expiry: Date,ip_addresses: [String],created_at: Date,last_login: Date,preferences: {theme: String('dark'|'light'),language: String('en'|'pt'),anonymous_mode: Boolean}}

Topics Collection

{_id: ObjectId,title: String,description: String,owner_id: ObjectId,moderators: [{user_id: ObjectId,added_by: ObjectId,added_at: Date,permissions: [String]}],tags: [String],member_count: Number,is_public: Boolean,created_at: Date,last_activity: Date,settings: {allow_anonymous: Boolean,require_approval: Boolean}}

Messages Collection

{_id: ObjectId,topic_id: ObjectId,user_id: ObjectId,content: String,topic_id: ObjectId,chat_room_id: ObjectId,// For chat room messagesuser_id: ObjectId,content: String,message_type: String('text'|'emoji'|'gif'|'image'|'video'|'file'|'system'),anonymous_identity: String,gif_url: String,attachments: [{// File references (not base64 data)type: String,file_id: String,url: String,filename: String,size: Number,mime_type: String}],is_deleted: Boolean,deleted_by: ObjectId,deleted_at: Date,deletion_reason: String,// For owner deletionsreports: [{reported_by: ObjectId,reason: String,created_at: Date}],created_at: Date,updated_at: Date}

Chat Rooms Collection

{_id: ObjectId,topic_id: ObjectId,name: String,description: String,owner_id: ObjectId,moderators: [ObjectId],members: [ObjectId],picture: String,// Base64 profile picturebackground_picture: String,// Base64 background imageis_public: Boolean,created_at: Date,updated_at: Date}

Private Messages Collection

{_id: ObjectId,from_user_id: ObjectId,to_user_id: ObjectId,content: String,message_type: String,gif_url: String,deleted_for_user_ids: [ObjectId],// Soft delete per useris_read: Boolean,read_at: Date,created_at: Date}

Reports Collection

{_id: ObjectId,reporter_id: ObjectId,reported_user_id: ObjectId,content_id: String,// Message, post, comment, or chatroom IDcontent_type: String,// 'user' | 'message' | 'post' | 'comment' | 'chatroom' | 'chatroom_background' | 'chatroom_picture'reason: String,description: String,owner_id: ObjectId,// For chatroom/content reportsowner_username: String,moderators: [{id: ObjectId,username: String}],// For admin analysisstatus: String,created_at: Date}

Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    python app.py
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker run -d --name mongodb -p 27017:27017 mongo:7.0
    # Start Redis
    docker run -d --name redis -p 6379:6379 redis:7.2-alpine

Testing

Quick Testing Guide

# 1. Migrate database
python migrate_database.py migrate
# 2. Make admin user
python make_admin.py <username># 3. Start backendcd backend && python app.py
# 4. Start frontendcd frontend && npm run dev
# 5. Access app
http://localhost:3000

Test Scenarios

  1. Admin Controls: Login as admin, check for shield icon (🛡️) in top bar
  2. Clickable Usernames: Click username in chat → user banner appears
  3. Right-Click Menu: Right-click username → context menu with options
  4. Report User: Right-click → Report User → fill form → submit
  5. Ticket Creation: Profile menu → Open Ticket → create ticket
  6. Anonymous Mode: Enable "Use Anonymous" toggle in chat

Backend API Testing

Using Postman:

  1. Import tests/TopicsFlow_API.postman_collection.json
  2. Import environment file from tests/postman/environments/
  3. Run collection tests

Using Newman (CLI):

npm install -g newman newman-reporter-html
newman run tests/postman/TopicsFlow_Backend_API.postman_collection.json \
-e tests/postman/environments/Local.postman_environment.json \
-r html --reporter-html-export tests/reports/report.html

WebSocket Testing:

  • Use browser DevTools console
  • See tests/postman/TopicsFlow_WebSocket_Tests.md for detailed instructions

For comprehensive testing documentation, see:

  • TESTING_GUIDE.md - Quick testing scenarios
  • TEST_PLAN.md - Comprehensive test plan
  • tests/TESTING_GUIDE.md - Backend API testing guide
  • tests/TEST_TROUBLESHOOTING.md - Test troubleshooting

Code Quality

# Backend lintingcd backend
flake8 .
black .# Frontend lintingcd frontend
npm run lint
npm run type-check

Security Considerations

  • TOTP Secrets: Encrypted at rest using AES-256
  • Passwords: Hashed with bcrypt
  • Sessions: Secure session management with HTTP-only cookies
  • Rate Limiting: Implemented on all sensitive endpoints
  • Input Validation: Comprehensive validation and sanitization
  • HTTPS: Enforced in production
  • CORS: Properly configured for frontend domain
  • Content Security Policy: Headers implemented for XSS prevention

Monitoring & Logging

Application Logs

# View all service logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f backend
docker-compose logs -f frontend

Health Checks

  • Backend: GET /health
  • Frontend: HTTP status checks
  • Database: Connection health monitoring

Azure Deployment

Quick Start (5 minutes)

# 1. Install Azure CLI# Linux/Mac: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash# Windows: Download from https://aka.ms/installazurecliwindows# 2. Login to Azure
az login
# 3. Configure variables
cp .env.azure.example .env.azure
# Edit .env.azure with your values# 4. Deployexport$(cat .env.azure | xargs)
./azure-deploy.sh

Architecture

  • Backend: Flask + SocketIO + Static Frontend (served by Flask)
  • Database: Azure CosmosDB (MongoDB API)
  • Cache: Azure Cache for Redis (optional)
  • Deployment: Azure Container Apps
  • SSL: Automatic HTTPS

Environment Detection

The application automatically detects Azure environment via:

  • WEBSITE_INSTANCE_ID
  • AZURE_COSMOS_CONNECTIONSTRING

When detected, it automatically:

  • Uses CosmosDB instead of MongoDB
  • Configures SSL connections
  • Disables retryWrites (not supported by CosmosDB)
  • Serves static frontend

Required Azure Resources

  • Azure Container Registry (ACR)
  • Azure CosmosDB (MongoDB API)
  • Azure Container Apps Environment
  • Azure Container App

Cost Estimate

  • Container Apps: ~$40/month
  • CosmosDB: ~$24/month
  • Redis Cache: ~$16/month (optional)
  • Container Registry: ~$5/month
  • Total: ~$85/month (or ~$69 without Redis)

CI/CD with GitHub Actions

  1. Configure GitHub Secrets:

    • AZURE_CREDENTIALS - Service Principal JSON
    • AZURE_CONTAINER_REGISTRY - ACR name
    • AZURE_RESOURCE_GROUP - Resource group name
    • AZURE_APP_NAME - Container App name
    • ACR_USERNAME - ACR username
    • ACR_PASSWORD - ACR password
  2. Push to trigger deployment:

    git push origin main

See GITHUB_ACTIONS_SETUP.md for detailed CI/CD setup instructions.

For complete Azure deployment documentation, see:

  • AZURE_DEPLOYMENT.md - Comprehensive deployment guide
  • AZURE_QUICKSTART.md - Quick start guide

Troubleshooting

Common Issues

  1. Services won't start

    # Check if ports are available# Windows
    netstat -ano | findstr :5000
    taskkill /PID <number> /F
    # Linux/Mac
    lsof -i :3000
    lsof -i :5000
    lsof -i :27017
    lsof -i :6379
    # Clean and restart
    docker-compose down -v
    docker system prune -f
    ./START.sh
  2. Database connection issues

    # Check MongoDB logs
    docker-compose logs mongodb
    # Connect to MongoDB directly
    docker-compose exec mongodb mongosh
  3. TOTP authentication issues

    • Ensure server time is synchronized
    • Check TOTP secret encryption
    • Verify authenticator app time sync
    • Codes expire every 30 seconds - use current code
  4. Frontend build issues

    # Clear Next.js cache
    rm -rf .next
    npm run build
  5. Email not sending

    • Verify Resend API key is set: echo $RESEND_API_KEY
    • Check domain is verified in Resend dashboard
    • Verify FROM_EMAIL uses verified domain
    • Check backend logs for errors
  6. bcrypt module not found (Windows)

    # Solution 1: Reinstall bcrypt
    pip uninstall -y bcrypt
    pip install --only-binary :all: bcrypt==4.1.0
    # Solution 2: Install Visual Studio Build Tools# Download from https://visualstudio.microsoft.com/downloads/# Install "Desktop development with C++"# Solution 3: Use compatible version
    pip install bcrypt==4.0.1
  7. Port already in use (Windows)

    netstat -ano |findstr :5000
    taskkill /PID <number> /F
  8. MongoDB connection failed

    # Check if MongoDB is running
    docker ps | findstr mongodb
    # Start MongoDB
    docker start mongodb-test
    # Or create new container
    docker run -d --name mongodb-test -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    mongo:7.0

For Windows-specific troubleshooting, see WINDOWS_TROUBLESHOOTING.md.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test and python -m pytest
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow existing code patterns
  • Write tests for new features
  • Update documentation
  • Use descriptive commit messages
  • Keep PRs focused and manageable

License

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

Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section above
  • Review the API documentation

Acknowledgments

  • Built with Flask, Next.js, MongoDB, and Socket.IO
  • Inspired by Reddit's community structure
  • TOTP authentication standards
  • Open source libraries and frameworks used

About

Chat application that features publications and chatrooms by topic and direct messages and groups.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - 8JP8/TopicsFlow: Chat application that features publications and chatrooms by topic and direct messages and groups. · GitHub
Skip to content

Latest commit

History

161 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TopicsFlow App

📚 Comprehensive Documentation: Check out the Project Wiki for detailed guides on Architecture, API, Deployment, and more.

Overview

TopicsFlow is a comprehensive chat and topic discussion platform designed to facilitate focused conversations and community interactions.

🔐 Security & Authentication

  • Passwordless Authentication: Users log in via email/username + 6-digit TOTP code.
  • TOTP-based 2FA: Full compatibility with Google Authenticator, Microsoft Authenticator, and Authy.
  • Robust Account Recovery: Multi-step recovery using email verification and original TOTP secrets.
  • Backup Codes: 10 high-entropy emergency access codes provided during setup.
  • Secure Sessions: Encrypted session storage in Redis (Azure/Docker) or filesystem (local) with proper cookie security (HttpOnly).
  • Intelligent Caching: Redis-based caching system for database queries with automatic cache invalidation. Dramatically improves performance (50-90% faster response times) while ensuring data consistency.
  • Advanced Banning: Global banning system targeting IP addresses, emails, and phone numbers.

💬 Real-time Communication

  • Hybrid Platform: Seamless integration between Reddit-style forums and instant chat rooms.
  • WebSocket Foundation: Built on Socket.IO for sub-100ms latency.
  • Presence System: Real-time "online" status and typing indicators across the entire app.
  • Group Chat Rooms: Unlimited rooms per Topic with customizable profile/background images.
  • Direct Messaging (DMs): Private 1-on-1 conversations with encryption-ready architecture.
  • Voice Communication (VOIP): Integrated voice rooms with participant lists and active speaker detection.
  • Media Engine: Instant sharing of GIFs (Tenor), images, videos, and files with secure cloud storage.
  • Anonymous Mode: Per-topic identity masking with custom aliases to encourage open discussion.

📝 Content Management (The "Publications" System)

  • Dynamic Topics: Hierarchical community spaces for high-level categorization.
  • Publications (Posts): Reddit-style nested posts with rich text (Markdown) support.
  • Voting Mechanism: Positive/Negative reputation system for quality control.
  • Threaded Comments: Deeply nested conversations with @mentions and reply tracking.
  • Navigation Controls: Advanced sorting (Hot, New, Top) and tag-based discovery.
  • Search Engine: Rapid indexing of topics and posts for easy discovery.

🛡️ Moderation & Support

  • Admin Dashboard: Centralized command center for platform-wide oversight.
  • Integrated Ticket System: Direct communication channel between users and administrators for help requests.
  • Report Lifecycle: Comprehensive reporting for users/messages/posts with automated context attachment.
  • Role-based Access Control (RBAC): Granular permissions system (Owner -> Moderator -> Member).
  • Content Filtering: Integrated profanity filters and link sanitization.

🎨 Design & Accessibility

  • Responsive Architecture: Pixel-perfect layouts for Mobile, Tablet, and Desktop.
  • Modern Theme Engine: Dynamic Dark/Light mode switching with cohesive HSL color palettes.
  • Internationalization (i18n): Native-level support for English and Portuguese.
  • PWA Capabilities: Installable web app with push notifications and offline caching.
  • Accessibility: ARIA-compliant components and keyboard-friendly navigation.

Technology Stack

Backend

  • Flask (Python web framework)
  • Flask-SocketIO (real-time WebSocket communication)
  • MongoDB (NoSQL database)
  • PyOTP (TOTP authentication)
  • Redis (session storage and intelligent database caching with automatic invalidation)

Frontend

  • Next.js with TypeScript
  • Socket.IO Client (real-time communication)
  • Tailwind CSS (styling with theme variables)
  • React Hot Toast (notifications)
  • PWA capabilities with service workers and native install prompts
  • Image Viewer Modal: Full-screen image viewing with download controls
  • Enhanced Video Player: Fullscreen support, download, and right-click context menu
  • Context Menus: Right-click menus for posts, messages, chatrooms, and users

Infrastructure

  • Docker with multi-stage builds
  • Docker Compose for orchestration
  • Nginx reverse proxy (production)
  • Environment-based configuration

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local development)
  • Python 3.11+ (for local development)
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>cd RINTEP2
  2. Start the application

    ./START.sh

    This will:

    • Check prerequisites
    • Set up environment variables
    • Create necessary directories
    • Start all services (MongoDB, Redis, Backend, Frontend)
    • Wait for services to be healthy
  3. Access the application

Manual Setup (Alternative)

If you prefer to set up manually:

  1. Set up environment variables

    # Backend
    cp backend/env.example backend/.env
    # Frontend
    cp frontend/env.local.example frontend/.env.local
    # Edit the copied files with your configuration
  2. Start services with Docker Compose

    docker-compose up --build
  3. Or run locally for development

    Backend:

    cd backend
    python -m venv venv
    source venv/bin/activate # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python app.py

    Frontend:

    cd frontend
    npm install
    npm run dev

Configuration

Environment Variables

The application uses environment variables for configuration. You can set them up automatically or manually.

Automatic Setup (Recommended)

Windows:

setup-env.bat

Linux/Mac:

chmod +x setup-env.sh
./setup-env.sh

PowerShell:

powershell -ExecutionPolicy Bypass -File setup-env.ps1

Manual Setup

Create a .env file in the backend/ directory:

# Database ConfigurationDATABASE_URL=mongodb://localhost:27017/TopicsFlowREDIS_URL=redis://localhost:6379/0# Application ConfigurationSECRET_KEY=your_super_secret_key_hereFRONTEND_URL=http://localhost:3000TOTP_ISSUER=TopicsFlowAPP_NAME=TopicsFlow# Email Service (Resend)RESEND_API_KEY=your_resend_api_keyFROM_EMAIL=noreply@topicsflow.me# External ServicesTENOR_API_KEY=your_tenor_api_key# File Storage (Optional - for Azure deployments)USE_AZURE_STORAGE=falseAZURE_STORAGE_CONNECTION_STRING=your_azure_storage_connection_stringAZURE_STORAGE_CONTAINER=uploadsFILE_ENCRYPTION_KEY=your_file_encryption_key# Optional, defaults to SECRET_KEY# ImgBB (Optional - for large chatroom images)USE_IMGBB=falseIMGBB_API_KEY=your_imgbb_api_keyIMGBB_EXPIRATION_SECONDS=600IMGBB_MAX_BASE64_SIZE_BYTES=2097152# CORS (Development)CORS_ALLOW_ALL=true

Environment variables reference (Local + Azure)

You can use these example templates:

  • backend/env.example → copy to backend/.env
  • frontend/env.local.example → copy to frontend/.env.local

Backend (local development)

VariableDescriptionRequired
SECRET_KEYFlask secret key✅ Yes
ENVIRONMENTdevelopment/production (affects cookie security)Recommended
DATABASE_URLMongoDB connection string✅ Yes
DB_NAMEMongoDB database nameRecommended
REDIS_URLRedis connection string (sessions/rate limit)Recommended
FRONTEND_URLFrontend origin (CORS + passkeys)✅ Yes
CORS_ALLOW_ALLAllow all origins in devOptional
RESEND_API_KEYResend email API key✅ Yes
FROM_EMAILVerified sender email✅ Yes
APP_NAMEApp name used in emailsRecommended
TENOR_API_KEYTenor API key for GIF searchOptional
TENOR_CLIENT_KEYTenor client key (defaults to topicsflow_app)Optional
PASSKEY_RP_IDWebAuthn RP ID (defaults to localhost)Optional
LOG_LEVELLogging levelOptional

Backend storage (attachments)

VariableDescriptionRequired
USE_AZURE_STORAGEUse Azure Blob Storage for attachmentsOptional
AZURE_STORAGE_CONNECTION_STRINGAzure Storage connection stringRequired if USE_AZURE_STORAGE=true
AZURE_STORAGE_CONTAINERBlob container name (use uploads)Required if USE_AZURE_STORAGE=true
API_BASE_URLUsed to build attachment URLsRecommended
FILE_ENCRYPTION_KEYOptional encryption key for attachment URLs (defaults to SECRET_KEY)Optional

Backend ImgBB (recomended)

VariableDescriptionRequired
USE_IMGBBEnable ImgBB uploads for large imagesOptional
IMGBB_API_KEYImgBB API keyRequired if USE_IMGBB=true
IMGBB_EXPIRATION_SECONDSOptional ImgBB expirationOptional
IMGBB_MAX_BASE64_SIZE_BYTESThreshold to upload to ImgBBOptional

Backend (Azure/CosmosDB Mongo API)

VariableDescriptionRequired
AZURE_COSMOS_CONNECTIONSTRINGCosmosDB (Mongo API) connection string✅ Yes (Azure)
AZURE_COSMOS_DATABASECosmos database name✅ Yes (Azure)
COSMOS_DB_URI / COSMOS_DB_NAMEAlternative Cosmos env names supported by configOptional
AZURE_DEPLOYMENTSet to true to force Azure modeOptional
FORCE_AZURE_MODE / FORCE_LOCAL_MODEForce environment detectionOptional

Backend (Redis - Azure/Docker only)

VariableDescriptionRequired
AZURE_REDIS_CONNECTIONSTRINGAzure Redis Cache connection string (format: host:port,password=...,ssl=True)Optional (Azure only)
REDIS_URLRedis connection string (format: redis://password@host:port/0)Optional (Docker/Azure)
REDIS_PASSWORDRedis password (used in Docker Compose)Optional (Docker)
SESSION_TYPESession backend: filesystem (local) or redis (Docker/Azure)Auto-detected

Note: Redis is automatically disabled for local development (non-Docker). The application uses filesystem sessions and direct database queries when running locally without Docker.

Frontend

VariableDescriptionRequired
NEXT_PUBLIC_API_URLBackend base URL✅ Yes
NEXT_PUBLIC_APP_NAMEApp nameOptional
NEXT_PUBLIC_TENOR_API_KEYTenor API key (only if frontend uses it directly)Optional

Email Service Setup (Resend)

  1. Get your API key from Resend Dashboard
  2. Verify your domain in Resend Domains
  3. Add DNS records provided by Resend to your domain
  4. Set FROM_EMAIL to use your verified domain

Tenor API Setup

  1. Go to Tenor Developer Portal
  2. Sign in with Google account
  3. Create a new API key
  4. Add TENOR_API_KEY to your .env file

Passwordless Authentication

The application uses passwordless authentication with TOTP (Time-based One-Time Password):

  • No passwords - Users authenticate with username/email + 6-digit authenticator code
  • Email verification - Required during registration (6-digit codes)
  • TOTP 2FA - Industry-standard authenticator apps (Google Authenticator, Authy, etc.)
  • Backup codes - Emergency access codes for account recovery
  • Secure recovery - Requires email verification + original TOTP secret

User Registration Flow:

  1. Enter username and email
  2. Verify email with 6-digit code
  3. Setup authenticator app (scan QR code or manual entry)
  4. Verify TOTP code
  5. Save backup codes

User Login Flow:

  1. Enter username/email
  2. Enter 6-digit code from authenticator app

Account Recovery:

  1. Enter email → receive verification code
  2. Verify email code
  3. Enter original TOTP secret (saved during registration)
  4. Setup new authenticator
  5. Get new backup codes

⚠️ Important: Users must save their TOTP secret during registration for account recovery!

Caching System

TopicsFlow includes an intelligent Redis-based caching system that dramatically improves performance:

Features:

  • Automatic Caching: All database queries are automatically cached with appropriate TTLs
    • Static data (users, topics): 1 hour cache
    • Dynamic data (posts, comments, messages): 5 minutes cache
  • Automatic Invalidation: Cache is automatically invalidated when data is updated, ensuring consistency
  • Graceful Fallback: If Redis is unavailable, the application automatically falls back to direct database queries
  • Zero Configuration: Works automatically in Docker/Azure deployments with Redis

Local Development:

  • Redis cache is disabled by default on local machines
  • Uses filesystem sessions and direct database queries
  • No Redis installation required for local development

Docker/Azure Deployments:

  • Redis is automatically used for both sessions and caching
  • Provides 50-90% faster response times for cached queries
  • Automatic cache invalidation ensures data consistency
  • Docker: Redis is configured with password authentication (matches Azure approach)
  • Azure: Uses Azure Redis Cache with SSL and connection string format (host:port,password=...,ssl=True)

Cache Invalidation Strategy:

  • Direct updates invalidate the entity and related entities
  • Cascading invalidation ensures all dependent data is refreshed
  • Pattern-based invalidation for list queries

Production Deployment

For production deployment:

  1. Update environment variables with secure values
  2. Set up SSL certificates for HTTPS
  3. Use production Docker Compose file:
    ./START.sh prod
  4. Configure Nginx for reverse proxy and SSL termination

See Azure Deployment section for cloud deployment options.

API Documentation

Authentication Endpoints

Passwordless Registration (Step 1: Start Registration)

POST /api/auth/register-passwordlessContent-Type: application/json
{
"username": "username",
"email": "user@example.com"
}
Response 201:
{
"success": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Verification code sent to your email"
}

Verify Email (Step 2)

POST /api/auth/verify-emailContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}
Response 200:
{
"success": true,
"totp_qr_data": "otpauth://totp/TopicsFlow:username?secret=...",
"totp_secret": "JBSWY3DPEHPK3PXP",
"user_id": "507f1f77bcf86cd799439011"
}

Complete TOTP Setup (Step 3)

POST /api/auth/complete-totp-setupContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"totp_code": "123456"
}
Response 200:
{
"success": true,
"backup_codes": ["12345678", "23456789", ...]
}

Passwordless Login

POST /api/auth/login-passwordlessContent-Type: application/json
{
"identifier": "username", // username or email"totp_code": "123456"
}
Response 200:
{
"success": true,
"user": {
"id": "507f1f77bcf86cd799439011",
"username": "username",
"email": "user@example.com"
}
}

Response 200 (Email 2FA Required):

{
"success": false,
"require_email_2fa": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Please check your email for the verification code"
}

Verify Login Email 2FA

POST /api/auth/verify-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}

Resend Login Email 2FA Code

POST /api/auth/resend-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011"
}
Response 200:
{
"success": true,
"message": "Verification code sent.",
"cooldown": 60
}

Account Recovery

POST /api/auth/recovery/initiate-passwordlessContent-Type: application/json
{
"email": "user@example.com"
}
POST /api/auth/recovery/verify-email-codeContent-Type: application/json
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/recovery/reset-totpContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"original_secret": "JBSWY3DPEHPK3PXP"// Saved during registration
}

Topic Endpoints

Get Topics

GET /api/topics?sort_by=last_activity&limit=20&offset=0&tags=chat,gaming&search=gaming

Create Topic

POST /api/topicsContent-Type: application/jsonAuthorization: Session cookie
{
"title": "Topic Title",
"description": "Topic description",
"tags": ["chat", "gaming"],
"allow_anonymous": true,
"require_approval": false
}

Message Endpoints

Get Topic Messages

GET /api/messages/topic/{topic_id}?limit=50&before_message_id={message_id}

Send Message

POST /api/messages/topic/{topic_id}Content-Type: application/jsonAuthorization: Session cookie
{
"content": "Hello, world!",
"message_type": "text",
"use_anonymous": false,
"gif_url": "https://example.com/gif.gif"
}

Database Schema

Users Collection

{_id: ObjectId,username: String(unique,validated),email: String(unique),phone: String(optional,forrecovery),password_hash: String,totp_secret: String(encrypted),totp_enabled: Boolean,security_questions: [Array],is_banned: Boolean,ban_reason: String,ban_expiry: Date,ip_addresses: [String],created_at: Date,last_login: Date,preferences: {theme: String('dark'|'light'),language: String('en'|'pt'),anonymous_mode: Boolean}}

Topics Collection

{_id: ObjectId,title: String,description: String,owner_id: ObjectId,moderators: [{user_id: ObjectId,added_by: ObjectId,added_at: Date,permissions: [String]}],tags: [String],member_count: Number,is_public: Boolean,created_at: Date,last_activity: Date,settings: {allow_anonymous: Boolean,require_approval: Boolean}}

Messages Collection

{_id: ObjectId,topic_id: ObjectId,user_id: ObjectId,content: String,topic_id: ObjectId,chat_room_id: ObjectId,// For chat room messagesuser_id: ObjectId,content: String,message_type: String('text'|'emoji'|'gif'|'image'|'video'|'file'|'system'),anonymous_identity: String,gif_url: String,attachments: [{// File references (not base64 data)type: String,file_id: String,url: String,filename: String,size: Number,mime_type: String}],is_deleted: Boolean,deleted_by: ObjectId,deleted_at: Date,deletion_reason: String,// For owner deletionsreports: [{reported_by: ObjectId,reason: String,created_at: Date}],created_at: Date,updated_at: Date}

Chat Rooms Collection

{_id: ObjectId,topic_id: ObjectId,name: String,description: String,owner_id: ObjectId,moderators: [ObjectId],members: [ObjectId],picture: String,// Base64 profile picturebackground_picture: String,// Base64 background imageis_public: Boolean,created_at: Date,updated_at: Date}

Private Messages Collection

{_id: ObjectId,from_user_id: ObjectId,to_user_id: ObjectId,content: String,message_type: String,gif_url: String,deleted_for_user_ids: [ObjectId],// Soft delete per useris_read: Boolean,read_at: Date,created_at: Date}

Reports Collection

{_id: ObjectId,reporter_id: ObjectId,reported_user_id: ObjectId,content_id: String,// Message, post, comment, or chatroom IDcontent_type: String,// 'user' | 'message' | 'post' | 'comment' | 'chatroom' | 'chatroom_background' | 'chatroom_picture'reason: String,description: String,owner_id: ObjectId,// For chatroom/content reportsowner_username: String,moderators: [{id: ObjectId,username: String}],// For admin analysisstatus: String,created_at: Date}

Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    python app.py
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker run -d --name mongodb -p 27017:27017 mongo:7.0
    # Start Redis
    docker run -d --name redis -p 6379:6379 redis:7.2-alpine

Testing

Quick Testing Guide

# 1. Migrate database
python migrate_database.py migrate
# 2. Make admin user
python make_admin.py <username># 3. Start backendcd backend && python app.py
# 4. Start frontendcd frontend && npm run dev
# 5. Access app
http://localhost:3000

Test Scenarios

  1. Admin Controls: Login as admin, check for shield icon (🛡️) in top bar
  2. Clickable Usernames: Click username in chat → user banner appears
  3. Right-Click Menu: Right-click username → context menu with options
  4. Report User: Right-click → Report User → fill form → submit
  5. Ticket Creation: Profile menu → Open Ticket → create ticket
  6. Anonymous Mode: Enable "Use Anonymous" toggle in chat

Backend API Testing

Using Postman:

  1. Import tests/TopicsFlow_API.postman_collection.json
  2. Import environment file from tests/postman/environments/
  3. Run collection tests

Using Newman (CLI):

npm install -g newman newman-reporter-html
newman run tests/postman/TopicsFlow_Backend_API.postman_collection.json \
-e tests/postman/environments/Local.postman_environment.json \
-r html --reporter-html-export tests/reports/report.html

WebSocket Testing:

  • Use browser DevTools console
  • See tests/postman/TopicsFlow_WebSocket_Tests.md for detailed instructions

For comprehensive testing documentation, see:

  • TESTING_GUIDE.md - Quick testing scenarios
  • TEST_PLAN.md - Comprehensive test plan
  • tests/TESTING_GUIDE.md - Backend API testing guide
  • tests/TEST_TROUBLESHOOTING.md - Test troubleshooting

Code Quality

# Backend lintingcd backend
flake8 .
black .# Frontend lintingcd frontend
npm run lint
npm run type-check

Security Considerations

  • TOTP Secrets: Encrypted at rest using AES-256
  • Passwords: Hashed with bcrypt
  • Sessions: Secure session management with HTTP-only cookies
  • Rate Limiting: Implemented on all sensitive endpoints
  • Input Validation: Comprehensive validation and sanitization
  • HTTPS: Enforced in production
  • CORS: Properly configured for frontend domain
  • Content Security Policy: Headers implemented for XSS prevention

Monitoring & Logging

Application Logs

# View all service logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f backend
docker-compose logs -f frontend

Health Checks

  • Backend: GET /health
  • Frontend: HTTP status checks
  • Database: Connection health monitoring

Azure Deployment

Quick Start (5 minutes)

# 1. Install Azure CLI# Linux/Mac: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash# Windows: Download from https://aka.ms/installazurecliwindows# 2. Login to Azure
az login
# 3. Configure variables
cp .env.azure.example .env.azure
# Edit .env.azure with your values# 4. Deployexport$(cat .env.azure | xargs)
./azure-deploy.sh

Architecture

  • Backend: Flask + SocketIO + Static Frontend (served by Flask)
  • Database: Azure CosmosDB (MongoDB API)
  • Cache: Azure Cache for Redis (optional)
  • Deployment: Azure Container Apps
  • SSL: Automatic HTTPS

Environment Detection

The application automatically detects Azure environment via:

  • WEBSITE_INSTANCE_ID
  • AZURE_COSMOS_CONNECTIONSTRING

When detected, it automatically:

  • Uses CosmosDB instead of MongoDB
  • Configures SSL connections
  • Disables retryWrites (not supported by CosmosDB)
  • Serves static frontend

Required Azure Resources

  • Azure Container Registry (ACR)
  • Azure CosmosDB (MongoDB API)
  • Azure Container Apps Environment
  • Azure Container App

Cost Estimate

  • Container Apps: ~$40/month
  • CosmosDB: ~$24/month
  • Redis Cache: ~$16/month (optional)
  • Container Registry: ~$5/month
  • Total: ~$85/month (or ~$69 without Redis)

CI/CD with GitHub Actions

  1. Configure GitHub Secrets:

    • AZURE_CREDENTIALS - Service Principal JSON
    • AZURE_CONTAINER_REGISTRY - ACR name
    • AZURE_RESOURCE_GROUP - Resource group name
    • AZURE_APP_NAME - Container App name
    • ACR_USERNAME - ACR username
    • ACR_PASSWORD - ACR password
  2. Push to trigger deployment:

    git push origin main

See GITHUB_ACTIONS_SETUP.md for detailed CI/CD setup instructions.

For complete Azure deployment documentation, see:

  • AZURE_DEPLOYMENT.md - Comprehensive deployment guide
  • AZURE_QUICKSTART.md - Quick start guide

Troubleshooting

Common Issues

  1. Services won't start

    # Check if ports are available# Windows
    netstat -ano | findstr :5000
    taskkill /PID <number> /F
    # Linux/Mac
    lsof -i :3000
    lsof -i :5000
    lsof -i :27017
    lsof -i :6379
    # Clean and restart
    docker-compose down -v
    docker system prune -f
    ./START.sh
  2. Database connection issues

    # Check MongoDB logs
    docker-compose logs mongodb
    # Connect to MongoDB directly
    docker-compose exec mongodb mongosh
  3. TOTP authentication issues

    • Ensure server time is synchronized
    • Check TOTP secret encryption
    • Verify authenticator app time sync
    • Codes expire every 30 seconds - use current code
  4. Frontend build issues

    # Clear Next.js cache
    rm -rf .next
    npm run build
  5. Email not sending

    • Verify Resend API key is set: echo $RESEND_API_KEY
    • Check domain is verified in Resend dashboard
    • Verify FROM_EMAIL uses verified domain
    • Check backend logs for errors
  6. bcrypt module not found (Windows)

    # Solution 1: Reinstall bcrypt
    pip uninstall -y bcrypt
    pip install --only-binary :all: bcrypt==4.1.0
    # Solution 2: Install Visual Studio Build Tools# Download from https://visualstudio.microsoft.com/downloads/# Install "Desktop development with C++"# Solution 3: Use compatible version
    pip install bcrypt==4.0.1
  7. Port already in use (Windows)

    netstat -ano |findstr :5000
    taskkill /PID <number> /F
  8. MongoDB connection failed

    # Check if MongoDB is running
    docker ps | findstr mongodb
    # Start MongoDB
    docker start mongodb-test
    # Or create new container
    docker run -d --name mongodb-test -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    mongo:7.0

For Windows-specific troubleshooting, see WINDOWS_TROUBLESHOOTING.md.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test and python -m pytest
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow existing code patterns
  • Write tests for new features
  • Update documentation
  • Use descriptive commit messages
  • Keep PRs focused and manageable

License

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

Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section above
  • Review the API documentation

Acknowledgments

  • Built with Flask, Next.js, MongoDB, and Socket.IO
  • Inspired by Reddit's community structure
  • TOTP authentication standards
  • Open source libraries and frameworks used

About

Chat application that features publications and chatrooms by topic and direct messages and groups.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - 8JP8/TopicsFlow: Chat application that features publications and chatrooms by topic and direct messages and groups. · GitHub
Skip to content

Latest commit

History

161 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TopicsFlow App

📚 Comprehensive Documentation: Check out the Project Wiki for detailed guides on Architecture, API, Deployment, and more.

Overview

TopicsFlow is a comprehensive chat and topic discussion platform designed to facilitate focused conversations and community interactions.

🔐 Security & Authentication

  • Passwordless Authentication: Users log in via email/username + 6-digit TOTP code.
  • TOTP-based 2FA: Full compatibility with Google Authenticator, Microsoft Authenticator, and Authy.
  • Robust Account Recovery: Multi-step recovery using email verification and original TOTP secrets.
  • Backup Codes: 10 high-entropy emergency access codes provided during setup.
  • Secure Sessions: Encrypted session storage in Redis (Azure/Docker) or filesystem (local) with proper cookie security (HttpOnly).
  • Intelligent Caching: Redis-based caching system for database queries with automatic cache invalidation. Dramatically improves performance (50-90% faster response times) while ensuring data consistency.
  • Advanced Banning: Global banning system targeting IP addresses, emails, and phone numbers.

💬 Real-time Communication

  • Hybrid Platform: Seamless integration between Reddit-style forums and instant chat rooms.
  • WebSocket Foundation: Built on Socket.IO for sub-100ms latency.
  • Presence System: Real-time "online" status and typing indicators across the entire app.
  • Group Chat Rooms: Unlimited rooms per Topic with customizable profile/background images.
  • Direct Messaging (DMs): Private 1-on-1 conversations with encryption-ready architecture.
  • Voice Communication (VOIP): Integrated voice rooms with participant lists and active speaker detection.
  • Media Engine: Instant sharing of GIFs (Tenor), images, videos, and files with secure cloud storage.
  • Anonymous Mode: Per-topic identity masking with custom aliases to encourage open discussion.

📝 Content Management (The "Publications" System)

  • Dynamic Topics: Hierarchical community spaces for high-level categorization.
  • Publications (Posts): Reddit-style nested posts with rich text (Markdown) support.
  • Voting Mechanism: Positive/Negative reputation system for quality control.
  • Threaded Comments: Deeply nested conversations with @mentions and reply tracking.
  • Navigation Controls: Advanced sorting (Hot, New, Top) and tag-based discovery.
  • Search Engine: Rapid indexing of topics and posts for easy discovery.

🛡️ Moderation & Support

  • Admin Dashboard: Centralized command center for platform-wide oversight.
  • Integrated Ticket System: Direct communication channel between users and administrators for help requests.
  • Report Lifecycle: Comprehensive reporting for users/messages/posts with automated context attachment.
  • Role-based Access Control (RBAC): Granular permissions system (Owner -> Moderator -> Member).
  • Content Filtering: Integrated profanity filters and link sanitization.

🎨 Design & Accessibility

  • Responsive Architecture: Pixel-perfect layouts for Mobile, Tablet, and Desktop.
  • Modern Theme Engine: Dynamic Dark/Light mode switching with cohesive HSL color palettes.
  • Internationalization (i18n): Native-level support for English and Portuguese.
  • PWA Capabilities: Installable web app with push notifications and offline caching.
  • Accessibility: ARIA-compliant components and keyboard-friendly navigation.

Technology Stack

Backend

  • Flask (Python web framework)
  • Flask-SocketIO (real-time WebSocket communication)
  • MongoDB (NoSQL database)
  • PyOTP (TOTP authentication)
  • Redis (session storage and intelligent database caching with automatic invalidation)

Frontend

  • Next.js with TypeScript
  • Socket.IO Client (real-time communication)
  • Tailwind CSS (styling with theme variables)
  • React Hot Toast (notifications)
  • PWA capabilities with service workers and native install prompts
  • Image Viewer Modal: Full-screen image viewing with download controls
  • Enhanced Video Player: Fullscreen support, download, and right-click context menu
  • Context Menus: Right-click menus for posts, messages, chatrooms, and users

Infrastructure

  • Docker with multi-stage builds
  • Docker Compose for orchestration
  • Nginx reverse proxy (production)
  • Environment-based configuration

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local development)
  • Python 3.11+ (for local development)
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>cd RINTEP2
  2. Start the application

    ./START.sh

    This will:

    • Check prerequisites
    • Set up environment variables
    • Create necessary directories
    • Start all services (MongoDB, Redis, Backend, Frontend)
    • Wait for services to be healthy
  3. Access the application

Manual Setup (Alternative)

If you prefer to set up manually:

  1. Set up environment variables

    # Backend
    cp backend/env.example backend/.env
    # Frontend
    cp frontend/env.local.example frontend/.env.local
    # Edit the copied files with your configuration
  2. Start services with Docker Compose

    docker-compose up --build
  3. Or run locally for development

    Backend:

    cd backend
    python -m venv venv
    source venv/bin/activate # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python app.py

    Frontend:

    cd frontend
    npm install
    npm run dev

Configuration

Environment Variables

The application uses environment variables for configuration. You can set them up automatically or manually.

Automatic Setup (Recommended)

Windows:

setup-env.bat

Linux/Mac:

chmod +x setup-env.sh
./setup-env.sh

PowerShell:

powershell -ExecutionPolicy Bypass -File setup-env.ps1

Manual Setup

Create a .env file in the backend/ directory:

# Database ConfigurationDATABASE_URL=mongodb://localhost:27017/TopicsFlowREDIS_URL=redis://localhost:6379/0# Application ConfigurationSECRET_KEY=your_super_secret_key_hereFRONTEND_URL=http://localhost:3000TOTP_ISSUER=TopicsFlowAPP_NAME=TopicsFlow# Email Service (Resend)RESEND_API_KEY=your_resend_api_keyFROM_EMAIL=noreply@topicsflow.me# External ServicesTENOR_API_KEY=your_tenor_api_key# File Storage (Optional - for Azure deployments)USE_AZURE_STORAGE=falseAZURE_STORAGE_CONNECTION_STRING=your_azure_storage_connection_stringAZURE_STORAGE_CONTAINER=uploadsFILE_ENCRYPTION_KEY=your_file_encryption_key# Optional, defaults to SECRET_KEY# ImgBB (Optional - for large chatroom images)USE_IMGBB=falseIMGBB_API_KEY=your_imgbb_api_keyIMGBB_EXPIRATION_SECONDS=600IMGBB_MAX_BASE64_SIZE_BYTES=2097152# CORS (Development)CORS_ALLOW_ALL=true

Environment variables reference (Local + Azure)

You can use these example templates:

  • backend/env.example → copy to backend/.env
  • frontend/env.local.example → copy to frontend/.env.local

Backend (local development)

VariableDescriptionRequired
SECRET_KEYFlask secret key✅ Yes
ENVIRONMENTdevelopment/production (affects cookie security)Recommended
DATABASE_URLMongoDB connection string✅ Yes
DB_NAMEMongoDB database nameRecommended
REDIS_URLRedis connection string (sessions/rate limit)Recommended
FRONTEND_URLFrontend origin (CORS + passkeys)✅ Yes
CORS_ALLOW_ALLAllow all origins in devOptional
RESEND_API_KEYResend email API key✅ Yes
FROM_EMAILVerified sender email✅ Yes
APP_NAMEApp name used in emailsRecommended
TENOR_API_KEYTenor API key for GIF searchOptional
TENOR_CLIENT_KEYTenor client key (defaults to topicsflow_app)Optional
PASSKEY_RP_IDWebAuthn RP ID (defaults to localhost)Optional
LOG_LEVELLogging levelOptional

Backend storage (attachments)

VariableDescriptionRequired
USE_AZURE_STORAGEUse Azure Blob Storage for attachmentsOptional
AZURE_STORAGE_CONNECTION_STRINGAzure Storage connection stringRequired if USE_AZURE_STORAGE=true
AZURE_STORAGE_CONTAINERBlob container name (use uploads)Required if USE_AZURE_STORAGE=true
API_BASE_URLUsed to build attachment URLsRecommended
FILE_ENCRYPTION_KEYOptional encryption key for attachment URLs (defaults to SECRET_KEY)Optional

Backend ImgBB (recomended)

VariableDescriptionRequired
USE_IMGBBEnable ImgBB uploads for large imagesOptional
IMGBB_API_KEYImgBB API keyRequired if USE_IMGBB=true
IMGBB_EXPIRATION_SECONDSOptional ImgBB expirationOptional
IMGBB_MAX_BASE64_SIZE_BYTESThreshold to upload to ImgBBOptional

Backend (Azure/CosmosDB Mongo API)

VariableDescriptionRequired
AZURE_COSMOS_CONNECTIONSTRINGCosmosDB (Mongo API) connection string✅ Yes (Azure)
AZURE_COSMOS_DATABASECosmos database name✅ Yes (Azure)
COSMOS_DB_URI / COSMOS_DB_NAMEAlternative Cosmos env names supported by configOptional
AZURE_DEPLOYMENTSet to true to force Azure modeOptional
FORCE_AZURE_MODE / FORCE_LOCAL_MODEForce environment detectionOptional

Backend (Redis - Azure/Docker only)

VariableDescriptionRequired
AZURE_REDIS_CONNECTIONSTRINGAzure Redis Cache connection string (format: host:port,password=...,ssl=True)Optional (Azure only)
REDIS_URLRedis connection string (format: redis://password@host:port/0)Optional (Docker/Azure)
REDIS_PASSWORDRedis password (used in Docker Compose)Optional (Docker)
SESSION_TYPESession backend: filesystem (local) or redis (Docker/Azure)Auto-detected

Note: Redis is automatically disabled for local development (non-Docker). The application uses filesystem sessions and direct database queries when running locally without Docker.

Frontend

VariableDescriptionRequired
NEXT_PUBLIC_API_URLBackend base URL✅ Yes
NEXT_PUBLIC_APP_NAMEApp nameOptional
NEXT_PUBLIC_TENOR_API_KEYTenor API key (only if frontend uses it directly)Optional

Email Service Setup (Resend)

  1. Get your API key from Resend Dashboard
  2. Verify your domain in Resend Domains
  3. Add DNS records provided by Resend to your domain
  4. Set FROM_EMAIL to use your verified domain

Tenor API Setup

  1. Go to Tenor Developer Portal
  2. Sign in with Google account
  3. Create a new API key
  4. Add TENOR_API_KEY to your .env file

Passwordless Authentication

The application uses passwordless authentication with TOTP (Time-based One-Time Password):

  • No passwords - Users authenticate with username/email + 6-digit authenticator code
  • Email verification - Required during registration (6-digit codes)
  • TOTP 2FA - Industry-standard authenticator apps (Google Authenticator, Authy, etc.)
  • Backup codes - Emergency access codes for account recovery
  • Secure recovery - Requires email verification + original TOTP secret

User Registration Flow:

  1. Enter username and email
  2. Verify email with 6-digit code
  3. Setup authenticator app (scan QR code or manual entry)
  4. Verify TOTP code
  5. Save backup codes

User Login Flow:

  1. Enter username/email
  2. Enter 6-digit code from authenticator app

Account Recovery:

  1. Enter email → receive verification code
  2. Verify email code
  3. Enter original TOTP secret (saved during registration)
  4. Setup new authenticator
  5. Get new backup codes

⚠️ Important: Users must save their TOTP secret during registration for account recovery!

Caching System

TopicsFlow includes an intelligent Redis-based caching system that dramatically improves performance:

Features:

  • Automatic Caching: All database queries are automatically cached with appropriate TTLs
    • Static data (users, topics): 1 hour cache
    • Dynamic data (posts, comments, messages): 5 minutes cache
  • Automatic Invalidation: Cache is automatically invalidated when data is updated, ensuring consistency
  • Graceful Fallback: If Redis is unavailable, the application automatically falls back to direct database queries
  • Zero Configuration: Works automatically in Docker/Azure deployments with Redis

Local Development:

  • Redis cache is disabled by default on local machines
  • Uses filesystem sessions and direct database queries
  • No Redis installation required for local development

Docker/Azure Deployments:

  • Redis is automatically used for both sessions and caching
  • Provides 50-90% faster response times for cached queries
  • Automatic cache invalidation ensures data consistency
  • Docker: Redis is configured with password authentication (matches Azure approach)
  • Azure: Uses Azure Redis Cache with SSL and connection string format (host:port,password=...,ssl=True)

Cache Invalidation Strategy:

  • Direct updates invalidate the entity and related entities
  • Cascading invalidation ensures all dependent data is refreshed
  • Pattern-based invalidation for list queries

Production Deployment

For production deployment:

  1. Update environment variables with secure values
  2. Set up SSL certificates for HTTPS
  3. Use production Docker Compose file:
    ./START.sh prod
  4. Configure Nginx for reverse proxy and SSL termination

See Azure Deployment section for cloud deployment options.

API Documentation

Authentication Endpoints

Passwordless Registration (Step 1: Start Registration)

POST /api/auth/register-passwordlessContent-Type: application/json
{
"username": "username",
"email": "user@example.com"
}
Response 201:
{
"success": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Verification code sent to your email"
}

Verify Email (Step 2)

POST /api/auth/verify-emailContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}
Response 200:
{
"success": true,
"totp_qr_data": "otpauth://totp/TopicsFlow:username?secret=...",
"totp_secret": "JBSWY3DPEHPK3PXP",
"user_id": "507f1f77bcf86cd799439011"
}

Complete TOTP Setup (Step 3)

POST /api/auth/complete-totp-setupContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"totp_code": "123456"
}
Response 200:
{
"success": true,
"backup_codes": ["12345678", "23456789", ...]
}

Passwordless Login

POST /api/auth/login-passwordlessContent-Type: application/json
{
"identifier": "username", // username or email"totp_code": "123456"
}
Response 200:
{
"success": true,
"user": {
"id": "507f1f77bcf86cd799439011",
"username": "username",
"email": "user@example.com"
}
}

Response 200 (Email 2FA Required):

{
"success": false,
"require_email_2fa": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Please check your email for the verification code"
}

Verify Login Email 2FA

POST /api/auth/verify-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}

Resend Login Email 2FA Code

POST /api/auth/resend-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011"
}
Response 200:
{
"success": true,
"message": "Verification code sent.",
"cooldown": 60
}

Account Recovery

POST /api/auth/recovery/initiate-passwordlessContent-Type: application/json
{
"email": "user@example.com"
}
POST /api/auth/recovery/verify-email-codeContent-Type: application/json
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/recovery/reset-totpContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"original_secret": "JBSWY3DPEHPK3PXP"// Saved during registration
}

Topic Endpoints

Get Topics

GET /api/topics?sort_by=last_activity&limit=20&offset=0&tags=chat,gaming&search=gaming

Create Topic

POST /api/topicsContent-Type: application/jsonAuthorization: Session cookie
{
"title": "Topic Title",
"description": "Topic description",
"tags": ["chat", "gaming"],
"allow_anonymous": true,
"require_approval": false
}

Message Endpoints

Get Topic Messages

GET /api/messages/topic/{topic_id}?limit=50&before_message_id={message_id}

Send Message

POST /api/messages/topic/{topic_id}Content-Type: application/jsonAuthorization: Session cookie
{
"content": "Hello, world!",
"message_type": "text",
"use_anonymous": false,
"gif_url": "https://example.com/gif.gif"
}

Database Schema

Users Collection

{_id: ObjectId,username: String(unique,validated),email: String(unique),phone: String(optional,forrecovery),password_hash: String,totp_secret: String(encrypted),totp_enabled: Boolean,security_questions: [Array],is_banned: Boolean,ban_reason: String,ban_expiry: Date,ip_addresses: [String],created_at: Date,last_login: Date,preferences: {theme: String('dark'|'light'),language: String('en'|'pt'),anonymous_mode: Boolean}}

Topics Collection

{_id: ObjectId,title: String,description: String,owner_id: ObjectId,moderators: [{user_id: ObjectId,added_by: ObjectId,added_at: Date,permissions: [String]}],tags: [String],member_count: Number,is_public: Boolean,created_at: Date,last_activity: Date,settings: {allow_anonymous: Boolean,require_approval: Boolean}}

Messages Collection

{_id: ObjectId,topic_id: ObjectId,user_id: ObjectId,content: String,topic_id: ObjectId,chat_room_id: ObjectId,// For chat room messagesuser_id: ObjectId,content: String,message_type: String('text'|'emoji'|'gif'|'image'|'video'|'file'|'system'),anonymous_identity: String,gif_url: String,attachments: [{// File references (not base64 data)type: String,file_id: String,url: String,filename: String,size: Number,mime_type: String}],is_deleted: Boolean,deleted_by: ObjectId,deleted_at: Date,deletion_reason: String,// For owner deletionsreports: [{reported_by: ObjectId,reason: String,created_at: Date}],created_at: Date,updated_at: Date}

Chat Rooms Collection

{_id: ObjectId,topic_id: ObjectId,name: String,description: String,owner_id: ObjectId,moderators: [ObjectId],members: [ObjectId],picture: String,// Base64 profile picturebackground_picture: String,// Base64 background imageis_public: Boolean,created_at: Date,updated_at: Date}

Private Messages Collection

{_id: ObjectId,from_user_id: ObjectId,to_user_id: ObjectId,content: String,message_type: String,gif_url: String,deleted_for_user_ids: [ObjectId],// Soft delete per useris_read: Boolean,read_at: Date,created_at: Date}

Reports Collection

{_id: ObjectId,reporter_id: ObjectId,reported_user_id: ObjectId,content_id: String,// Message, post, comment, or chatroom IDcontent_type: String,// 'user' | 'message' | 'post' | 'comment' | 'chatroom' | 'chatroom_background' | 'chatroom_picture'reason: String,description: String,owner_id: ObjectId,// For chatroom/content reportsowner_username: String,moderators: [{id: ObjectId,username: String}],// For admin analysisstatus: String,created_at: Date}

Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    python app.py
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker run -d --name mongodb -p 27017:27017 mongo:7.0
    # Start Redis
    docker run -d --name redis -p 6379:6379 redis:7.2-alpine

Testing

Quick Testing Guide

# 1. Migrate database
python migrate_database.py migrate
# 2. Make admin user
python make_admin.py <username># 3. Start backendcd backend && python app.py
# 4. Start frontendcd frontend && npm run dev
# 5. Access app
http://localhost:3000

Test Scenarios

  1. Admin Controls: Login as admin, check for shield icon (🛡️) in top bar
  2. Clickable Usernames: Click username in chat → user banner appears
  3. Right-Click Menu: Right-click username → context menu with options
  4. Report User: Right-click → Report User → fill form → submit
  5. Ticket Creation: Profile menu → Open Ticket → create ticket
  6. Anonymous Mode: Enable "Use Anonymous" toggle in chat

Backend API Testing

Using Postman:

  1. Import tests/TopicsFlow_API.postman_collection.json
  2. Import environment file from tests/postman/environments/
  3. Run collection tests

Using Newman (CLI):

npm install -g newman newman-reporter-html
newman run tests/postman/TopicsFlow_Backend_API.postman_collection.json \
-e tests/postman/environments/Local.postman_environment.json \
-r html --reporter-html-export tests/reports/report.html

WebSocket Testing:

  • Use browser DevTools console
  • See tests/postman/TopicsFlow_WebSocket_Tests.md for detailed instructions

For comprehensive testing documentation, see:

  • TESTING_GUIDE.md - Quick testing scenarios
  • TEST_PLAN.md - Comprehensive test plan
  • tests/TESTING_GUIDE.md - Backend API testing guide
  • tests/TEST_TROUBLESHOOTING.md - Test troubleshooting

Code Quality

# Backend lintingcd backend
flake8 .
black .# Frontend lintingcd frontend
npm run lint
npm run type-check

Security Considerations

  • TOTP Secrets: Encrypted at rest using AES-256
  • Passwords: Hashed with bcrypt
  • Sessions: Secure session management with HTTP-only cookies
  • Rate Limiting: Implemented on all sensitive endpoints
  • Input Validation: Comprehensive validation and sanitization
  • HTTPS: Enforced in production
  • CORS: Properly configured for frontend domain
  • Content Security Policy: Headers implemented for XSS prevention

Monitoring & Logging

Application Logs

# View all service logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f backend
docker-compose logs -f frontend

Health Checks

  • Backend: GET /health
  • Frontend: HTTP status checks
  • Database: Connection health monitoring

Azure Deployment

Quick Start (5 minutes)

# 1. Install Azure CLI# Linux/Mac: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash# Windows: Download from https://aka.ms/installazurecliwindows# 2. Login to Azure
az login
# 3. Configure variables
cp .env.azure.example .env.azure
# Edit .env.azure with your values# 4. Deployexport$(cat .env.azure | xargs)
./azure-deploy.sh

Architecture

  • Backend: Flask + SocketIO + Static Frontend (served by Flask)
  • Database: Azure CosmosDB (MongoDB API)
  • Cache: Azure Cache for Redis (optional)
  • Deployment: Azure Container Apps
  • SSL: Automatic HTTPS

Environment Detection

The application automatically detects Azure environment via:

  • WEBSITE_INSTANCE_ID
  • AZURE_COSMOS_CONNECTIONSTRING

When detected, it automatically:

  • Uses CosmosDB instead of MongoDB
  • Configures SSL connections
  • Disables retryWrites (not supported by CosmosDB)
  • Serves static frontend

Required Azure Resources

  • Azure Container Registry (ACR)
  • Azure CosmosDB (MongoDB API)
  • Azure Container Apps Environment
  • Azure Container App

Cost Estimate

  • Container Apps: ~$40/month
  • CosmosDB: ~$24/month
  • Redis Cache: ~$16/month (optional)
  • Container Registry: ~$5/month
  • Total: ~$85/month (or ~$69 without Redis)

CI/CD with GitHub Actions

  1. Configure GitHub Secrets:

    • AZURE_CREDENTIALS - Service Principal JSON
    • AZURE_CONTAINER_REGISTRY - ACR name
    • AZURE_RESOURCE_GROUP - Resource group name
    • AZURE_APP_NAME - Container App name
    • ACR_USERNAME - ACR username
    • ACR_PASSWORD - ACR password
  2. Push to trigger deployment:

    git push origin main

See GITHUB_ACTIONS_SETUP.md for detailed CI/CD setup instructions.

For complete Azure deployment documentation, see:

  • AZURE_DEPLOYMENT.md - Comprehensive deployment guide
  • AZURE_QUICKSTART.md - Quick start guide

Troubleshooting

Common Issues

  1. Services won't start

    # Check if ports are available# Windows
    netstat -ano | findstr :5000
    taskkill /PID <number> /F
    # Linux/Mac
    lsof -i :3000
    lsof -i :5000
    lsof -i :27017
    lsof -i :6379
    # Clean and restart
    docker-compose down -v
    docker system prune -f
    ./START.sh
  2. Database connection issues

    # Check MongoDB logs
    docker-compose logs mongodb
    # Connect to MongoDB directly
    docker-compose exec mongodb mongosh
  3. TOTP authentication issues

    • Ensure server time is synchronized
    • Check TOTP secret encryption
    • Verify authenticator app time sync
    • Codes expire every 30 seconds - use current code
  4. Frontend build issues

    # Clear Next.js cache
    rm -rf .next
    npm run build
  5. Email not sending

    • Verify Resend API key is set: echo $RESEND_API_KEY
    • Check domain is verified in Resend dashboard
    • Verify FROM_EMAIL uses verified domain
    • Check backend logs for errors
  6. bcrypt module not found (Windows)

    # Solution 1: Reinstall bcrypt
    pip uninstall -y bcrypt
    pip install --only-binary :all: bcrypt==4.1.0
    # Solution 2: Install Visual Studio Build Tools# Download from https://visualstudio.microsoft.com/downloads/# Install "Desktop development with C++"# Solution 3: Use compatible version
    pip install bcrypt==4.0.1
  7. Port already in use (Windows)

    netstat -ano |findstr :5000
    taskkill /PID <number> /F
  8. MongoDB connection failed

    # Check if MongoDB is running
    docker ps | findstr mongodb
    # Start MongoDB
    docker start mongodb-test
    # Or create new container
    docker run -d --name mongodb-test -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    mongo:7.0

For Windows-specific troubleshooting, see WINDOWS_TROUBLESHOOTING.md.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test and python -m pytest
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow existing code patterns
  • Write tests for new features
  • Update documentation
  • Use descriptive commit messages
  • Keep PRs focused and manageable

License

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

Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section above
  • Review the API documentation

Acknowledgments

  • Built with Flask, Next.js, MongoDB, and Socket.IO
  • Inspired by Reddit's community structure
  • TOTP authentication standards
  • Open source libraries and frameworks used

About

Chat application that features publications and chatrooms by topic and direct messages and groups.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - 8JP8/TopicsFlow: Chat application that features publications and chatrooms by topic and direct messages and groups. · GitHub
Skip to content

Latest commit

History

161 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TopicsFlow App

📚 Comprehensive Documentation: Check out the Project Wiki for detailed guides on Architecture, API, Deployment, and more.

Overview

TopicsFlow is a comprehensive chat and topic discussion platform designed to facilitate focused conversations and community interactions.

🔐 Security & Authentication

  • Passwordless Authentication: Users log in via email/username + 6-digit TOTP code.
  • TOTP-based 2FA: Full compatibility with Google Authenticator, Microsoft Authenticator, and Authy.
  • Robust Account Recovery: Multi-step recovery using email verification and original TOTP secrets.
  • Backup Codes: 10 high-entropy emergency access codes provided during setup.
  • Secure Sessions: Encrypted session storage in Redis (Azure/Docker) or filesystem (local) with proper cookie security (HttpOnly).
  • Intelligent Caching: Redis-based caching system for database queries with automatic cache invalidation. Dramatically improves performance (50-90% faster response times) while ensuring data consistency.
  • Advanced Banning: Global banning system targeting IP addresses, emails, and phone numbers.

💬 Real-time Communication

  • Hybrid Platform: Seamless integration between Reddit-style forums and instant chat rooms.
  • WebSocket Foundation: Built on Socket.IO for sub-100ms latency.
  • Presence System: Real-time "online" status and typing indicators across the entire app.
  • Group Chat Rooms: Unlimited rooms per Topic with customizable profile/background images.
  • Direct Messaging (DMs): Private 1-on-1 conversations with encryption-ready architecture.
  • Voice Communication (VOIP): Integrated voice rooms with participant lists and active speaker detection.
  • Media Engine: Instant sharing of GIFs (Tenor), images, videos, and files with secure cloud storage.
  • Anonymous Mode: Per-topic identity masking with custom aliases to encourage open discussion.

📝 Content Management (The "Publications" System)

  • Dynamic Topics: Hierarchical community spaces for high-level categorization.
  • Publications (Posts): Reddit-style nested posts with rich text (Markdown) support.
  • Voting Mechanism: Positive/Negative reputation system for quality control.
  • Threaded Comments: Deeply nested conversations with @mentions and reply tracking.
  • Navigation Controls: Advanced sorting (Hot, New, Top) and tag-based discovery.
  • Search Engine: Rapid indexing of topics and posts for easy discovery.

🛡️ Moderation & Support

  • Admin Dashboard: Centralized command center for platform-wide oversight.
  • Integrated Ticket System: Direct communication channel between users and administrators for help requests.
  • Report Lifecycle: Comprehensive reporting for users/messages/posts with automated context attachment.
  • Role-based Access Control (RBAC): Granular permissions system (Owner -> Moderator -> Member).
  • Content Filtering: Integrated profanity filters and link sanitization.

🎨 Design & Accessibility

  • Responsive Architecture: Pixel-perfect layouts for Mobile, Tablet, and Desktop.
  • Modern Theme Engine: Dynamic Dark/Light mode switching with cohesive HSL color palettes.
  • Internationalization (i18n): Native-level support for English and Portuguese.
  • PWA Capabilities: Installable web app with push notifications and offline caching.
  • Accessibility: ARIA-compliant components and keyboard-friendly navigation.

Technology Stack

Backend

  • Flask (Python web framework)
  • Flask-SocketIO (real-time WebSocket communication)
  • MongoDB (NoSQL database)
  • PyOTP (TOTP authentication)
  • Redis (session storage and intelligent database caching with automatic invalidation)

Frontend

  • Next.js with TypeScript
  • Socket.IO Client (real-time communication)
  • Tailwind CSS (styling with theme variables)
  • React Hot Toast (notifications)
  • PWA capabilities with service workers and native install prompts
  • Image Viewer Modal: Full-screen image viewing with download controls
  • Enhanced Video Player: Fullscreen support, download, and right-click context menu
  • Context Menus: Right-click menus for posts, messages, chatrooms, and users

Infrastructure

  • Docker with multi-stage builds
  • Docker Compose for orchestration
  • Nginx reverse proxy (production)
  • Environment-based configuration

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local development)
  • Python 3.11+ (for local development)
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>cd RINTEP2
  2. Start the application

    ./START.sh

    This will:

    • Check prerequisites
    • Set up environment variables
    • Create necessary directories
    • Start all services (MongoDB, Redis, Backend, Frontend)
    • Wait for services to be healthy
  3. Access the application

Manual Setup (Alternative)

If you prefer to set up manually:

  1. Set up environment variables

    # Backend
    cp backend/env.example backend/.env
    # Frontend
    cp frontend/env.local.example frontend/.env.local
    # Edit the copied files with your configuration
  2. Start services with Docker Compose

    docker-compose up --build
  3. Or run locally for development

    Backend:

    cd backend
    python -m venv venv
    source venv/bin/activate # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python app.py

    Frontend:

    cd frontend
    npm install
    npm run dev

Configuration

Environment Variables

The application uses environment variables for configuration. You can set them up automatically or manually.

Automatic Setup (Recommended)

Windows:

setup-env.bat

Linux/Mac:

chmod +x setup-env.sh
./setup-env.sh

PowerShell:

powershell -ExecutionPolicy Bypass -File setup-env.ps1

Manual Setup

Create a .env file in the backend/ directory:

# Database ConfigurationDATABASE_URL=mongodb://localhost:27017/TopicsFlowREDIS_URL=redis://localhost:6379/0# Application ConfigurationSECRET_KEY=your_super_secret_key_hereFRONTEND_URL=http://localhost:3000TOTP_ISSUER=TopicsFlowAPP_NAME=TopicsFlow# Email Service (Resend)RESEND_API_KEY=your_resend_api_keyFROM_EMAIL=noreply@topicsflow.me# External ServicesTENOR_API_KEY=your_tenor_api_key# File Storage (Optional - for Azure deployments)USE_AZURE_STORAGE=falseAZURE_STORAGE_CONNECTION_STRING=your_azure_storage_connection_stringAZURE_STORAGE_CONTAINER=uploadsFILE_ENCRYPTION_KEY=your_file_encryption_key# Optional, defaults to SECRET_KEY# ImgBB (Optional - for large chatroom images)USE_IMGBB=falseIMGBB_API_KEY=your_imgbb_api_keyIMGBB_EXPIRATION_SECONDS=600IMGBB_MAX_BASE64_SIZE_BYTES=2097152# CORS (Development)CORS_ALLOW_ALL=true

Environment variables reference (Local + Azure)

You can use these example templates:

  • backend/env.example → copy to backend/.env
  • frontend/env.local.example → copy to frontend/.env.local

Backend (local development)

VariableDescriptionRequired
SECRET_KEYFlask secret key✅ Yes
ENVIRONMENTdevelopment/production (affects cookie security)Recommended
DATABASE_URLMongoDB connection string✅ Yes
DB_NAMEMongoDB database nameRecommended
REDIS_URLRedis connection string (sessions/rate limit)Recommended
FRONTEND_URLFrontend origin (CORS + passkeys)✅ Yes
CORS_ALLOW_ALLAllow all origins in devOptional
RESEND_API_KEYResend email API key✅ Yes
FROM_EMAILVerified sender email✅ Yes
APP_NAMEApp name used in emailsRecommended
TENOR_API_KEYTenor API key for GIF searchOptional
TENOR_CLIENT_KEYTenor client key (defaults to topicsflow_app)Optional
PASSKEY_RP_IDWebAuthn RP ID (defaults to localhost)Optional
LOG_LEVELLogging levelOptional

Backend storage (attachments)

VariableDescriptionRequired
USE_AZURE_STORAGEUse Azure Blob Storage for attachmentsOptional
AZURE_STORAGE_CONNECTION_STRINGAzure Storage connection stringRequired if USE_AZURE_STORAGE=true
AZURE_STORAGE_CONTAINERBlob container name (use uploads)Required if USE_AZURE_STORAGE=true
API_BASE_URLUsed to build attachment URLsRecommended
FILE_ENCRYPTION_KEYOptional encryption key for attachment URLs (defaults to SECRET_KEY)Optional

Backend ImgBB (recomended)

VariableDescriptionRequired
USE_IMGBBEnable ImgBB uploads for large imagesOptional
IMGBB_API_KEYImgBB API keyRequired if USE_IMGBB=true
IMGBB_EXPIRATION_SECONDSOptional ImgBB expirationOptional
IMGBB_MAX_BASE64_SIZE_BYTESThreshold to upload to ImgBBOptional

Backend (Azure/CosmosDB Mongo API)

VariableDescriptionRequired
AZURE_COSMOS_CONNECTIONSTRINGCosmosDB (Mongo API) connection string✅ Yes (Azure)
AZURE_COSMOS_DATABASECosmos database name✅ Yes (Azure)
COSMOS_DB_URI / COSMOS_DB_NAMEAlternative Cosmos env names supported by configOptional
AZURE_DEPLOYMENTSet to true to force Azure modeOptional
FORCE_AZURE_MODE / FORCE_LOCAL_MODEForce environment detectionOptional

Backend (Redis - Azure/Docker only)

VariableDescriptionRequired
AZURE_REDIS_CONNECTIONSTRINGAzure Redis Cache connection string (format: host:port,password=...,ssl=True)Optional (Azure only)
REDIS_URLRedis connection string (format: redis://password@host:port/0)Optional (Docker/Azure)
REDIS_PASSWORDRedis password (used in Docker Compose)Optional (Docker)
SESSION_TYPESession backend: filesystem (local) or redis (Docker/Azure)Auto-detected

Note: Redis is automatically disabled for local development (non-Docker). The application uses filesystem sessions and direct database queries when running locally without Docker.

Frontend

VariableDescriptionRequired
NEXT_PUBLIC_API_URLBackend base URL✅ Yes
NEXT_PUBLIC_APP_NAMEApp nameOptional
NEXT_PUBLIC_TENOR_API_KEYTenor API key (only if frontend uses it directly)Optional

Email Service Setup (Resend)

  1. Get your API key from Resend Dashboard
  2. Verify your domain in Resend Domains
  3. Add DNS records provided by Resend to your domain
  4. Set FROM_EMAIL to use your verified domain

Tenor API Setup

  1. Go to Tenor Developer Portal
  2. Sign in with Google account
  3. Create a new API key
  4. Add TENOR_API_KEY to your .env file

Passwordless Authentication

The application uses passwordless authentication with TOTP (Time-based One-Time Password):

  • No passwords - Users authenticate with username/email + 6-digit authenticator code
  • Email verification - Required during registration (6-digit codes)
  • TOTP 2FA - Industry-standard authenticator apps (Google Authenticator, Authy, etc.)
  • Backup codes - Emergency access codes for account recovery
  • Secure recovery - Requires email verification + original TOTP secret

User Registration Flow:

  1. Enter username and email
  2. Verify email with 6-digit code
  3. Setup authenticator app (scan QR code or manual entry)
  4. Verify TOTP code
  5. Save backup codes

User Login Flow:

  1. Enter username/email
  2. Enter 6-digit code from authenticator app

Account Recovery:

  1. Enter email → receive verification code
  2. Verify email code
  3. Enter original TOTP secret (saved during registration)
  4. Setup new authenticator
  5. Get new backup codes

⚠️ Important: Users must save their TOTP secret during registration for account recovery!

Caching System

TopicsFlow includes an intelligent Redis-based caching system that dramatically improves performance:

Features:

  • Automatic Caching: All database queries are automatically cached with appropriate TTLs
    • Static data (users, topics): 1 hour cache
    • Dynamic data (posts, comments, messages): 5 minutes cache
  • Automatic Invalidation: Cache is automatically invalidated when data is updated, ensuring consistency
  • Graceful Fallback: If Redis is unavailable, the application automatically falls back to direct database queries
  • Zero Configuration: Works automatically in Docker/Azure deployments with Redis

Local Development:

  • Redis cache is disabled by default on local machines
  • Uses filesystem sessions and direct database queries
  • No Redis installation required for local development

Docker/Azure Deployments:

  • Redis is automatically used for both sessions and caching
  • Provides 50-90% faster response times for cached queries
  • Automatic cache invalidation ensures data consistency
  • Docker: Redis is configured with password authentication (matches Azure approach)
  • Azure: Uses Azure Redis Cache with SSL and connection string format (host:port,password=...,ssl=True)

Cache Invalidation Strategy:

  • Direct updates invalidate the entity and related entities
  • Cascading invalidation ensures all dependent data is refreshed
  • Pattern-based invalidation for list queries

Production Deployment

For production deployment:

  1. Update environment variables with secure values
  2. Set up SSL certificates for HTTPS
  3. Use production Docker Compose file:
    ./START.sh prod
  4. Configure Nginx for reverse proxy and SSL termination

See Azure Deployment section for cloud deployment options.

API Documentation

Authentication Endpoints

Passwordless Registration (Step 1: Start Registration)

POST /api/auth/register-passwordlessContent-Type: application/json
{
"username": "username",
"email": "user@example.com"
}
Response 201:
{
"success": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Verification code sent to your email"
}

Verify Email (Step 2)

POST /api/auth/verify-emailContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}
Response 200:
{
"success": true,
"totp_qr_data": "otpauth://totp/TopicsFlow:username?secret=...",
"totp_secret": "JBSWY3DPEHPK3PXP",
"user_id": "507f1f77bcf86cd799439011"
}

Complete TOTP Setup (Step 3)

POST /api/auth/complete-totp-setupContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"totp_code": "123456"
}
Response 200:
{
"success": true,
"backup_codes": ["12345678", "23456789", ...]
}

Passwordless Login

POST /api/auth/login-passwordlessContent-Type: application/json
{
"identifier": "username", // username or email"totp_code": "123456"
}
Response 200:
{
"success": true,
"user": {
"id": "507f1f77bcf86cd799439011",
"username": "username",
"email": "user@example.com"
}
}

Response 200 (Email 2FA Required):

{
"success": false,
"require_email_2fa": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Please check your email for the verification code"
}

Verify Login Email 2FA

POST /api/auth/verify-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}

Resend Login Email 2FA Code

POST /api/auth/resend-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011"
}
Response 200:
{
"success": true,
"message": "Verification code sent.",
"cooldown": 60
}

Account Recovery

POST /api/auth/recovery/initiate-passwordlessContent-Type: application/json
{
"email": "user@example.com"
}
POST /api/auth/recovery/verify-email-codeContent-Type: application/json
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/recovery/reset-totpContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"original_secret": "JBSWY3DPEHPK3PXP"// Saved during registration
}

Topic Endpoints

Get Topics

GET /api/topics?sort_by=last_activity&limit=20&offset=0&tags=chat,gaming&search=gaming

Create Topic

POST /api/topicsContent-Type: application/jsonAuthorization: Session cookie
{
"title": "Topic Title",
"description": "Topic description",
"tags": ["chat", "gaming"],
"allow_anonymous": true,
"require_approval": false
}

Message Endpoints

Get Topic Messages

GET /api/messages/topic/{topic_id}?limit=50&before_message_id={message_id}

Send Message

POST /api/messages/topic/{topic_id}Content-Type: application/jsonAuthorization: Session cookie
{
"content": "Hello, world!",
"message_type": "text",
"use_anonymous": false,
"gif_url": "https://example.com/gif.gif"
}

Database Schema

Users Collection

{_id: ObjectId,username: String(unique,validated),email: String(unique),phone: String(optional,forrecovery),password_hash: String,totp_secret: String(encrypted),totp_enabled: Boolean,security_questions: [Array],is_banned: Boolean,ban_reason: String,ban_expiry: Date,ip_addresses: [String],created_at: Date,last_login: Date,preferences: {theme: String('dark'|'light'),language: String('en'|'pt'),anonymous_mode: Boolean}}

Topics Collection

{_id: ObjectId,title: String,description: String,owner_id: ObjectId,moderators: [{user_id: ObjectId,added_by: ObjectId,added_at: Date,permissions: [String]}],tags: [String],member_count: Number,is_public: Boolean,created_at: Date,last_activity: Date,settings: {allow_anonymous: Boolean,require_approval: Boolean}}

Messages Collection

{_id: ObjectId,topic_id: ObjectId,user_id: ObjectId,content: String,topic_id: ObjectId,chat_room_id: ObjectId,// For chat room messagesuser_id: ObjectId,content: String,message_type: String('text'|'emoji'|'gif'|'image'|'video'|'file'|'system'),anonymous_identity: String,gif_url: String,attachments: [{// File references (not base64 data)type: String,file_id: String,url: String,filename: String,size: Number,mime_type: String}],is_deleted: Boolean,deleted_by: ObjectId,deleted_at: Date,deletion_reason: String,// For owner deletionsreports: [{reported_by: ObjectId,reason: String,created_at: Date}],created_at: Date,updated_at: Date}

Chat Rooms Collection

{_id: ObjectId,topic_id: ObjectId,name: String,description: String,owner_id: ObjectId,moderators: [ObjectId],members: [ObjectId],picture: String,// Base64 profile picturebackground_picture: String,// Base64 background imageis_public: Boolean,created_at: Date,updated_at: Date}

Private Messages Collection

{_id: ObjectId,from_user_id: ObjectId,to_user_id: ObjectId,content: String,message_type: String,gif_url: String,deleted_for_user_ids: [ObjectId],// Soft delete per useris_read: Boolean,read_at: Date,created_at: Date}

Reports Collection

{_id: ObjectId,reporter_id: ObjectId,reported_user_id: ObjectId,content_id: String,// Message, post, comment, or chatroom IDcontent_type: String,// 'user' | 'message' | 'post' | 'comment' | 'chatroom' | 'chatroom_background' | 'chatroom_picture'reason: String,description: String,owner_id: ObjectId,// For chatroom/content reportsowner_username: String,moderators: [{id: ObjectId,username: String}],// For admin analysisstatus: String,created_at: Date}

Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    python app.py
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker run -d --name mongodb -p 27017:27017 mongo:7.0
    # Start Redis
    docker run -d --name redis -p 6379:6379 redis:7.2-alpine

Testing

Quick Testing Guide

# 1. Migrate database
python migrate_database.py migrate
# 2. Make admin user
python make_admin.py <username># 3. Start backendcd backend && python app.py
# 4. Start frontendcd frontend && npm run dev
# 5. Access app
http://localhost:3000

Test Scenarios

  1. Admin Controls: Login as admin, check for shield icon (🛡️) in top bar
  2. Clickable Usernames: Click username in chat → user banner appears
  3. Right-Click Menu: Right-click username → context menu with options
  4. Report User: Right-click → Report User → fill form → submit
  5. Ticket Creation: Profile menu → Open Ticket → create ticket
  6. Anonymous Mode: Enable "Use Anonymous" toggle in chat

Backend API Testing

Using Postman:

  1. Import tests/TopicsFlow_API.postman_collection.json
  2. Import environment file from tests/postman/environments/
  3. Run collection tests

Using Newman (CLI):

npm install -g newman newman-reporter-html
newman run tests/postman/TopicsFlow_Backend_API.postman_collection.json \
-e tests/postman/environments/Local.postman_environment.json \
-r html --reporter-html-export tests/reports/report.html

WebSocket Testing:

  • Use browser DevTools console
  • See tests/postman/TopicsFlow_WebSocket_Tests.md for detailed instructions

For comprehensive testing documentation, see:

  • TESTING_GUIDE.md - Quick testing scenarios
  • TEST_PLAN.md - Comprehensive test plan
  • tests/TESTING_GUIDE.md - Backend API testing guide
  • tests/TEST_TROUBLESHOOTING.md - Test troubleshooting

Code Quality

# Backend lintingcd backend
flake8 .
black .# Frontend lintingcd frontend
npm run lint
npm run type-check

Security Considerations

  • TOTP Secrets: Encrypted at rest using AES-256
  • Passwords: Hashed with bcrypt
  • Sessions: Secure session management with HTTP-only cookies
  • Rate Limiting: Implemented on all sensitive endpoints
  • Input Validation: Comprehensive validation and sanitization
  • HTTPS: Enforced in production
  • CORS: Properly configured for frontend domain
  • Content Security Policy: Headers implemented for XSS prevention

Monitoring & Logging

Application Logs

# View all service logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f backend
docker-compose logs -f frontend

Health Checks

  • Backend: GET /health
  • Frontend: HTTP status checks
  • Database: Connection health monitoring

Azure Deployment

Quick Start (5 minutes)

# 1. Install Azure CLI# Linux/Mac: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash# Windows: Download from https://aka.ms/installazurecliwindows# 2. Login to Azure
az login
# 3. Configure variables
cp .env.azure.example .env.azure
# Edit .env.azure with your values# 4. Deployexport$(cat .env.azure | xargs)
./azure-deploy.sh

Architecture

  • Backend: Flask + SocketIO + Static Frontend (served by Flask)
  • Database: Azure CosmosDB (MongoDB API)
  • Cache: Azure Cache for Redis (optional)
  • Deployment: Azure Container Apps
  • SSL: Automatic HTTPS

Environment Detection

The application automatically detects Azure environment via:

  • WEBSITE_INSTANCE_ID
  • AZURE_COSMOS_CONNECTIONSTRING

When detected, it automatically:

  • Uses CosmosDB instead of MongoDB
  • Configures SSL connections
  • Disables retryWrites (not supported by CosmosDB)
  • Serves static frontend

Required Azure Resources

  • Azure Container Registry (ACR)
  • Azure CosmosDB (MongoDB API)
  • Azure Container Apps Environment
  • Azure Container App

Cost Estimate

  • Container Apps: ~$40/month
  • CosmosDB: ~$24/month
  • Redis Cache: ~$16/month (optional)
  • Container Registry: ~$5/month
  • Total: ~$85/month (or ~$69 without Redis)

CI/CD with GitHub Actions

  1. Configure GitHub Secrets:

    • AZURE_CREDENTIALS - Service Principal JSON
    • AZURE_CONTAINER_REGISTRY - ACR name
    • AZURE_RESOURCE_GROUP - Resource group name
    • AZURE_APP_NAME - Container App name
    • ACR_USERNAME - ACR username
    • ACR_PASSWORD - ACR password
  2. Push to trigger deployment:

    git push origin main

See GITHUB_ACTIONS_SETUP.md for detailed CI/CD setup instructions.

For complete Azure deployment documentation, see:

  • AZURE_DEPLOYMENT.md - Comprehensive deployment guide
  • AZURE_QUICKSTART.md - Quick start guide

Troubleshooting

Common Issues

  1. Services won't start

    # Check if ports are available# Windows
    netstat -ano | findstr :5000
    taskkill /PID <number> /F
    # Linux/Mac
    lsof -i :3000
    lsof -i :5000
    lsof -i :27017
    lsof -i :6379
    # Clean and restart
    docker-compose down -v
    docker system prune -f
    ./START.sh
  2. Database connection issues

    # Check MongoDB logs
    docker-compose logs mongodb
    # Connect to MongoDB directly
    docker-compose exec mongodb mongosh
  3. TOTP authentication issues

    • Ensure server time is synchronized
    • Check TOTP secret encryption
    • Verify authenticator app time sync
    • Codes expire every 30 seconds - use current code
  4. Frontend build issues

    # Clear Next.js cache
    rm -rf .next
    npm run build
  5. Email not sending

    • Verify Resend API key is set: echo $RESEND_API_KEY
    • Check domain is verified in Resend dashboard
    • Verify FROM_EMAIL uses verified domain
    • Check backend logs for errors
  6. bcrypt module not found (Windows)

    # Solution 1: Reinstall bcrypt
    pip uninstall -y bcrypt
    pip install --only-binary :all: bcrypt==4.1.0
    # Solution 2: Install Visual Studio Build Tools# Download from https://visualstudio.microsoft.com/downloads/# Install "Desktop development with C++"# Solution 3: Use compatible version
    pip install bcrypt==4.0.1
  7. Port already in use (Windows)

    netstat -ano |findstr :5000
    taskkill /PID <number> /F
  8. MongoDB connection failed

    # Check if MongoDB is running
    docker ps | findstr mongodb
    # Start MongoDB
    docker start mongodb-test
    # Or create new container
    docker run -d --name mongodb-test -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    mongo:7.0

For Windows-specific troubleshooting, see WINDOWS_TROUBLESHOOTING.md.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test and python -m pytest
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow existing code patterns
  • Write tests for new features
  • Update documentation
  • Use descriptive commit messages
  • Keep PRs focused and manageable

License

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

Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section above
  • Review the API documentation

Acknowledgments

  • Built with Flask, Next.js, MongoDB, and Socket.IO
  • Inspired by Reddit's community structure
  • TOTP authentication standards
  • Open source libraries and frameworks used

About

Chat application that features publications and chatrooms by topic and direct messages and groups.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - 8JP8/TopicsFlow: Chat application that features publications and chatrooms by topic and direct messages and groups. · GitHub
Skip to content

Latest commit

History

161 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TopicsFlow App

📚 Comprehensive Documentation: Check out the Project Wiki for detailed guides on Architecture, API, Deployment, and more.

Overview

TopicsFlow is a comprehensive chat and topic discussion platform designed to facilitate focused conversations and community interactions.

🔐 Security & Authentication

  • Passwordless Authentication: Users log in via email/username + 6-digit TOTP code.
  • TOTP-based 2FA: Full compatibility with Google Authenticator, Microsoft Authenticator, and Authy.
  • Robust Account Recovery: Multi-step recovery using email verification and original TOTP secrets.
  • Backup Codes: 10 high-entropy emergency access codes provided during setup.
  • Secure Sessions: Encrypted session storage in Redis (Azure/Docker) or filesystem (local) with proper cookie security (HttpOnly).
  • Intelligent Caching: Redis-based caching system for database queries with automatic cache invalidation. Dramatically improves performance (50-90% faster response times) while ensuring data consistency.
  • Advanced Banning: Global banning system targeting IP addresses, emails, and phone numbers.

💬 Real-time Communication

  • Hybrid Platform: Seamless integration between Reddit-style forums and instant chat rooms.
  • WebSocket Foundation: Built on Socket.IO for sub-100ms latency.
  • Presence System: Real-time "online" status and typing indicators across the entire app.
  • Group Chat Rooms: Unlimited rooms per Topic with customizable profile/background images.
  • Direct Messaging (DMs): Private 1-on-1 conversations with encryption-ready architecture.
  • Voice Communication (VOIP): Integrated voice rooms with participant lists and active speaker detection.
  • Media Engine: Instant sharing of GIFs (Tenor), images, videos, and files with secure cloud storage.
  • Anonymous Mode: Per-topic identity masking with custom aliases to encourage open discussion.

📝 Content Management (The "Publications" System)

  • Dynamic Topics: Hierarchical community spaces for high-level categorization.
  • Publications (Posts): Reddit-style nested posts with rich text (Markdown) support.
  • Voting Mechanism: Positive/Negative reputation system for quality control.
  • Threaded Comments: Deeply nested conversations with @mentions and reply tracking.
  • Navigation Controls: Advanced sorting (Hot, New, Top) and tag-based discovery.
  • Search Engine: Rapid indexing of topics and posts for easy discovery.

🛡️ Moderation & Support

  • Admin Dashboard: Centralized command center for platform-wide oversight.
  • Integrated Ticket System: Direct communication channel between users and administrators for help requests.
  • Report Lifecycle: Comprehensive reporting for users/messages/posts with automated context attachment.
  • Role-based Access Control (RBAC): Granular permissions system (Owner -> Moderator -> Member).
  • Content Filtering: Integrated profanity filters and link sanitization.

🎨 Design & Accessibility

  • Responsive Architecture: Pixel-perfect layouts for Mobile, Tablet, and Desktop.
  • Modern Theme Engine: Dynamic Dark/Light mode switching with cohesive HSL color palettes.
  • Internationalization (i18n): Native-level support for English and Portuguese.
  • PWA Capabilities: Installable web app with push notifications and offline caching.
  • Accessibility: ARIA-compliant components and keyboard-friendly navigation.

Technology Stack

Backend

  • Flask (Python web framework)
  • Flask-SocketIO (real-time WebSocket communication)
  • MongoDB (NoSQL database)
  • PyOTP (TOTP authentication)
  • Redis (session storage and intelligent database caching with automatic invalidation)

Frontend

  • Next.js with TypeScript
  • Socket.IO Client (real-time communication)
  • Tailwind CSS (styling with theme variables)
  • React Hot Toast (notifications)
  • PWA capabilities with service workers and native install prompts
  • Image Viewer Modal: Full-screen image viewing with download controls
  • Enhanced Video Player: Fullscreen support, download, and right-click context menu
  • Context Menus: Right-click menus for posts, messages, chatrooms, and users

Infrastructure

  • Docker with multi-stage builds
  • Docker Compose for orchestration
  • Nginx reverse proxy (production)
  • Environment-based configuration

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local development)
  • Python 3.11+ (for local development)
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>cd RINTEP2
  2. Start the application

    ./START.sh

    This will:

    • Check prerequisites
    • Set up environment variables
    • Create necessary directories
    • Start all services (MongoDB, Redis, Backend, Frontend)
    • Wait for services to be healthy
  3. Access the application

Manual Setup (Alternative)

If you prefer to set up manually:

  1. Set up environment variables

    # Backend
    cp backend/env.example backend/.env
    # Frontend
    cp frontend/env.local.example frontend/.env.local
    # Edit the copied files with your configuration
  2. Start services with Docker Compose

    docker-compose up --build
  3. Or run locally for development

    Backend:

    cd backend
    python -m venv venv
    source venv/bin/activate # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python app.py

    Frontend:

    cd frontend
    npm install
    npm run dev

Configuration

Environment Variables

The application uses environment variables for configuration. You can set them up automatically or manually.

Automatic Setup (Recommended)

Windows:

setup-env.bat

Linux/Mac:

chmod +x setup-env.sh
./setup-env.sh

PowerShell:

powershell -ExecutionPolicy Bypass -File setup-env.ps1

Manual Setup

Create a .env file in the backend/ directory:

# Database ConfigurationDATABASE_URL=mongodb://localhost:27017/TopicsFlowREDIS_URL=redis://localhost:6379/0# Application ConfigurationSECRET_KEY=your_super_secret_key_hereFRONTEND_URL=http://localhost:3000TOTP_ISSUER=TopicsFlowAPP_NAME=TopicsFlow# Email Service (Resend)RESEND_API_KEY=your_resend_api_keyFROM_EMAIL=noreply@topicsflow.me# External ServicesTENOR_API_KEY=your_tenor_api_key# File Storage (Optional - for Azure deployments)USE_AZURE_STORAGE=falseAZURE_STORAGE_CONNECTION_STRING=your_azure_storage_connection_stringAZURE_STORAGE_CONTAINER=uploadsFILE_ENCRYPTION_KEY=your_file_encryption_key# Optional, defaults to SECRET_KEY# ImgBB (Optional - for large chatroom images)USE_IMGBB=falseIMGBB_API_KEY=your_imgbb_api_keyIMGBB_EXPIRATION_SECONDS=600IMGBB_MAX_BASE64_SIZE_BYTES=2097152# CORS (Development)CORS_ALLOW_ALL=true

Environment variables reference (Local + Azure)

You can use these example templates:

  • backend/env.example → copy to backend/.env
  • frontend/env.local.example → copy to frontend/.env.local

Backend (local development)

VariableDescriptionRequired
SECRET_KEYFlask secret key✅ Yes
ENVIRONMENTdevelopment/production (affects cookie security)Recommended
DATABASE_URLMongoDB connection string✅ Yes
DB_NAMEMongoDB database nameRecommended
REDIS_URLRedis connection string (sessions/rate limit)Recommended
FRONTEND_URLFrontend origin (CORS + passkeys)✅ Yes
CORS_ALLOW_ALLAllow all origins in devOptional
RESEND_API_KEYResend email API key✅ Yes
FROM_EMAILVerified sender email✅ Yes
APP_NAMEApp name used in emailsRecommended
TENOR_API_KEYTenor API key for GIF searchOptional
TENOR_CLIENT_KEYTenor client key (defaults to topicsflow_app)Optional
PASSKEY_RP_IDWebAuthn RP ID (defaults to localhost)Optional
LOG_LEVELLogging levelOptional

Backend storage (attachments)

VariableDescriptionRequired
USE_AZURE_STORAGEUse Azure Blob Storage for attachmentsOptional
AZURE_STORAGE_CONNECTION_STRINGAzure Storage connection stringRequired if USE_AZURE_STORAGE=true
AZURE_STORAGE_CONTAINERBlob container name (use uploads)Required if USE_AZURE_STORAGE=true
API_BASE_URLUsed to build attachment URLsRecommended
FILE_ENCRYPTION_KEYOptional encryption key for attachment URLs (defaults to SECRET_KEY)Optional

Backend ImgBB (recomended)

VariableDescriptionRequired
USE_IMGBBEnable ImgBB uploads for large imagesOptional
IMGBB_API_KEYImgBB API keyRequired if USE_IMGBB=true
IMGBB_EXPIRATION_SECONDSOptional ImgBB expirationOptional
IMGBB_MAX_BASE64_SIZE_BYTESThreshold to upload to ImgBBOptional

Backend (Azure/CosmosDB Mongo API)

VariableDescriptionRequired
AZURE_COSMOS_CONNECTIONSTRINGCosmosDB (Mongo API) connection string✅ Yes (Azure)
AZURE_COSMOS_DATABASECosmos database name✅ Yes (Azure)
COSMOS_DB_URI / COSMOS_DB_NAMEAlternative Cosmos env names supported by configOptional
AZURE_DEPLOYMENTSet to true to force Azure modeOptional
FORCE_AZURE_MODE / FORCE_LOCAL_MODEForce environment detectionOptional

Backend (Redis - Azure/Docker only)

VariableDescriptionRequired
AZURE_REDIS_CONNECTIONSTRINGAzure Redis Cache connection string (format: host:port,password=...,ssl=True)Optional (Azure only)
REDIS_URLRedis connection string (format: redis://password@host:port/0)Optional (Docker/Azure)
REDIS_PASSWORDRedis password (used in Docker Compose)Optional (Docker)
SESSION_TYPESession backend: filesystem (local) or redis (Docker/Azure)Auto-detected

Note: Redis is automatically disabled for local development (non-Docker). The application uses filesystem sessions and direct database queries when running locally without Docker.

Frontend

VariableDescriptionRequired
NEXT_PUBLIC_API_URLBackend base URL✅ Yes
NEXT_PUBLIC_APP_NAMEApp nameOptional
NEXT_PUBLIC_TENOR_API_KEYTenor API key (only if frontend uses it directly)Optional

Email Service Setup (Resend)

  1. Get your API key from Resend Dashboard
  2. Verify your domain in Resend Domains
  3. Add DNS records provided by Resend to your domain
  4. Set FROM_EMAIL to use your verified domain

Tenor API Setup

  1. Go to Tenor Developer Portal
  2. Sign in with Google account
  3. Create a new API key
  4. Add TENOR_API_KEY to your .env file

Passwordless Authentication

The application uses passwordless authentication with TOTP (Time-based One-Time Password):

  • No passwords - Users authenticate with username/email + 6-digit authenticator code
  • Email verification - Required during registration (6-digit codes)
  • TOTP 2FA - Industry-standard authenticator apps (Google Authenticator, Authy, etc.)
  • Backup codes - Emergency access codes for account recovery
  • Secure recovery - Requires email verification + original TOTP secret

User Registration Flow:

  1. Enter username and email
  2. Verify email with 6-digit code
  3. Setup authenticator app (scan QR code or manual entry)
  4. Verify TOTP code
  5. Save backup codes

User Login Flow:

  1. Enter username/email
  2. Enter 6-digit code from authenticator app

Account Recovery:

  1. Enter email → receive verification code
  2. Verify email code
  3. Enter original TOTP secret (saved during registration)
  4. Setup new authenticator
  5. Get new backup codes

⚠️ Important: Users must save their TOTP secret during registration for account recovery!

Caching System

TopicsFlow includes an intelligent Redis-based caching system that dramatically improves performance:

Features:

  • Automatic Caching: All database queries are automatically cached with appropriate TTLs
    • Static data (users, topics): 1 hour cache
    • Dynamic data (posts, comments, messages): 5 minutes cache
  • Automatic Invalidation: Cache is automatically invalidated when data is updated, ensuring consistency
  • Graceful Fallback: If Redis is unavailable, the application automatically falls back to direct database queries
  • Zero Configuration: Works automatically in Docker/Azure deployments with Redis

Local Development:

  • Redis cache is disabled by default on local machines
  • Uses filesystem sessions and direct database queries
  • No Redis installation required for local development

Docker/Azure Deployments:

  • Redis is automatically used for both sessions and caching
  • Provides 50-90% faster response times for cached queries
  • Automatic cache invalidation ensures data consistency
  • Docker: Redis is configured with password authentication (matches Azure approach)
  • Azure: Uses Azure Redis Cache with SSL and connection string format (host:port,password=...,ssl=True)

Cache Invalidation Strategy:

  • Direct updates invalidate the entity and related entities
  • Cascading invalidation ensures all dependent data is refreshed
  • Pattern-based invalidation for list queries

Production Deployment

For production deployment:

  1. Update environment variables with secure values
  2. Set up SSL certificates for HTTPS
  3. Use production Docker Compose file:
    ./START.sh prod
  4. Configure Nginx for reverse proxy and SSL termination

See Azure Deployment section for cloud deployment options.

API Documentation

Authentication Endpoints

Passwordless Registration (Step 1: Start Registration)

POST /api/auth/register-passwordlessContent-Type: application/json
{
"username": "username",
"email": "user@example.com"
}
Response 201:
{
"success": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Verification code sent to your email"
}

Verify Email (Step 2)

POST /api/auth/verify-emailContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}
Response 200:
{
"success": true,
"totp_qr_data": "otpauth://totp/TopicsFlow:username?secret=...",
"totp_secret": "JBSWY3DPEHPK3PXP",
"user_id": "507f1f77bcf86cd799439011"
}

Complete TOTP Setup (Step 3)

POST /api/auth/complete-totp-setupContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"totp_code": "123456"
}
Response 200:
{
"success": true,
"backup_codes": ["12345678", "23456789", ...]
}

Passwordless Login

POST /api/auth/login-passwordlessContent-Type: application/json
{
"identifier": "username", // username or email"totp_code": "123456"
}
Response 200:
{
"success": true,
"user": {
"id": "507f1f77bcf86cd799439011",
"username": "username",
"email": "user@example.com"
}
}

Response 200 (Email 2FA Required):

{
"success": false,
"require_email_2fa": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Please check your email for the verification code"
}

Verify Login Email 2FA

POST /api/auth/verify-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}

Resend Login Email 2FA Code

POST /api/auth/resend-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011"
}
Response 200:
{
"success": true,
"message": "Verification code sent.",
"cooldown": 60
}

Account Recovery

POST /api/auth/recovery/initiate-passwordlessContent-Type: application/json
{
"email": "user@example.com"
}
POST /api/auth/recovery/verify-email-codeContent-Type: application/json
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/recovery/reset-totpContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"original_secret": "JBSWY3DPEHPK3PXP"// Saved during registration
}

Topic Endpoints

Get Topics

GET /api/topics?sort_by=last_activity&limit=20&offset=0&tags=chat,gaming&search=gaming

Create Topic

POST /api/topicsContent-Type: application/jsonAuthorization: Session cookie
{
"title": "Topic Title",
"description": "Topic description",
"tags": ["chat", "gaming"],
"allow_anonymous": true,
"require_approval": false
}

Message Endpoints

Get Topic Messages

GET /api/messages/topic/{topic_id}?limit=50&before_message_id={message_id}

Send Message

POST /api/messages/topic/{topic_id}Content-Type: application/jsonAuthorization: Session cookie
{
"content": "Hello, world!",
"message_type": "text",
"use_anonymous": false,
"gif_url": "https://example.com/gif.gif"
}

Database Schema

Users Collection

{_id: ObjectId,username: String(unique,validated),email: String(unique),phone: String(optional,forrecovery),password_hash: String,totp_secret: String(encrypted),totp_enabled: Boolean,security_questions: [Array],is_banned: Boolean,ban_reason: String,ban_expiry: Date,ip_addresses: [String],created_at: Date,last_login: Date,preferences: {theme: String('dark'|'light'),language: String('en'|'pt'),anonymous_mode: Boolean}}

Topics Collection

{_id: ObjectId,title: String,description: String,owner_id: ObjectId,moderators: [{user_id: ObjectId,added_by: ObjectId,added_at: Date,permissions: [String]}],tags: [String],member_count: Number,is_public: Boolean,created_at: Date,last_activity: Date,settings: {allow_anonymous: Boolean,require_approval: Boolean}}

Messages Collection

{_id: ObjectId,topic_id: ObjectId,user_id: ObjectId,content: String,topic_id: ObjectId,chat_room_id: ObjectId,// For chat room messagesuser_id: ObjectId,content: String,message_type: String('text'|'emoji'|'gif'|'image'|'video'|'file'|'system'),anonymous_identity: String,gif_url: String,attachments: [{// File references (not base64 data)type: String,file_id: String,url: String,filename: String,size: Number,mime_type: String}],is_deleted: Boolean,deleted_by: ObjectId,deleted_at: Date,deletion_reason: String,// For owner deletionsreports: [{reported_by: ObjectId,reason: String,created_at: Date}],created_at: Date,updated_at: Date}

Chat Rooms Collection

{_id: ObjectId,topic_id: ObjectId,name: String,description: String,owner_id: ObjectId,moderators: [ObjectId],members: [ObjectId],picture: String,// Base64 profile picturebackground_picture: String,// Base64 background imageis_public: Boolean,created_at: Date,updated_at: Date}

Private Messages Collection

{_id: ObjectId,from_user_id: ObjectId,to_user_id: ObjectId,content: String,message_type: String,gif_url: String,deleted_for_user_ids: [ObjectId],// Soft delete per useris_read: Boolean,read_at: Date,created_at: Date}

Reports Collection

{_id: ObjectId,reporter_id: ObjectId,reported_user_id: ObjectId,content_id: String,// Message, post, comment, or chatroom IDcontent_type: String,// 'user' | 'message' | 'post' | 'comment' | 'chatroom' | 'chatroom_background' | 'chatroom_picture'reason: String,description: String,owner_id: ObjectId,// For chatroom/content reportsowner_username: String,moderators: [{id: ObjectId,username: String}],// For admin analysisstatus: String,created_at: Date}

Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    python app.py
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker run -d --name mongodb -p 27017:27017 mongo:7.0
    # Start Redis
    docker run -d --name redis -p 6379:6379 redis:7.2-alpine

Testing

Quick Testing Guide

# 1. Migrate database
python migrate_database.py migrate
# 2. Make admin user
python make_admin.py <username># 3. Start backendcd backend && python app.py
# 4. Start frontendcd frontend && npm run dev
# 5. Access app
http://localhost:3000

Test Scenarios

  1. Admin Controls: Login as admin, check for shield icon (🛡️) in top bar
  2. Clickable Usernames: Click username in chat → user banner appears
  3. Right-Click Menu: Right-click username → context menu with options
  4. Report User: Right-click → Report User → fill form → submit
  5. Ticket Creation: Profile menu → Open Ticket → create ticket
  6. Anonymous Mode: Enable "Use Anonymous" toggle in chat

Backend API Testing

Using Postman:

  1. Import tests/TopicsFlow_API.postman_collection.json
  2. Import environment file from tests/postman/environments/
  3. Run collection tests

Using Newman (CLI):

npm install -g newman newman-reporter-html
newman run tests/postman/TopicsFlow_Backend_API.postman_collection.json \
-e tests/postman/environments/Local.postman_environment.json \
-r html --reporter-html-export tests/reports/report.html

WebSocket Testing:

  • Use browser DevTools console
  • See tests/postman/TopicsFlow_WebSocket_Tests.md for detailed instructions

For comprehensive testing documentation, see:

  • TESTING_GUIDE.md - Quick testing scenarios
  • TEST_PLAN.md - Comprehensive test plan
  • tests/TESTING_GUIDE.md - Backend API testing guide
  • tests/TEST_TROUBLESHOOTING.md - Test troubleshooting

Code Quality

# Backend lintingcd backend
flake8 .
black .# Frontend lintingcd frontend
npm run lint
npm run type-check

Security Considerations

  • TOTP Secrets: Encrypted at rest using AES-256
  • Passwords: Hashed with bcrypt
  • Sessions: Secure session management with HTTP-only cookies
  • Rate Limiting: Implemented on all sensitive endpoints
  • Input Validation: Comprehensive validation and sanitization
  • HTTPS: Enforced in production
  • CORS: Properly configured for frontend domain
  • Content Security Policy: Headers implemented for XSS prevention

Monitoring & Logging

Application Logs

# View all service logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f backend
docker-compose logs -f frontend

Health Checks

  • Backend: GET /health
  • Frontend: HTTP status checks
  • Database: Connection health monitoring

Azure Deployment

Quick Start (5 minutes)

# 1. Install Azure CLI# Linux/Mac: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash# Windows: Download from https://aka.ms/installazurecliwindows# 2. Login to Azure
az login
# 3. Configure variables
cp .env.azure.example .env.azure
# Edit .env.azure with your values# 4. Deployexport$(cat .env.azure | xargs)
./azure-deploy.sh

Architecture

  • Backend: Flask + SocketIO + Static Frontend (served by Flask)
  • Database: Azure CosmosDB (MongoDB API)
  • Cache: Azure Cache for Redis (optional)
  • Deployment: Azure Container Apps
  • SSL: Automatic HTTPS

Environment Detection

The application automatically detects Azure environment via:

  • WEBSITE_INSTANCE_ID
  • AZURE_COSMOS_CONNECTIONSTRING

When detected, it automatically:

  • Uses CosmosDB instead of MongoDB
  • Configures SSL connections
  • Disables retryWrites (not supported by CosmosDB)
  • Serves static frontend

Required Azure Resources

  • Azure Container Registry (ACR)
  • Azure CosmosDB (MongoDB API)
  • Azure Container Apps Environment
  • Azure Container App

Cost Estimate

  • Container Apps: ~$40/month
  • CosmosDB: ~$24/month
  • Redis Cache: ~$16/month (optional)
  • Container Registry: ~$5/month
  • Total: ~$85/month (or ~$69 without Redis)

CI/CD with GitHub Actions

  1. Configure GitHub Secrets:

    • AZURE_CREDENTIALS - Service Principal JSON
    • AZURE_CONTAINER_REGISTRY - ACR name
    • AZURE_RESOURCE_GROUP - Resource group name
    • AZURE_APP_NAME - Container App name
    • ACR_USERNAME - ACR username
    • ACR_PASSWORD - ACR password
  2. Push to trigger deployment:

    git push origin main

See GITHUB_ACTIONS_SETUP.md for detailed CI/CD setup instructions.

For complete Azure deployment documentation, see:

  • AZURE_DEPLOYMENT.md - Comprehensive deployment guide
  • AZURE_QUICKSTART.md - Quick start guide

Troubleshooting

Common Issues

  1. Services won't start

    # Check if ports are available# Windows
    netstat -ano | findstr :5000
    taskkill /PID <number> /F
    # Linux/Mac
    lsof -i :3000
    lsof -i :5000
    lsof -i :27017
    lsof -i :6379
    # Clean and restart
    docker-compose down -v
    docker system prune -f
    ./START.sh
  2. Database connection issues

    # Check MongoDB logs
    docker-compose logs mongodb
    # Connect to MongoDB directly
    docker-compose exec mongodb mongosh
  3. TOTP authentication issues

    • Ensure server time is synchronized
    • Check TOTP secret encryption
    • Verify authenticator app time sync
    • Codes expire every 30 seconds - use current code
  4. Frontend build issues

    # Clear Next.js cache
    rm -rf .next
    npm run build
  5. Email not sending

    • Verify Resend API key is set: echo $RESEND_API_KEY
    • Check domain is verified in Resend dashboard
    • Verify FROM_EMAIL uses verified domain
    • Check backend logs for errors
  6. bcrypt module not found (Windows)

    # Solution 1: Reinstall bcrypt
    pip uninstall -y bcrypt
    pip install --only-binary :all: bcrypt==4.1.0
    # Solution 2: Install Visual Studio Build Tools# Download from https://visualstudio.microsoft.com/downloads/# Install "Desktop development with C++"# Solution 3: Use compatible version
    pip install bcrypt==4.0.1
  7. Port already in use (Windows)

    netstat -ano |findstr :5000
    taskkill /PID <number> /F
  8. MongoDB connection failed

    # Check if MongoDB is running
    docker ps | findstr mongodb
    # Start MongoDB
    docker start mongodb-test
    # Or create new container
    docker run -d --name mongodb-test -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    mongo:7.0

For Windows-specific troubleshooting, see WINDOWS_TROUBLESHOOTING.md.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test and python -m pytest
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow existing code patterns
  • Write tests for new features
  • Update documentation
  • Use descriptive commit messages
  • Keep PRs focused and manageable

License

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

Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section above
  • Review the API documentation

Acknowledgments

  • Built with Flask, Next.js, MongoDB, and Socket.IO
  • Inspired by Reddit's community structure
  • TOTP authentication standards
  • Open source libraries and frameworks used

About

Chat application that features publications and chatrooms by topic and direct messages and groups.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - 8JP8/TopicsFlow: Chat application that features publications and chatrooms by topic and direct messages and groups. · GitHub
Skip to content

Latest commit

History

161 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TopicsFlow App

📚 Comprehensive Documentation: Check out the Project Wiki for detailed guides on Architecture, API, Deployment, and more.

Overview

TopicsFlow is a comprehensive chat and topic discussion platform designed to facilitate focused conversations and community interactions.

🔐 Security & Authentication

  • Passwordless Authentication: Users log in via email/username + 6-digit TOTP code.
  • TOTP-based 2FA: Full compatibility with Google Authenticator, Microsoft Authenticator, and Authy.
  • Robust Account Recovery: Multi-step recovery using email verification and original TOTP secrets.
  • Backup Codes: 10 high-entropy emergency access codes provided during setup.
  • Secure Sessions: Encrypted session storage in Redis (Azure/Docker) or filesystem (local) with proper cookie security (HttpOnly).
  • Intelligent Caching: Redis-based caching system for database queries with automatic cache invalidation. Dramatically improves performance (50-90% faster response times) while ensuring data consistency.
  • Advanced Banning: Global banning system targeting IP addresses, emails, and phone numbers.

💬 Real-time Communication

  • Hybrid Platform: Seamless integration between Reddit-style forums and instant chat rooms.
  • WebSocket Foundation: Built on Socket.IO for sub-100ms latency.
  • Presence System: Real-time "online" status and typing indicators across the entire app.
  • Group Chat Rooms: Unlimited rooms per Topic with customizable profile/background images.
  • Direct Messaging (DMs): Private 1-on-1 conversations with encryption-ready architecture.
  • Voice Communication (VOIP): Integrated voice rooms with participant lists and active speaker detection.
  • Media Engine: Instant sharing of GIFs (Tenor), images, videos, and files with secure cloud storage.
  • Anonymous Mode: Per-topic identity masking with custom aliases to encourage open discussion.

📝 Content Management (The "Publications" System)

  • Dynamic Topics: Hierarchical community spaces for high-level categorization.
  • Publications (Posts): Reddit-style nested posts with rich text (Markdown) support.
  • Voting Mechanism: Positive/Negative reputation system for quality control.
  • Threaded Comments: Deeply nested conversations with @mentions and reply tracking.
  • Navigation Controls: Advanced sorting (Hot, New, Top) and tag-based discovery.
  • Search Engine: Rapid indexing of topics and posts for easy discovery.

🛡️ Moderation & Support

  • Admin Dashboard: Centralized command center for platform-wide oversight.
  • Integrated Ticket System: Direct communication channel between users and administrators for help requests.
  • Report Lifecycle: Comprehensive reporting for users/messages/posts with automated context attachment.
  • Role-based Access Control (RBAC): Granular permissions system (Owner -> Moderator -> Member).
  • Content Filtering: Integrated profanity filters and link sanitization.

🎨 Design & Accessibility

  • Responsive Architecture: Pixel-perfect layouts for Mobile, Tablet, and Desktop.
  • Modern Theme Engine: Dynamic Dark/Light mode switching with cohesive HSL color palettes.
  • Internationalization (i18n): Native-level support for English and Portuguese.
  • PWA Capabilities: Installable web app with push notifications and offline caching.
  • Accessibility: ARIA-compliant components and keyboard-friendly navigation.

Technology Stack

Backend

  • Flask (Python web framework)
  • Flask-SocketIO (real-time WebSocket communication)
  • MongoDB (NoSQL database)
  • PyOTP (TOTP authentication)
  • Redis (session storage and intelligent database caching with automatic invalidation)

Frontend

  • Next.js with TypeScript
  • Socket.IO Client (real-time communication)
  • Tailwind CSS (styling with theme variables)
  • React Hot Toast (notifications)
  • PWA capabilities with service workers and native install prompts
  • Image Viewer Modal: Full-screen image viewing with download controls
  • Enhanced Video Player: Fullscreen support, download, and right-click context menu
  • Context Menus: Right-click menus for posts, messages, chatrooms, and users

Infrastructure

  • Docker with multi-stage builds
  • Docker Compose for orchestration
  • Nginx reverse proxy (production)
  • Environment-based configuration

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local development)
  • Python 3.11+ (for local development)
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>cd RINTEP2
  2. Start the application

    ./START.sh

    This will:

    • Check prerequisites
    • Set up environment variables
    • Create necessary directories
    • Start all services (MongoDB, Redis, Backend, Frontend)
    • Wait for services to be healthy
  3. Access the application

Manual Setup (Alternative)

If you prefer to set up manually:

  1. Set up environment variables

    # Backend
    cp backend/env.example backend/.env
    # Frontend
    cp frontend/env.local.example frontend/.env.local
    # Edit the copied files with your configuration
  2. Start services with Docker Compose

    docker-compose up --build
  3. Or run locally for development

    Backend:

    cd backend
    python -m venv venv
    source venv/bin/activate # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python app.py

    Frontend:

    cd frontend
    npm install
    npm run dev

Configuration

Environment Variables

The application uses environment variables for configuration. You can set them up automatically or manually.

Automatic Setup (Recommended)

Windows:

setup-env.bat

Linux/Mac:

chmod +x setup-env.sh
./setup-env.sh

PowerShell:

powershell -ExecutionPolicy Bypass -File setup-env.ps1

Manual Setup

Create a .env file in the backend/ directory:

# Database ConfigurationDATABASE_URL=mongodb://localhost:27017/TopicsFlowREDIS_URL=redis://localhost:6379/0# Application ConfigurationSECRET_KEY=your_super_secret_key_hereFRONTEND_URL=http://localhost:3000TOTP_ISSUER=TopicsFlowAPP_NAME=TopicsFlow# Email Service (Resend)RESEND_API_KEY=your_resend_api_keyFROM_EMAIL=noreply@topicsflow.me# External ServicesTENOR_API_KEY=your_tenor_api_key# File Storage (Optional - for Azure deployments)USE_AZURE_STORAGE=falseAZURE_STORAGE_CONNECTION_STRING=your_azure_storage_connection_stringAZURE_STORAGE_CONTAINER=uploadsFILE_ENCRYPTION_KEY=your_file_encryption_key# Optional, defaults to SECRET_KEY# ImgBB (Optional - for large chatroom images)USE_IMGBB=falseIMGBB_API_KEY=your_imgbb_api_keyIMGBB_EXPIRATION_SECONDS=600IMGBB_MAX_BASE64_SIZE_BYTES=2097152# CORS (Development)CORS_ALLOW_ALL=true

Environment variables reference (Local + Azure)

You can use these example templates:

  • backend/env.example → copy to backend/.env
  • frontend/env.local.example → copy to frontend/.env.local

Backend (local development)

VariableDescriptionRequired
SECRET_KEYFlask secret key✅ Yes
ENVIRONMENTdevelopment/production (affects cookie security)Recommended
DATABASE_URLMongoDB connection string✅ Yes
DB_NAMEMongoDB database nameRecommended
REDIS_URLRedis connection string (sessions/rate limit)Recommended
FRONTEND_URLFrontend origin (CORS + passkeys)✅ Yes
CORS_ALLOW_ALLAllow all origins in devOptional
RESEND_API_KEYResend email API key✅ Yes
FROM_EMAILVerified sender email✅ Yes
APP_NAMEApp name used in emailsRecommended
TENOR_API_KEYTenor API key for GIF searchOptional
TENOR_CLIENT_KEYTenor client key (defaults to topicsflow_app)Optional
PASSKEY_RP_IDWebAuthn RP ID (defaults to localhost)Optional
LOG_LEVELLogging levelOptional

Backend storage (attachments)

VariableDescriptionRequired
USE_AZURE_STORAGEUse Azure Blob Storage for attachmentsOptional
AZURE_STORAGE_CONNECTION_STRINGAzure Storage connection stringRequired if USE_AZURE_STORAGE=true
AZURE_STORAGE_CONTAINERBlob container name (use uploads)Required if USE_AZURE_STORAGE=true
API_BASE_URLUsed to build attachment URLsRecommended
FILE_ENCRYPTION_KEYOptional encryption key for attachment URLs (defaults to SECRET_KEY)Optional

Backend ImgBB (recomended)

VariableDescriptionRequired
USE_IMGBBEnable ImgBB uploads for large imagesOptional
IMGBB_API_KEYImgBB API keyRequired if USE_IMGBB=true
IMGBB_EXPIRATION_SECONDSOptional ImgBB expirationOptional
IMGBB_MAX_BASE64_SIZE_BYTESThreshold to upload to ImgBBOptional

Backend (Azure/CosmosDB Mongo API)

VariableDescriptionRequired
AZURE_COSMOS_CONNECTIONSTRINGCosmosDB (Mongo API) connection string✅ Yes (Azure)
AZURE_COSMOS_DATABASECosmos database name✅ Yes (Azure)
COSMOS_DB_URI / COSMOS_DB_NAMEAlternative Cosmos env names supported by configOptional
AZURE_DEPLOYMENTSet to true to force Azure modeOptional
FORCE_AZURE_MODE / FORCE_LOCAL_MODEForce environment detectionOptional

Backend (Redis - Azure/Docker only)

VariableDescriptionRequired
AZURE_REDIS_CONNECTIONSTRINGAzure Redis Cache connection string (format: host:port,password=...,ssl=True)Optional (Azure only)
REDIS_URLRedis connection string (format: redis://password@host:port/0)Optional (Docker/Azure)
REDIS_PASSWORDRedis password (used in Docker Compose)Optional (Docker)
SESSION_TYPESession backend: filesystem (local) or redis (Docker/Azure)Auto-detected

Note: Redis is automatically disabled for local development (non-Docker). The application uses filesystem sessions and direct database queries when running locally without Docker.

Frontend

VariableDescriptionRequired
NEXT_PUBLIC_API_URLBackend base URL✅ Yes
NEXT_PUBLIC_APP_NAMEApp nameOptional
NEXT_PUBLIC_TENOR_API_KEYTenor API key (only if frontend uses it directly)Optional

Email Service Setup (Resend)

  1. Get your API key from Resend Dashboard
  2. Verify your domain in Resend Domains
  3. Add DNS records provided by Resend to your domain
  4. Set FROM_EMAIL to use your verified domain

Tenor API Setup

  1. Go to Tenor Developer Portal
  2. Sign in with Google account
  3. Create a new API key
  4. Add TENOR_API_KEY to your .env file

Passwordless Authentication

The application uses passwordless authentication with TOTP (Time-based One-Time Password):

  • No passwords - Users authenticate with username/email + 6-digit authenticator code
  • Email verification - Required during registration (6-digit codes)
  • TOTP 2FA - Industry-standard authenticator apps (Google Authenticator, Authy, etc.)
  • Backup codes - Emergency access codes for account recovery
  • Secure recovery - Requires email verification + original TOTP secret

User Registration Flow:

  1. Enter username and email
  2. Verify email with 6-digit code
  3. Setup authenticator app (scan QR code or manual entry)
  4. Verify TOTP code
  5. Save backup codes

User Login Flow:

  1. Enter username/email
  2. Enter 6-digit code from authenticator app

Account Recovery:

  1. Enter email → receive verification code
  2. Verify email code
  3. Enter original TOTP secret (saved during registration)
  4. Setup new authenticator
  5. Get new backup codes

⚠️ Important: Users must save their TOTP secret during registration for account recovery!

Caching System

TopicsFlow includes an intelligent Redis-based caching system that dramatically improves performance:

Features:

  • Automatic Caching: All database queries are automatically cached with appropriate TTLs
    • Static data (users, topics): 1 hour cache
    • Dynamic data (posts, comments, messages): 5 minutes cache
  • Automatic Invalidation: Cache is automatically invalidated when data is updated, ensuring consistency
  • Graceful Fallback: If Redis is unavailable, the application automatically falls back to direct database queries
  • Zero Configuration: Works automatically in Docker/Azure deployments with Redis

Local Development:

  • Redis cache is disabled by default on local machines
  • Uses filesystem sessions and direct database queries
  • No Redis installation required for local development

Docker/Azure Deployments:

  • Redis is automatically used for both sessions and caching
  • Provides 50-90% faster response times for cached queries
  • Automatic cache invalidation ensures data consistency
  • Docker: Redis is configured with password authentication (matches Azure approach)
  • Azure: Uses Azure Redis Cache with SSL and connection string format (host:port,password=...,ssl=True)

Cache Invalidation Strategy:

  • Direct updates invalidate the entity and related entities
  • Cascading invalidation ensures all dependent data is refreshed
  • Pattern-based invalidation for list queries

Production Deployment

For production deployment:

  1. Update environment variables with secure values
  2. Set up SSL certificates for HTTPS
  3. Use production Docker Compose file:
    ./START.sh prod
  4. Configure Nginx for reverse proxy and SSL termination

See Azure Deployment section for cloud deployment options.

API Documentation

Authentication Endpoints

Passwordless Registration (Step 1: Start Registration)

POST /api/auth/register-passwordlessContent-Type: application/json
{
"username": "username",
"email": "user@example.com"
}
Response 201:
{
"success": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Verification code sent to your email"
}

Verify Email (Step 2)

POST /api/auth/verify-emailContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}
Response 200:
{
"success": true,
"totp_qr_data": "otpauth://totp/TopicsFlow:username?secret=...",
"totp_secret": "JBSWY3DPEHPK3PXP",
"user_id": "507f1f77bcf86cd799439011"
}

Complete TOTP Setup (Step 3)

POST /api/auth/complete-totp-setupContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"totp_code": "123456"
}
Response 200:
{
"success": true,
"backup_codes": ["12345678", "23456789", ...]
}

Passwordless Login

POST /api/auth/login-passwordlessContent-Type: application/json
{
"identifier": "username", // username or email"totp_code": "123456"
}
Response 200:
{
"success": true,
"user": {
"id": "507f1f77bcf86cd799439011",
"username": "username",
"email": "user@example.com"
}
}

Response 200 (Email 2FA Required):

{
"success": false,
"require_email_2fa": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Please check your email for the verification code"
}

Verify Login Email 2FA

POST /api/auth/verify-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}

Resend Login Email 2FA Code

POST /api/auth/resend-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011"
}
Response 200:
{
"success": true,
"message": "Verification code sent.",
"cooldown": 60
}

Account Recovery

POST /api/auth/recovery/initiate-passwordlessContent-Type: application/json
{
"email": "user@example.com"
}
POST /api/auth/recovery/verify-email-codeContent-Type: application/json
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/recovery/reset-totpContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"original_secret": "JBSWY3DPEHPK3PXP"// Saved during registration
}

Topic Endpoints

Get Topics

GET /api/topics?sort_by=last_activity&limit=20&offset=0&tags=chat,gaming&search=gaming

Create Topic

POST /api/topicsContent-Type: application/jsonAuthorization: Session cookie
{
"title": "Topic Title",
"description": "Topic description",
"tags": ["chat", "gaming"],
"allow_anonymous": true,
"require_approval": false
}

Message Endpoints

Get Topic Messages

GET /api/messages/topic/{topic_id}?limit=50&before_message_id={message_id}

Send Message

POST /api/messages/topic/{topic_id}Content-Type: application/jsonAuthorization: Session cookie
{
"content": "Hello, world!",
"message_type": "text",
"use_anonymous": false,
"gif_url": "https://example.com/gif.gif"
}

Database Schema

Users Collection

{_id: ObjectId,username: String(unique,validated),email: String(unique),phone: String(optional,forrecovery),password_hash: String,totp_secret: String(encrypted),totp_enabled: Boolean,security_questions: [Array],is_banned: Boolean,ban_reason: String,ban_expiry: Date,ip_addresses: [String],created_at: Date,last_login: Date,preferences: {theme: String('dark'|'light'),language: String('en'|'pt'),anonymous_mode: Boolean}}

Topics Collection

{_id: ObjectId,title: String,description: String,owner_id: ObjectId,moderators: [{user_id: ObjectId,added_by: ObjectId,added_at: Date,permissions: [String]}],tags: [String],member_count: Number,is_public: Boolean,created_at: Date,last_activity: Date,settings: {allow_anonymous: Boolean,require_approval: Boolean}}

Messages Collection

{_id: ObjectId,topic_id: ObjectId,user_id: ObjectId,content: String,topic_id: ObjectId,chat_room_id: ObjectId,// For chat room messagesuser_id: ObjectId,content: String,message_type: String('text'|'emoji'|'gif'|'image'|'video'|'file'|'system'),anonymous_identity: String,gif_url: String,attachments: [{// File references (not base64 data)type: String,file_id: String,url: String,filename: String,size: Number,mime_type: String}],is_deleted: Boolean,deleted_by: ObjectId,deleted_at: Date,deletion_reason: String,// For owner deletionsreports: [{reported_by: ObjectId,reason: String,created_at: Date}],created_at: Date,updated_at: Date}

Chat Rooms Collection

{_id: ObjectId,topic_id: ObjectId,name: String,description: String,owner_id: ObjectId,moderators: [ObjectId],members: [ObjectId],picture: String,// Base64 profile picturebackground_picture: String,// Base64 background imageis_public: Boolean,created_at: Date,updated_at: Date}

Private Messages Collection

{_id: ObjectId,from_user_id: ObjectId,to_user_id: ObjectId,content: String,message_type: String,gif_url: String,deleted_for_user_ids: [ObjectId],// Soft delete per useris_read: Boolean,read_at: Date,created_at: Date}

Reports Collection

{_id: ObjectId,reporter_id: ObjectId,reported_user_id: ObjectId,content_id: String,// Message, post, comment, or chatroom IDcontent_type: String,// 'user' | 'message' | 'post' | 'comment' | 'chatroom' | 'chatroom_background' | 'chatroom_picture'reason: String,description: String,owner_id: ObjectId,// For chatroom/content reportsowner_username: String,moderators: [{id: ObjectId,username: String}],// For admin analysisstatus: String,created_at: Date}

Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    python app.py
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker run -d --name mongodb -p 27017:27017 mongo:7.0
    # Start Redis
    docker run -d --name redis -p 6379:6379 redis:7.2-alpine

Testing

Quick Testing Guide

# 1. Migrate database
python migrate_database.py migrate
# 2. Make admin user
python make_admin.py <username># 3. Start backendcd backend && python app.py
# 4. Start frontendcd frontend && npm run dev
# 5. Access app
http://localhost:3000

Test Scenarios

  1. Admin Controls: Login as admin, check for shield icon (🛡️) in top bar
  2. Clickable Usernames: Click username in chat → user banner appears
  3. Right-Click Menu: Right-click username → context menu with options
  4. Report User: Right-click → Report User → fill form → submit
  5. Ticket Creation: Profile menu → Open Ticket → create ticket
  6. Anonymous Mode: Enable "Use Anonymous" toggle in chat

Backend API Testing

Using Postman:

  1. Import tests/TopicsFlow_API.postman_collection.json
  2. Import environment file from tests/postman/environments/
  3. Run collection tests

Using Newman (CLI):

npm install -g newman newman-reporter-html
newman run tests/postman/TopicsFlow_Backend_API.postman_collection.json \
-e tests/postman/environments/Local.postman_environment.json \
-r html --reporter-html-export tests/reports/report.html

WebSocket Testing:

  • Use browser DevTools console
  • See tests/postman/TopicsFlow_WebSocket_Tests.md for detailed instructions

For comprehensive testing documentation, see:

  • TESTING_GUIDE.md - Quick testing scenarios
  • TEST_PLAN.md - Comprehensive test plan
  • tests/TESTING_GUIDE.md - Backend API testing guide
  • tests/TEST_TROUBLESHOOTING.md - Test troubleshooting

Code Quality

# Backend lintingcd backend
flake8 .
black .# Frontend lintingcd frontend
npm run lint
npm run type-check

Security Considerations

  • TOTP Secrets: Encrypted at rest using AES-256
  • Passwords: Hashed with bcrypt
  • Sessions: Secure session management with HTTP-only cookies
  • Rate Limiting: Implemented on all sensitive endpoints
  • Input Validation: Comprehensive validation and sanitization
  • HTTPS: Enforced in production
  • CORS: Properly configured for frontend domain
  • Content Security Policy: Headers implemented for XSS prevention

Monitoring & Logging

Application Logs

# View all service logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f backend
docker-compose logs -f frontend

Health Checks

  • Backend: GET /health
  • Frontend: HTTP status checks
  • Database: Connection health monitoring

Azure Deployment

Quick Start (5 minutes)

# 1. Install Azure CLI# Linux/Mac: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash# Windows: Download from https://aka.ms/installazurecliwindows# 2. Login to Azure
az login
# 3. Configure variables
cp .env.azure.example .env.azure
# Edit .env.azure with your values# 4. Deployexport$(cat .env.azure | xargs)
./azure-deploy.sh

Architecture

  • Backend: Flask + SocketIO + Static Frontend (served by Flask)
  • Database: Azure CosmosDB (MongoDB API)
  • Cache: Azure Cache for Redis (optional)
  • Deployment: Azure Container Apps
  • SSL: Automatic HTTPS

Environment Detection

The application automatically detects Azure environment via:

  • WEBSITE_INSTANCE_ID
  • AZURE_COSMOS_CONNECTIONSTRING

When detected, it automatically:

  • Uses CosmosDB instead of MongoDB
  • Configures SSL connections
  • Disables retryWrites (not supported by CosmosDB)
  • Serves static frontend

Required Azure Resources

  • Azure Container Registry (ACR)
  • Azure CosmosDB (MongoDB API)
  • Azure Container Apps Environment
  • Azure Container App

Cost Estimate

  • Container Apps: ~$40/month
  • CosmosDB: ~$24/month
  • Redis Cache: ~$16/month (optional)
  • Container Registry: ~$5/month
  • Total: ~$85/month (or ~$69 without Redis)

CI/CD with GitHub Actions

  1. Configure GitHub Secrets:

    • AZURE_CREDENTIALS - Service Principal JSON
    • AZURE_CONTAINER_REGISTRY - ACR name
    • AZURE_RESOURCE_GROUP - Resource group name
    • AZURE_APP_NAME - Container App name
    • ACR_USERNAME - ACR username
    • ACR_PASSWORD - ACR password
  2. Push to trigger deployment:

    git push origin main

See GITHUB_ACTIONS_SETUP.md for detailed CI/CD setup instructions.

For complete Azure deployment documentation, see:

  • AZURE_DEPLOYMENT.md - Comprehensive deployment guide
  • AZURE_QUICKSTART.md - Quick start guide

Troubleshooting

Common Issues

  1. Services won't start

    # Check if ports are available# Windows
    netstat -ano | findstr :5000
    taskkill /PID <number> /F
    # Linux/Mac
    lsof -i :3000
    lsof -i :5000
    lsof -i :27017
    lsof -i :6379
    # Clean and restart
    docker-compose down -v
    docker system prune -f
    ./START.sh
  2. Database connection issues

    # Check MongoDB logs
    docker-compose logs mongodb
    # Connect to MongoDB directly
    docker-compose exec mongodb mongosh
  3. TOTP authentication issues

    • Ensure server time is synchronized
    • Check TOTP secret encryption
    • Verify authenticator app time sync
    • Codes expire every 30 seconds - use current code
  4. Frontend build issues

    # Clear Next.js cache
    rm -rf .next
    npm run build
  5. Email not sending

    • Verify Resend API key is set: echo $RESEND_API_KEY
    • Check domain is verified in Resend dashboard
    • Verify FROM_EMAIL uses verified domain
    • Check backend logs for errors
  6. bcrypt module not found (Windows)

    # Solution 1: Reinstall bcrypt
    pip uninstall -y bcrypt
    pip install --only-binary :all: bcrypt==4.1.0
    # Solution 2: Install Visual Studio Build Tools# Download from https://visualstudio.microsoft.com/downloads/# Install "Desktop development with C++"# Solution 3: Use compatible version
    pip install bcrypt==4.0.1
  7. Port already in use (Windows)

    netstat -ano |findstr :5000
    taskkill /PID <number> /F
  8. MongoDB connection failed

    # Check if MongoDB is running
    docker ps | findstr mongodb
    # Start MongoDB
    docker start mongodb-test
    # Or create new container
    docker run -d --name mongodb-test -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    mongo:7.0

For Windows-specific troubleshooting, see WINDOWS_TROUBLESHOOTING.md.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test and python -m pytest
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow existing code patterns
  • Write tests for new features
  • Update documentation
  • Use descriptive commit messages
  • Keep PRs focused and manageable

License

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

Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section above
  • Review the API documentation

Acknowledgments

  • Built with Flask, Next.js, MongoDB, and Socket.IO
  • Inspired by Reddit's community structure
  • TOTP authentication standards
  • Open source libraries and frameworks used

About

Chat application that features publications and chatrooms by topic and direct messages and groups.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - 8JP8/TopicsFlow: Chat application that features publications and chatrooms by topic and direct messages and groups. · GitHub
Skip to content

Latest commit

History

161 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TopicsFlow App

📚 Comprehensive Documentation: Check out the Project Wiki for detailed guides on Architecture, API, Deployment, and more.

Overview

TopicsFlow is a comprehensive chat and topic discussion platform designed to facilitate focused conversations and community interactions.

🔐 Security & Authentication

  • Passwordless Authentication: Users log in via email/username + 6-digit TOTP code.
  • TOTP-based 2FA: Full compatibility with Google Authenticator, Microsoft Authenticator, and Authy.
  • Robust Account Recovery: Multi-step recovery using email verification and original TOTP secrets.
  • Backup Codes: 10 high-entropy emergency access codes provided during setup.
  • Secure Sessions: Encrypted session storage in Redis (Azure/Docker) or filesystem (local) with proper cookie security (HttpOnly).
  • Intelligent Caching: Redis-based caching system for database queries with automatic cache invalidation. Dramatically improves performance (50-90% faster response times) while ensuring data consistency.
  • Advanced Banning: Global banning system targeting IP addresses, emails, and phone numbers.

💬 Real-time Communication

  • Hybrid Platform: Seamless integration between Reddit-style forums and instant chat rooms.
  • WebSocket Foundation: Built on Socket.IO for sub-100ms latency.
  • Presence System: Real-time "online" status and typing indicators across the entire app.
  • Group Chat Rooms: Unlimited rooms per Topic with customizable profile/background images.
  • Direct Messaging (DMs): Private 1-on-1 conversations with encryption-ready architecture.
  • Voice Communication (VOIP): Integrated voice rooms with participant lists and active speaker detection.
  • Media Engine: Instant sharing of GIFs (Tenor), images, videos, and files with secure cloud storage.
  • Anonymous Mode: Per-topic identity masking with custom aliases to encourage open discussion.

📝 Content Management (The "Publications" System)

  • Dynamic Topics: Hierarchical community spaces for high-level categorization.
  • Publications (Posts): Reddit-style nested posts with rich text (Markdown) support.
  • Voting Mechanism: Positive/Negative reputation system for quality control.
  • Threaded Comments: Deeply nested conversations with @mentions and reply tracking.
  • Navigation Controls: Advanced sorting (Hot, New, Top) and tag-based discovery.
  • Search Engine: Rapid indexing of topics and posts for easy discovery.

🛡️ Moderation & Support

  • Admin Dashboard: Centralized command center for platform-wide oversight.
  • Integrated Ticket System: Direct communication channel between users and administrators for help requests.
  • Report Lifecycle: Comprehensive reporting for users/messages/posts with automated context attachment.
  • Role-based Access Control (RBAC): Granular permissions system (Owner -> Moderator -> Member).
  • Content Filtering: Integrated profanity filters and link sanitization.

🎨 Design & Accessibility

  • Responsive Architecture: Pixel-perfect layouts for Mobile, Tablet, and Desktop.
  • Modern Theme Engine: Dynamic Dark/Light mode switching with cohesive HSL color palettes.
  • Internationalization (i18n): Native-level support for English and Portuguese.
  • PWA Capabilities: Installable web app with push notifications and offline caching.
  • Accessibility: ARIA-compliant components and keyboard-friendly navigation.

Technology Stack

Backend

  • Flask (Python web framework)
  • Flask-SocketIO (real-time WebSocket communication)
  • MongoDB (NoSQL database)
  • PyOTP (TOTP authentication)
  • Redis (session storage and intelligent database caching with automatic invalidation)

Frontend

  • Next.js with TypeScript
  • Socket.IO Client (real-time communication)
  • Tailwind CSS (styling with theme variables)
  • React Hot Toast (notifications)
  • PWA capabilities with service workers and native install prompts
  • Image Viewer Modal: Full-screen image viewing with download controls
  • Enhanced Video Player: Fullscreen support, download, and right-click context menu
  • Context Menus: Right-click menus for posts, messages, chatrooms, and users

Infrastructure

  • Docker with multi-stage builds
  • Docker Compose for orchestration
  • Nginx reverse proxy (production)
  • Environment-based configuration

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local development)
  • Python 3.11+ (for local development)
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>cd RINTEP2
  2. Start the application

    ./START.sh

    This will:

    • Check prerequisites
    • Set up environment variables
    • Create necessary directories
    • Start all services (MongoDB, Redis, Backend, Frontend)
    • Wait for services to be healthy
  3. Access the application

Manual Setup (Alternative)

If you prefer to set up manually:

  1. Set up environment variables

    # Backend
    cp backend/env.example backend/.env
    # Frontend
    cp frontend/env.local.example frontend/.env.local
    # Edit the copied files with your configuration
  2. Start services with Docker Compose

    docker-compose up --build
  3. Or run locally for development

    Backend:

    cd backend
    python -m venv venv
    source venv/bin/activate # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python app.py

    Frontend:

    cd frontend
    npm install
    npm run dev

Configuration

Environment Variables

The application uses environment variables for configuration. You can set them up automatically or manually.

Automatic Setup (Recommended)

Windows:

setup-env.bat

Linux/Mac:

chmod +x setup-env.sh
./setup-env.sh

PowerShell:

powershell -ExecutionPolicy Bypass -File setup-env.ps1

Manual Setup

Create a .env file in the backend/ directory:

# Database ConfigurationDATABASE_URL=mongodb://localhost:27017/TopicsFlowREDIS_URL=redis://localhost:6379/0# Application ConfigurationSECRET_KEY=your_super_secret_key_hereFRONTEND_URL=http://localhost:3000TOTP_ISSUER=TopicsFlowAPP_NAME=TopicsFlow# Email Service (Resend)RESEND_API_KEY=your_resend_api_keyFROM_EMAIL=noreply@topicsflow.me# External ServicesTENOR_API_KEY=your_tenor_api_key# File Storage (Optional - for Azure deployments)USE_AZURE_STORAGE=falseAZURE_STORAGE_CONNECTION_STRING=your_azure_storage_connection_stringAZURE_STORAGE_CONTAINER=uploadsFILE_ENCRYPTION_KEY=your_file_encryption_key# Optional, defaults to SECRET_KEY# ImgBB (Optional - for large chatroom images)USE_IMGBB=falseIMGBB_API_KEY=your_imgbb_api_keyIMGBB_EXPIRATION_SECONDS=600IMGBB_MAX_BASE64_SIZE_BYTES=2097152# CORS (Development)CORS_ALLOW_ALL=true

Environment variables reference (Local + Azure)

You can use these example templates:

  • backend/env.example → copy to backend/.env
  • frontend/env.local.example → copy to frontend/.env.local

Backend (local development)

VariableDescriptionRequired
SECRET_KEYFlask secret key✅ Yes
ENVIRONMENTdevelopment/production (affects cookie security)Recommended
DATABASE_URLMongoDB connection string✅ Yes
DB_NAMEMongoDB database nameRecommended
REDIS_URLRedis connection string (sessions/rate limit)Recommended
FRONTEND_URLFrontend origin (CORS + passkeys)✅ Yes
CORS_ALLOW_ALLAllow all origins in devOptional
RESEND_API_KEYResend email API key✅ Yes
FROM_EMAILVerified sender email✅ Yes
APP_NAMEApp name used in emailsRecommended
TENOR_API_KEYTenor API key for GIF searchOptional
TENOR_CLIENT_KEYTenor client key (defaults to topicsflow_app)Optional
PASSKEY_RP_IDWebAuthn RP ID (defaults to localhost)Optional
LOG_LEVELLogging levelOptional

Backend storage (attachments)

VariableDescriptionRequired
USE_AZURE_STORAGEUse Azure Blob Storage for attachmentsOptional
AZURE_STORAGE_CONNECTION_STRINGAzure Storage connection stringRequired if USE_AZURE_STORAGE=true
AZURE_STORAGE_CONTAINERBlob container name (use uploads)Required if USE_AZURE_STORAGE=true
API_BASE_URLUsed to build attachment URLsRecommended
FILE_ENCRYPTION_KEYOptional encryption key for attachment URLs (defaults to SECRET_KEY)Optional

Backend ImgBB (recomended)

VariableDescriptionRequired
USE_IMGBBEnable ImgBB uploads for large imagesOptional
IMGBB_API_KEYImgBB API keyRequired if USE_IMGBB=true
IMGBB_EXPIRATION_SECONDSOptional ImgBB expirationOptional
IMGBB_MAX_BASE64_SIZE_BYTESThreshold to upload to ImgBBOptional

Backend (Azure/CosmosDB Mongo API)

VariableDescriptionRequired
AZURE_COSMOS_CONNECTIONSTRINGCosmosDB (Mongo API) connection string✅ Yes (Azure)
AZURE_COSMOS_DATABASECosmos database name✅ Yes (Azure)
COSMOS_DB_URI / COSMOS_DB_NAMEAlternative Cosmos env names supported by configOptional
AZURE_DEPLOYMENTSet to true to force Azure modeOptional
FORCE_AZURE_MODE / FORCE_LOCAL_MODEForce environment detectionOptional

Backend (Redis - Azure/Docker only)

VariableDescriptionRequired
AZURE_REDIS_CONNECTIONSTRINGAzure Redis Cache connection string (format: host:port,password=...,ssl=True)Optional (Azure only)
REDIS_URLRedis connection string (format: redis://password@host:port/0)Optional (Docker/Azure)
REDIS_PASSWORDRedis password (used in Docker Compose)Optional (Docker)
SESSION_TYPESession backend: filesystem (local) or redis (Docker/Azure)Auto-detected

Note: Redis is automatically disabled for local development (non-Docker). The application uses filesystem sessions and direct database queries when running locally without Docker.

Frontend

VariableDescriptionRequired
NEXT_PUBLIC_API_URLBackend base URL✅ Yes
NEXT_PUBLIC_APP_NAMEApp nameOptional
NEXT_PUBLIC_TENOR_API_KEYTenor API key (only if frontend uses it directly)Optional

Email Service Setup (Resend)

  1. Get your API key from Resend Dashboard
  2. Verify your domain in Resend Domains
  3. Add DNS records provided by Resend to your domain
  4. Set FROM_EMAIL to use your verified domain

Tenor API Setup

  1. Go to Tenor Developer Portal
  2. Sign in with Google account
  3. Create a new API key
  4. Add TENOR_API_KEY to your .env file

Passwordless Authentication

The application uses passwordless authentication with TOTP (Time-based One-Time Password):

  • No passwords - Users authenticate with username/email + 6-digit authenticator code
  • Email verification - Required during registration (6-digit codes)
  • TOTP 2FA - Industry-standard authenticator apps (Google Authenticator, Authy, etc.)
  • Backup codes - Emergency access codes for account recovery
  • Secure recovery - Requires email verification + original TOTP secret

User Registration Flow:

  1. Enter username and email
  2. Verify email with 6-digit code
  3. Setup authenticator app (scan QR code or manual entry)
  4. Verify TOTP code
  5. Save backup codes

User Login Flow:

  1. Enter username/email
  2. Enter 6-digit code from authenticator app

Account Recovery:

  1. Enter email → receive verification code
  2. Verify email code
  3. Enter original TOTP secret (saved during registration)
  4. Setup new authenticator
  5. Get new backup codes

⚠️ Important: Users must save their TOTP secret during registration for account recovery!

Caching System

TopicsFlow includes an intelligent Redis-based caching system that dramatically improves performance:

Features:

  • Automatic Caching: All database queries are automatically cached with appropriate TTLs
    • Static data (users, topics): 1 hour cache
    • Dynamic data (posts, comments, messages): 5 minutes cache
  • Automatic Invalidation: Cache is automatically invalidated when data is updated, ensuring consistency
  • Graceful Fallback: If Redis is unavailable, the application automatically falls back to direct database queries
  • Zero Configuration: Works automatically in Docker/Azure deployments with Redis

Local Development:

  • Redis cache is disabled by default on local machines
  • Uses filesystem sessions and direct database queries
  • No Redis installation required for local development

Docker/Azure Deployments:

  • Redis is automatically used for both sessions and caching
  • Provides 50-90% faster response times for cached queries
  • Automatic cache invalidation ensures data consistency
  • Docker: Redis is configured with password authentication (matches Azure approach)
  • Azure: Uses Azure Redis Cache with SSL and connection string format (host:port,password=...,ssl=True)

Cache Invalidation Strategy:

  • Direct updates invalidate the entity and related entities
  • Cascading invalidation ensures all dependent data is refreshed
  • Pattern-based invalidation for list queries

Production Deployment

For production deployment:

  1. Update environment variables with secure values
  2. Set up SSL certificates for HTTPS
  3. Use production Docker Compose file:
    ./START.sh prod
  4. Configure Nginx for reverse proxy and SSL termination

See Azure Deployment section for cloud deployment options.

API Documentation

Authentication Endpoints

Passwordless Registration (Step 1: Start Registration)

POST /api/auth/register-passwordlessContent-Type: application/json
{
"username": "username",
"email": "user@example.com"
}
Response 201:
{
"success": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Verification code sent to your email"
}

Verify Email (Step 2)

POST /api/auth/verify-emailContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}
Response 200:
{
"success": true,
"totp_qr_data": "otpauth://totp/TopicsFlow:username?secret=...",
"totp_secret": "JBSWY3DPEHPK3PXP",
"user_id": "507f1f77bcf86cd799439011"
}

Complete TOTP Setup (Step 3)

POST /api/auth/complete-totp-setupContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"totp_code": "123456"
}
Response 200:
{
"success": true,
"backup_codes": ["12345678", "23456789", ...]
}

Passwordless Login

POST /api/auth/login-passwordlessContent-Type: application/json
{
"identifier": "username", // username or email"totp_code": "123456"
}
Response 200:
{
"success": true,
"user": {
"id": "507f1f77bcf86cd799439011",
"username": "username",
"email": "user@example.com"
}
}

Response 200 (Email 2FA Required):

{
"success": false,
"require_email_2fa": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Please check your email for the verification code"
}

Verify Login Email 2FA

POST /api/auth/verify-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}

Resend Login Email 2FA Code

POST /api/auth/resend-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011"
}
Response 200:
{
"success": true,
"message": "Verification code sent.",
"cooldown": 60
}

Account Recovery

POST /api/auth/recovery/initiate-passwordlessContent-Type: application/json
{
"email": "user@example.com"
}
POST /api/auth/recovery/verify-email-codeContent-Type: application/json
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/recovery/reset-totpContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"original_secret": "JBSWY3DPEHPK3PXP"// Saved during registration
}

Topic Endpoints

Get Topics

GET /api/topics?sort_by=last_activity&limit=20&offset=0&tags=chat,gaming&search=gaming

Create Topic

POST /api/topicsContent-Type: application/jsonAuthorization: Session cookie
{
"title": "Topic Title",
"description": "Topic description",
"tags": ["chat", "gaming"],
"allow_anonymous": true,
"require_approval": false
}

Message Endpoints

Get Topic Messages

GET /api/messages/topic/{topic_id}?limit=50&before_message_id={message_id}

Send Message

POST /api/messages/topic/{topic_id}Content-Type: application/jsonAuthorization: Session cookie
{
"content": "Hello, world!",
"message_type": "text",
"use_anonymous": false,
"gif_url": "https://example.com/gif.gif"
}

Database Schema

Users Collection

{_id: ObjectId,username: String(unique,validated),email: String(unique),phone: String(optional,forrecovery),password_hash: String,totp_secret: String(encrypted),totp_enabled: Boolean,security_questions: [Array],is_banned: Boolean,ban_reason: String,ban_expiry: Date,ip_addresses: [String],created_at: Date,last_login: Date,preferences: {theme: String('dark'|'light'),language: String('en'|'pt'),anonymous_mode: Boolean}}

Topics Collection

{_id: ObjectId,title: String,description: String,owner_id: ObjectId,moderators: [{user_id: ObjectId,added_by: ObjectId,added_at: Date,permissions: [String]}],tags: [String],member_count: Number,is_public: Boolean,created_at: Date,last_activity: Date,settings: {allow_anonymous: Boolean,require_approval: Boolean}}

Messages Collection

{_id: ObjectId,topic_id: ObjectId,user_id: ObjectId,content: String,topic_id: ObjectId,chat_room_id: ObjectId,// For chat room messagesuser_id: ObjectId,content: String,message_type: String('text'|'emoji'|'gif'|'image'|'video'|'file'|'system'),anonymous_identity: String,gif_url: String,attachments: [{// File references (not base64 data)type: String,file_id: String,url: String,filename: String,size: Number,mime_type: String}],is_deleted: Boolean,deleted_by: ObjectId,deleted_at: Date,deletion_reason: String,// For owner deletionsreports: [{reported_by: ObjectId,reason: String,created_at: Date}],created_at: Date,updated_at: Date}

Chat Rooms Collection

{_id: ObjectId,topic_id: ObjectId,name: String,description: String,owner_id: ObjectId,moderators: [ObjectId],members: [ObjectId],picture: String,// Base64 profile picturebackground_picture: String,// Base64 background imageis_public: Boolean,created_at: Date,updated_at: Date}

Private Messages Collection

{_id: ObjectId,from_user_id: ObjectId,to_user_id: ObjectId,content: String,message_type: String,gif_url: String,deleted_for_user_ids: [ObjectId],// Soft delete per useris_read: Boolean,read_at: Date,created_at: Date}

Reports Collection

{_id: ObjectId,reporter_id: ObjectId,reported_user_id: ObjectId,content_id: String,// Message, post, comment, or chatroom IDcontent_type: String,// 'user' | 'message' | 'post' | 'comment' | 'chatroom' | 'chatroom_background' | 'chatroom_picture'reason: String,description: String,owner_id: ObjectId,// For chatroom/content reportsowner_username: String,moderators: [{id: ObjectId,username: String}],// For admin analysisstatus: String,created_at: Date}

Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    python app.py
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker run -d --name mongodb -p 27017:27017 mongo:7.0
    # Start Redis
    docker run -d --name redis -p 6379:6379 redis:7.2-alpine

Testing

Quick Testing Guide

# 1. Migrate database
python migrate_database.py migrate
# 2. Make admin user
python make_admin.py <username># 3. Start backendcd backend && python app.py
# 4. Start frontendcd frontend && npm run dev
# 5. Access app
http://localhost:3000

Test Scenarios

  1. Admin Controls: Login as admin, check for shield icon (🛡️) in top bar
  2. Clickable Usernames: Click username in chat → user banner appears
  3. Right-Click Menu: Right-click username → context menu with options
  4. Report User: Right-click → Report User → fill form → submit
  5. Ticket Creation: Profile menu → Open Ticket → create ticket
  6. Anonymous Mode: Enable "Use Anonymous" toggle in chat

Backend API Testing

Using Postman:

  1. Import tests/TopicsFlow_API.postman_collection.json
  2. Import environment file from tests/postman/environments/
  3. Run collection tests

Using Newman (CLI):

npm install -g newman newman-reporter-html
newman run tests/postman/TopicsFlow_Backend_API.postman_collection.json \
-e tests/postman/environments/Local.postman_environment.json \
-r html --reporter-html-export tests/reports/report.html

WebSocket Testing:

  • Use browser DevTools console
  • See tests/postman/TopicsFlow_WebSocket_Tests.md for detailed instructions

For comprehensive testing documentation, see:

  • TESTING_GUIDE.md - Quick testing scenarios
  • TEST_PLAN.md - Comprehensive test plan
  • tests/TESTING_GUIDE.md - Backend API testing guide
  • tests/TEST_TROUBLESHOOTING.md - Test troubleshooting

Code Quality

# Backend lintingcd backend
flake8 .
black .# Frontend lintingcd frontend
npm run lint
npm run type-check

Security Considerations

  • TOTP Secrets: Encrypted at rest using AES-256
  • Passwords: Hashed with bcrypt
  • Sessions: Secure session management with HTTP-only cookies
  • Rate Limiting: Implemented on all sensitive endpoints
  • Input Validation: Comprehensive validation and sanitization
  • HTTPS: Enforced in production
  • CORS: Properly configured for frontend domain
  • Content Security Policy: Headers implemented for XSS prevention

Monitoring & Logging

Application Logs

# View all service logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f backend
docker-compose logs -f frontend

Health Checks

  • Backend: GET /health
  • Frontend: HTTP status checks
  • Database: Connection health monitoring

Azure Deployment

Quick Start (5 minutes)

# 1. Install Azure CLI# Linux/Mac: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash# Windows: Download from https://aka.ms/installazurecliwindows# 2. Login to Azure
az login
# 3. Configure variables
cp .env.azure.example .env.azure
# Edit .env.azure with your values# 4. Deployexport$(cat .env.azure | xargs)
./azure-deploy.sh

Architecture

  • Backend: Flask + SocketIO + Static Frontend (served by Flask)
  • Database: Azure CosmosDB (MongoDB API)
  • Cache: Azure Cache for Redis (optional)
  • Deployment: Azure Container Apps
  • SSL: Automatic HTTPS

Environment Detection

The application automatically detects Azure environment via:

  • WEBSITE_INSTANCE_ID
  • AZURE_COSMOS_CONNECTIONSTRING

When detected, it automatically:

  • Uses CosmosDB instead of MongoDB
  • Configures SSL connections
  • Disables retryWrites (not supported by CosmosDB)
  • Serves static frontend

Required Azure Resources

  • Azure Container Registry (ACR)
  • Azure CosmosDB (MongoDB API)
  • Azure Container Apps Environment
  • Azure Container App

Cost Estimate

  • Container Apps: ~$40/month
  • CosmosDB: ~$24/month
  • Redis Cache: ~$16/month (optional)
  • Container Registry: ~$5/month
  • Total: ~$85/month (or ~$69 without Redis)

CI/CD with GitHub Actions

  1. Configure GitHub Secrets:

    • AZURE_CREDENTIALS - Service Principal JSON
    • AZURE_CONTAINER_REGISTRY - ACR name
    • AZURE_RESOURCE_GROUP - Resource group name
    • AZURE_APP_NAME - Container App name
    • ACR_USERNAME - ACR username
    • ACR_PASSWORD - ACR password
  2. Push to trigger deployment:

    git push origin main

See GITHUB_ACTIONS_SETUP.md for detailed CI/CD setup instructions.

For complete Azure deployment documentation, see:

  • AZURE_DEPLOYMENT.md - Comprehensive deployment guide
  • AZURE_QUICKSTART.md - Quick start guide

Troubleshooting

Common Issues

  1. Services won't start

    # Check if ports are available# Windows
    netstat -ano | findstr :5000
    taskkill /PID <number> /F
    # Linux/Mac
    lsof -i :3000
    lsof -i :5000
    lsof -i :27017
    lsof -i :6379
    # Clean and restart
    docker-compose down -v
    docker system prune -f
    ./START.sh
  2. Database connection issues

    # Check MongoDB logs
    docker-compose logs mongodb
    # Connect to MongoDB directly
    docker-compose exec mongodb mongosh
  3. TOTP authentication issues

    • Ensure server time is synchronized
    • Check TOTP secret encryption
    • Verify authenticator app time sync
    • Codes expire every 30 seconds - use current code
  4. Frontend build issues

    # Clear Next.js cache
    rm -rf .next
    npm run build
  5. Email not sending

    • Verify Resend API key is set: echo $RESEND_API_KEY
    • Check domain is verified in Resend dashboard
    • Verify FROM_EMAIL uses verified domain
    • Check backend logs for errors
  6. bcrypt module not found (Windows)

    # Solution 1: Reinstall bcrypt
    pip uninstall -y bcrypt
    pip install --only-binary :all: bcrypt==4.1.0
    # Solution 2: Install Visual Studio Build Tools# Download from https://visualstudio.microsoft.com/downloads/# Install "Desktop development with C++"# Solution 3: Use compatible version
    pip install bcrypt==4.0.1
  7. Port already in use (Windows)

    netstat -ano |findstr :5000
    taskkill /PID <number> /F
  8. MongoDB connection failed

    # Check if MongoDB is running
    docker ps | findstr mongodb
    # Start MongoDB
    docker start mongodb-test
    # Or create new container
    docker run -d --name mongodb-test -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    mongo:7.0

For Windows-specific troubleshooting, see WINDOWS_TROUBLESHOOTING.md.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test and python -m pytest
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow existing code patterns
  • Write tests for new features
  • Update documentation
  • Use descriptive commit messages
  • Keep PRs focused and manageable

License

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

Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section above
  • Review the API documentation

Acknowledgments

  • Built with Flask, Next.js, MongoDB, and Socket.IO
  • Inspired by Reddit's community structure
  • TOTP authentication standards
  • Open source libraries and frameworks used

About

Chat application that features publications and chatrooms by topic and direct messages and groups.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - 8JP8/TopicsFlow: Chat application that features publications and chatrooms by topic and direct messages and groups. · GitHub
Skip to content

Latest commit

History

161 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TopicsFlow App

📚 Comprehensive Documentation: Check out the Project Wiki for detailed guides on Architecture, API, Deployment, and more.

Overview

TopicsFlow is a comprehensive chat and topic discussion platform designed to facilitate focused conversations and community interactions.

🔐 Security & Authentication

  • Passwordless Authentication: Users log in via email/username + 6-digit TOTP code.
  • TOTP-based 2FA: Full compatibility with Google Authenticator, Microsoft Authenticator, and Authy.
  • Robust Account Recovery: Multi-step recovery using email verification and original TOTP secrets.
  • Backup Codes: 10 high-entropy emergency access codes provided during setup.
  • Secure Sessions: Encrypted session storage in Redis (Azure/Docker) or filesystem (local) with proper cookie security (HttpOnly).
  • Intelligent Caching: Redis-based caching system for database queries with automatic cache invalidation. Dramatically improves performance (50-90% faster response times) while ensuring data consistency.
  • Advanced Banning: Global banning system targeting IP addresses, emails, and phone numbers.

💬 Real-time Communication

  • Hybrid Platform: Seamless integration between Reddit-style forums and instant chat rooms.
  • WebSocket Foundation: Built on Socket.IO for sub-100ms latency.
  • Presence System: Real-time "online" status and typing indicators across the entire app.
  • Group Chat Rooms: Unlimited rooms per Topic with customizable profile/background images.
  • Direct Messaging (DMs): Private 1-on-1 conversations with encryption-ready architecture.
  • Voice Communication (VOIP): Integrated voice rooms with participant lists and active speaker detection.
  • Media Engine: Instant sharing of GIFs (Tenor), images, videos, and files with secure cloud storage.
  • Anonymous Mode: Per-topic identity masking with custom aliases to encourage open discussion.

📝 Content Management (The "Publications" System)

  • Dynamic Topics: Hierarchical community spaces for high-level categorization.
  • Publications (Posts): Reddit-style nested posts with rich text (Markdown) support.
  • Voting Mechanism: Positive/Negative reputation system for quality control.
  • Threaded Comments: Deeply nested conversations with @mentions and reply tracking.
  • Navigation Controls: Advanced sorting (Hot, New, Top) and tag-based discovery.
  • Search Engine: Rapid indexing of topics and posts for easy discovery.

🛡️ Moderation & Support

  • Admin Dashboard: Centralized command center for platform-wide oversight.
  • Integrated Ticket System: Direct communication channel between users and administrators for help requests.
  • Report Lifecycle: Comprehensive reporting for users/messages/posts with automated context attachment.
  • Role-based Access Control (RBAC): Granular permissions system (Owner -> Moderator -> Member).
  • Content Filtering: Integrated profanity filters and link sanitization.

🎨 Design & Accessibility

  • Responsive Architecture: Pixel-perfect layouts for Mobile, Tablet, and Desktop.
  • Modern Theme Engine: Dynamic Dark/Light mode switching with cohesive HSL color palettes.
  • Internationalization (i18n): Native-level support for English and Portuguese.
  • PWA Capabilities: Installable web app with push notifications and offline caching.
  • Accessibility: ARIA-compliant components and keyboard-friendly navigation.

Technology Stack

Backend

  • Flask (Python web framework)
  • Flask-SocketIO (real-time WebSocket communication)
  • MongoDB (NoSQL database)
  • PyOTP (TOTP authentication)
  • Redis (session storage and intelligent database caching with automatic invalidation)

Frontend

  • Next.js with TypeScript
  • Socket.IO Client (real-time communication)
  • Tailwind CSS (styling with theme variables)
  • React Hot Toast (notifications)
  • PWA capabilities with service workers and native install prompts
  • Image Viewer Modal: Full-screen image viewing with download controls
  • Enhanced Video Player: Fullscreen support, download, and right-click context menu
  • Context Menus: Right-click menus for posts, messages, chatrooms, and users

Infrastructure

  • Docker with multi-stage builds
  • Docker Compose for orchestration
  • Nginx reverse proxy (production)
  • Environment-based configuration

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Node.js 18+ (for local development)
  • Python 3.11+ (for local development)
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>cd RINTEP2
  2. Start the application

    ./START.sh

    This will:

    • Check prerequisites
    • Set up environment variables
    • Create necessary directories
    • Start all services (MongoDB, Redis, Backend, Frontend)
    • Wait for services to be healthy
  3. Access the application

Manual Setup (Alternative)

If you prefer to set up manually:

  1. Set up environment variables

    # Backend
    cp backend/env.example backend/.env
    # Frontend
    cp frontend/env.local.example frontend/.env.local
    # Edit the copied files with your configuration
  2. Start services with Docker Compose

    docker-compose up --build
  3. Or run locally for development

    Backend:

    cd backend
    python -m venv venv
    source venv/bin/activate # On Windows: venv\Scripts\activate
    pip install -r requirements.txt
    python app.py

    Frontend:

    cd frontend
    npm install
    npm run dev

Configuration

Environment Variables

The application uses environment variables for configuration. You can set them up automatically or manually.

Automatic Setup (Recommended)

Windows:

setup-env.bat

Linux/Mac:

chmod +x setup-env.sh
./setup-env.sh

PowerShell:

powershell -ExecutionPolicy Bypass -File setup-env.ps1

Manual Setup

Create a .env file in the backend/ directory:

# Database ConfigurationDATABASE_URL=mongodb://localhost:27017/TopicsFlowREDIS_URL=redis://localhost:6379/0# Application ConfigurationSECRET_KEY=your_super_secret_key_hereFRONTEND_URL=http://localhost:3000TOTP_ISSUER=TopicsFlowAPP_NAME=TopicsFlow# Email Service (Resend)RESEND_API_KEY=your_resend_api_keyFROM_EMAIL=noreply@topicsflow.me# External ServicesTENOR_API_KEY=your_tenor_api_key# File Storage (Optional - for Azure deployments)USE_AZURE_STORAGE=falseAZURE_STORAGE_CONNECTION_STRING=your_azure_storage_connection_stringAZURE_STORAGE_CONTAINER=uploadsFILE_ENCRYPTION_KEY=your_file_encryption_key# Optional, defaults to SECRET_KEY# ImgBB (Optional - for large chatroom images)USE_IMGBB=falseIMGBB_API_KEY=your_imgbb_api_keyIMGBB_EXPIRATION_SECONDS=600IMGBB_MAX_BASE64_SIZE_BYTES=2097152# CORS (Development)CORS_ALLOW_ALL=true

Environment variables reference (Local + Azure)

You can use these example templates:

  • backend/env.example → copy to backend/.env
  • frontend/env.local.example → copy to frontend/.env.local

Backend (local development)

VariableDescriptionRequired
SECRET_KEYFlask secret key✅ Yes
ENVIRONMENTdevelopment/production (affects cookie security)Recommended
DATABASE_URLMongoDB connection string✅ Yes
DB_NAMEMongoDB database nameRecommended
REDIS_URLRedis connection string (sessions/rate limit)Recommended
FRONTEND_URLFrontend origin (CORS + passkeys)✅ Yes
CORS_ALLOW_ALLAllow all origins in devOptional
RESEND_API_KEYResend email API key✅ Yes
FROM_EMAILVerified sender email✅ Yes
APP_NAMEApp name used in emailsRecommended
TENOR_API_KEYTenor API key for GIF searchOptional
TENOR_CLIENT_KEYTenor client key (defaults to topicsflow_app)Optional
PASSKEY_RP_IDWebAuthn RP ID (defaults to localhost)Optional
LOG_LEVELLogging levelOptional

Backend storage (attachments)

VariableDescriptionRequired
USE_AZURE_STORAGEUse Azure Blob Storage for attachmentsOptional
AZURE_STORAGE_CONNECTION_STRINGAzure Storage connection stringRequired if USE_AZURE_STORAGE=true
AZURE_STORAGE_CONTAINERBlob container name (use uploads)Required if USE_AZURE_STORAGE=true
API_BASE_URLUsed to build attachment URLsRecommended
FILE_ENCRYPTION_KEYOptional encryption key for attachment URLs (defaults to SECRET_KEY)Optional

Backend ImgBB (recomended)

VariableDescriptionRequired
USE_IMGBBEnable ImgBB uploads for large imagesOptional
IMGBB_API_KEYImgBB API keyRequired if USE_IMGBB=true
IMGBB_EXPIRATION_SECONDSOptional ImgBB expirationOptional
IMGBB_MAX_BASE64_SIZE_BYTESThreshold to upload to ImgBBOptional

Backend (Azure/CosmosDB Mongo API)

VariableDescriptionRequired
AZURE_COSMOS_CONNECTIONSTRINGCosmosDB (Mongo API) connection string✅ Yes (Azure)
AZURE_COSMOS_DATABASECosmos database name✅ Yes (Azure)
COSMOS_DB_URI / COSMOS_DB_NAMEAlternative Cosmos env names supported by configOptional
AZURE_DEPLOYMENTSet to true to force Azure modeOptional
FORCE_AZURE_MODE / FORCE_LOCAL_MODEForce environment detectionOptional

Backend (Redis - Azure/Docker only)

VariableDescriptionRequired
AZURE_REDIS_CONNECTIONSTRINGAzure Redis Cache connection string (format: host:port,password=...,ssl=True)Optional (Azure only)
REDIS_URLRedis connection string (format: redis://password@host:port/0)Optional (Docker/Azure)
REDIS_PASSWORDRedis password (used in Docker Compose)Optional (Docker)
SESSION_TYPESession backend: filesystem (local) or redis (Docker/Azure)Auto-detected

Note: Redis is automatically disabled for local development (non-Docker). The application uses filesystem sessions and direct database queries when running locally without Docker.

Frontend

VariableDescriptionRequired
NEXT_PUBLIC_API_URLBackend base URL✅ Yes
NEXT_PUBLIC_APP_NAMEApp nameOptional
NEXT_PUBLIC_TENOR_API_KEYTenor API key (only if frontend uses it directly)Optional

Email Service Setup (Resend)

  1. Get your API key from Resend Dashboard
  2. Verify your domain in Resend Domains
  3. Add DNS records provided by Resend to your domain
  4. Set FROM_EMAIL to use your verified domain

Tenor API Setup

  1. Go to Tenor Developer Portal
  2. Sign in with Google account
  3. Create a new API key
  4. Add TENOR_API_KEY to your .env file

Passwordless Authentication

The application uses passwordless authentication with TOTP (Time-based One-Time Password):

  • No passwords - Users authenticate with username/email + 6-digit authenticator code
  • Email verification - Required during registration (6-digit codes)
  • TOTP 2FA - Industry-standard authenticator apps (Google Authenticator, Authy, etc.)
  • Backup codes - Emergency access codes for account recovery
  • Secure recovery - Requires email verification + original TOTP secret

User Registration Flow:

  1. Enter username and email
  2. Verify email with 6-digit code
  3. Setup authenticator app (scan QR code or manual entry)
  4. Verify TOTP code
  5. Save backup codes

User Login Flow:

  1. Enter username/email
  2. Enter 6-digit code from authenticator app

Account Recovery:

  1. Enter email → receive verification code
  2. Verify email code
  3. Enter original TOTP secret (saved during registration)
  4. Setup new authenticator
  5. Get new backup codes

⚠️ Important: Users must save their TOTP secret during registration for account recovery!

Caching System

TopicsFlow includes an intelligent Redis-based caching system that dramatically improves performance:

Features:

  • Automatic Caching: All database queries are automatically cached with appropriate TTLs
    • Static data (users, topics): 1 hour cache
    • Dynamic data (posts, comments, messages): 5 minutes cache
  • Automatic Invalidation: Cache is automatically invalidated when data is updated, ensuring consistency
  • Graceful Fallback: If Redis is unavailable, the application automatically falls back to direct database queries
  • Zero Configuration: Works automatically in Docker/Azure deployments with Redis

Local Development:

  • Redis cache is disabled by default on local machines
  • Uses filesystem sessions and direct database queries
  • No Redis installation required for local development

Docker/Azure Deployments:

  • Redis is automatically used for both sessions and caching
  • Provides 50-90% faster response times for cached queries
  • Automatic cache invalidation ensures data consistency
  • Docker: Redis is configured with password authentication (matches Azure approach)
  • Azure: Uses Azure Redis Cache with SSL and connection string format (host:port,password=...,ssl=True)

Cache Invalidation Strategy:

  • Direct updates invalidate the entity and related entities
  • Cascading invalidation ensures all dependent data is refreshed
  • Pattern-based invalidation for list queries

Production Deployment

For production deployment:

  1. Update environment variables with secure values
  2. Set up SSL certificates for HTTPS
  3. Use production Docker Compose file:
    ./START.sh prod
  4. Configure Nginx for reverse proxy and SSL termination

See Azure Deployment section for cloud deployment options.

API Documentation

Authentication Endpoints

Passwordless Registration (Step 1: Start Registration)

POST /api/auth/register-passwordlessContent-Type: application/json
{
"username": "username",
"email": "user@example.com"
}
Response 201:
{
"success": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Verification code sent to your email"
}

Verify Email (Step 2)

POST /api/auth/verify-emailContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}
Response 200:
{
"success": true,
"totp_qr_data": "otpauth://totp/TopicsFlow:username?secret=...",
"totp_secret": "JBSWY3DPEHPK3PXP",
"user_id": "507f1f77bcf86cd799439011"
}

Complete TOTP Setup (Step 3)

POST /api/auth/complete-totp-setupContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"totp_code": "123456"
}
Response 200:
{
"success": true,
"backup_codes": ["12345678", "23456789", ...]
}

Passwordless Login

POST /api/auth/login-passwordlessContent-Type: application/json
{
"identifier": "username", // username or email"totp_code": "123456"
}
Response 200:
{
"success": true,
"user": {
"id": "507f1f77bcf86cd799439011",
"username": "username",
"email": "user@example.com"
}
}

Response 200 (Email 2FA Required):

{
"success": false,
"require_email_2fa": true,
"user_id": "507f1f77bcf86cd799439011",
"message": "Please check your email for the verification code"
}

Verify Login Email 2FA

POST /api/auth/verify-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"code": "123456"
}

Resend Login Email 2FA Code

POST /api/auth/resend-login-email-2faContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011"
}
Response 200:
{
"success": true,
"message": "Verification code sent.",
"cooldown": 60
}

Account Recovery

POST /api/auth/recovery/initiate-passwordlessContent-Type: application/json
{
"email": "user@example.com"
}
POST /api/auth/recovery/verify-email-codeContent-Type: application/json
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/recovery/reset-totpContent-Type: application/json
{
"user_id": "507f1f77bcf86cd799439011",
"original_secret": "JBSWY3DPEHPK3PXP"// Saved during registration
}

Topic Endpoints

Get Topics

GET /api/topics?sort_by=last_activity&limit=20&offset=0&tags=chat,gaming&search=gaming

Create Topic

POST /api/topicsContent-Type: application/jsonAuthorization: Session cookie
{
"title": "Topic Title",
"description": "Topic description",
"tags": ["chat", "gaming"],
"allow_anonymous": true,
"require_approval": false
}

Message Endpoints

Get Topic Messages

GET /api/messages/topic/{topic_id}?limit=50&before_message_id={message_id}

Send Message

POST /api/messages/topic/{topic_id}Content-Type: application/jsonAuthorization: Session cookie
{
"content": "Hello, world!",
"message_type": "text",
"use_anonymous": false,
"gif_url": "https://example.com/gif.gif"
}

Database Schema

Users Collection

{_id: ObjectId,username: String(unique,validated),email: String(unique),phone: String(optional,forrecovery),password_hash: String,totp_secret: String(encrypted),totp_enabled: Boolean,security_questions: [Array],is_banned: Boolean,ban_reason: String,ban_expiry: Date,ip_addresses: [String],created_at: Date,last_login: Date,preferences: {theme: String('dark'|'light'),language: String('en'|'pt'),anonymous_mode: Boolean}}

Topics Collection

{_id: ObjectId,title: String,description: String,owner_id: ObjectId,moderators: [{user_id: ObjectId,added_by: ObjectId,added_at: Date,permissions: [String]}],tags: [String],member_count: Number,is_public: Boolean,created_at: Date,last_activity: Date,settings: {allow_anonymous: Boolean,require_approval: Boolean}}

Messages Collection

{_id: ObjectId,topic_id: ObjectId,user_id: ObjectId,content: String,topic_id: ObjectId,chat_room_id: ObjectId,// For chat room messagesuser_id: ObjectId,content: String,message_type: String('text'|'emoji'|'gif'|'image'|'video'|'file'|'system'),anonymous_identity: String,gif_url: String,attachments: [{// File references (not base64 data)type: String,file_id: String,url: String,filename: String,size: Number,mime_type: String}],is_deleted: Boolean,deleted_by: ObjectId,deleted_at: Date,deletion_reason: String,// For owner deletionsreports: [{reported_by: ObjectId,reason: String,created_at: Date}],created_at: Date,updated_at: Date}

Chat Rooms Collection

{_id: ObjectId,topic_id: ObjectId,name: String,description: String,owner_id: ObjectId,moderators: [ObjectId],members: [ObjectId],picture: String,// Base64 profile picturebackground_picture: String,// Base64 background imageis_public: Boolean,created_at: Date,updated_at: Date}

Private Messages Collection

{_id: ObjectId,from_user_id: ObjectId,to_user_id: ObjectId,content: String,message_type: String,gif_url: String,deleted_for_user_ids: [ObjectId],// Soft delete per useris_read: Boolean,read_at: Date,created_at: Date}

Reports Collection

{_id: ObjectId,reporter_id: ObjectId,reported_user_id: ObjectId,content_id: String,// Message, post, comment, or chatroom IDcontent_type: String,// 'user' | 'message' | 'post' | 'comment' | 'chatroom' | 'chatroom_background' | 'chatroom_picture'reason: String,description: String,owner_id: ObjectId,// For chatroom/content reportsowner_username: String,moderators: [{id: ObjectId,username: String}],// For admin analysisstatus: String,created_at: Date}

Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    python app.py
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker run -d --name mongodb -p 27017:27017 mongo:7.0
    # Start Redis
    docker run -d --name redis -p 6379:6379 redis:7.2-alpine

Testing

Quick Testing Guide

# 1. Migrate database
python migrate_database.py migrate
# 2. Make admin user
python make_admin.py <username># 3. Start backendcd backend && python app.py
# 4. Start frontendcd frontend && npm run dev
# 5. Access app
http://localhost:3000

Test Scenarios

  1. Admin Controls: Login as admin, check for shield icon (🛡️) in top bar
  2. Clickable Usernames: Click username in chat → user banner appears
  3. Right-Click Menu: Right-click username → context menu with options
  4. Report User: Right-click → Report User → fill form → submit
  5. Ticket Creation: Profile menu → Open Ticket → create ticket
  6. Anonymous Mode: Enable "Use Anonymous" toggle in chat

Backend API Testing

Using Postman:

  1. Import tests/TopicsFlow_API.postman_collection.json
  2. Import environment file from tests/postman/environments/
  3. Run collection tests

Using Newman (CLI):

npm install -g newman newman-reporter-html
newman run tests/postman/TopicsFlow_Backend_API.postman_collection.json \
-e tests/postman/environments/Local.postman_environment.json \
-r html --reporter-html-export tests/reports/report.html

WebSocket Testing:

  • Use browser DevTools console
  • See tests/postman/TopicsFlow_WebSocket_Tests.md for detailed instructions

For comprehensive testing documentation, see:

  • TESTING_GUIDE.md - Quick testing scenarios
  • TEST_PLAN.md - Comprehensive test plan
  • tests/TESTING_GUIDE.md - Backend API testing guide
  • tests/TEST_TROUBLESHOOTING.md - Test troubleshooting

Code Quality

# Backend lintingcd backend
flake8 .
black .# Frontend lintingcd frontend
npm run lint
npm run type-check

Security Considerations

  • TOTP Secrets: Encrypted at rest using AES-256
  • Passwords: Hashed with bcrypt
  • Sessions: Secure session management with HTTP-only cookies
  • Rate Limiting: Implemented on all sensitive endpoints
  • Input Validation: Comprehensive validation and sanitization
  • HTTPS: Enforced in production
  • CORS: Properly configured for frontend domain
  • Content Security Policy: Headers implemented for XSS prevention

Monitoring & Logging

Application Logs

# View all service logs
docker-compose logs -f
# View specific service logs
docker-compose logs -f backend
docker-compose logs -f frontend

Health Checks

  • Backend: GET /health
  • Frontend: HTTP status checks
  • Database: Connection health monitoring

Azure Deployment

Quick Start (5 minutes)

# 1. Install Azure CLI# Linux/Mac: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash# Windows: Download from https://aka.ms/installazurecliwindows# 2. Login to Azure
az login
# 3. Configure variables
cp .env.azure.example .env.azure
# Edit .env.azure with your values# 4. Deployexport$(cat .env.azure | xargs)
./azure-deploy.sh

Architecture

  • Backend: Flask + SocketIO + Static Frontend (served by Flask)
  • Database: Azure CosmosDB (MongoDB API)
  • Cache: Azure Cache for Redis (optional)
  • Deployment: Azure Container Apps
  • SSL: Automatic HTTPS

Environment Detection

The application automatically detects Azure environment via:

  • WEBSITE_INSTANCE_ID
  • AZURE_COSMOS_CONNECTIONSTRING

When detected, it automatically:

  • Uses CosmosDB instead of MongoDB
  • Configures SSL connections
  • Disables retryWrites (not supported by CosmosDB)
  • Serves static frontend

Required Azure Resources

  • Azure Container Registry (ACR)
  • Azure CosmosDB (MongoDB API)
  • Azure Container Apps Environment
  • Azure Container App

Cost Estimate

  • Container Apps: ~$40/month
  • CosmosDB: ~$24/month
  • Redis Cache: ~$16/month (optional)
  • Container Registry: ~$5/month
  • Total: ~$85/month (or ~$69 without Redis)

CI/CD with GitHub Actions

  1. Configure GitHub Secrets:

    • AZURE_CREDENTIALS - Service Principal JSON
    • AZURE_CONTAINER_REGISTRY - ACR name
    • AZURE_RESOURCE_GROUP - Resource group name
    • AZURE_APP_NAME - Container App name
    • ACR_USERNAME - ACR username
    • ACR_PASSWORD - ACR password
  2. Push to trigger deployment:

    git push origin main

See GITHUB_ACTIONS_SETUP.md for detailed CI/CD setup instructions.

For complete Azure deployment documentation, see:

  • AZURE_DEPLOYMENT.md - Comprehensive deployment guide
  • AZURE_QUICKSTART.md - Quick start guide

Troubleshooting

Common Issues

  1. Services won't start

    # Check if ports are available# Windows
    netstat -ano | findstr :5000
    taskkill /PID <number> /F
    # Linux/Mac
    lsof -i :3000
    lsof -i :5000
    lsof -i :27017
    lsof -i :6379
    # Clean and restart
    docker-compose down -v
    docker system prune -f
    ./START.sh
  2. Database connection issues

    # Check MongoDB logs
    docker-compose logs mongodb
    # Connect to MongoDB directly
    docker-compose exec mongodb mongosh
  3. TOTP authentication issues

    • Ensure server time is synchronized
    • Check TOTP secret encryption
    • Verify authenticator app time sync
    • Codes expire every 30 seconds - use current code
  4. Frontend build issues

    # Clear Next.js cache
    rm -rf .next
    npm run build
  5. Email not sending

    • Verify Resend API key is set: echo $RESEND_API_KEY
    • Check domain is verified in Resend dashboard
    • Verify FROM_EMAIL uses verified domain
    • Check backend logs for errors
  6. bcrypt module not found (Windows)

    # Solution 1: Reinstall bcrypt
    pip uninstall -y bcrypt
    pip install --only-binary :all: bcrypt==4.1.0
    # Solution 2: Install Visual Studio Build Tools# Download from https://visualstudio.microsoft.com/downloads/# Install "Desktop development with C++"# Solution 3: Use compatible version
    pip install bcrypt==4.0.1
  7. Port already in use (Windows)

    netstat -ano |findstr :5000
    taskkill /PID <number> /F
  8. MongoDB connection failed

    # Check if MongoDB is running
    docker ps | findstr mongodb
    # Start MongoDB
    docker start mongodb-test
    # Or create new container
    docker run -d --name mongodb-test -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=password123 \
    mongo:7.0

For Windows-specific troubleshooting, see WINDOWS_TROUBLESHOOTING.md.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test and python -m pytest
  5. Commit your changes: git commit -m 'Add amazing feature'
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request

Development Guidelines

  • Follow existing code patterns
  • Write tests for new features
  • Update documentation
  • Use descriptive commit messages
  • Keep PRs focused and manageable

License

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

Support

For support and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section above
  • Review the API documentation

Acknowledgments

  • Built with Flask, Next.js, MongoDB, and Socket.IO
  • Inspired by Reddit's community structure
  • TOTP authentication standards
  • Open source libraries and frameworks used

About

Chat application that features publications and chatrooms by topic and direct messages and groups.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages