Skip to content

🏢 Appgain Server

Core business logic, CRM, analytics, and multi-tenant platform

Overview

The Appgain Server is the central business logic engine that powers the entire Appgain platform. It handles user management, CRM operations, analytics, multi-tenant architecture, and serves as the primary backend for all Appgain applications.

🏗️ Architecture

Core Responsibilities

  • User Management: Authentication, authorization, and user profile management
  • CRM Operations: Customer relationship management and data processing
  • Analytics Engine: Data collection, processing, and business intelligence
  • Multi-tenant Support: Isolated data and operations for different clients
  • API Management: RESTful API endpoints for all platform operations
  • Business Logic: Core application logic and workflow management

Technology Stack

  • Node.js: Runtime environment
  • Express.js: Web application framework
  • MongoDB: Primary database
  • Redis: Caching and session management
  • JWT: Authentication and authorization
  • Socket.io: Real-time communication

🔧 Configuration

Server Details

  • Server: ovh-appgain-server
  • Port: 3000 (HTTP), 3001 (HTTPS)
  • Environment: Production, Staging, Development

Environment Variables

# Database Configuration
MONGODB_URI=mongodb://localhost:27017/appgain
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=ask your direct manager for the access

# Authentication
JWT_SECRET=ask your direct manager for the access
JWT_EXPIRES_IN=24h
SESSION_SECRET=ask your direct manager for the access

# External Services
PARSE_SERVER_URL=http://ovh-parse-server:1337/parse
NOTIFY_SERVICE_URL=http://ovh-parse-server:3001
ADMIN_SERVER_URL=http://ovh-devops:5000

# Monitoring
SENTRY_DSN=ask your direct manager for the access
PROMETHEUS_ENABLED=true
LOG_LEVEL=info

🔐 Authentication & Authorization

JWT Token Structure

{
  "header": {
    "alg": "HS256",
    "typ": "JWT"
  },
  "payload": {
    "userId": "user_id",
    "accountId": "account_id",
    "suitId": "suit_id",
    "role": "admin|user|viewer",
    "permissions": ["read", "write", "delete"],
    "iat": 1640995200,
    "exp": 1641081600
  }
}

Role-Based Access Control

// User Roles
const ROLES = {
  SUPER_ADMIN: 'super_admin',    // Platform-wide access
  ACCOUNT_ADMIN: 'account_admin', // Account-level access
  USER: 'user',                  // Standard user access
  VIEWER: 'viewer'               // Read-only access
};

// Permissions
const PERMISSIONS = {
  USERS_READ: 'users:read',
  USERS_WRITE: 'users:write',
  USERS_DELETE: 'users:delete',
  ANALYTICS_READ: 'analytics:read',
  ANALYTICS_WRITE: 'analytics:write',
  SETTINGS_READ: 'settings:read',
  SETTINGS_WRITE: 'settings:write'
};

📊 API Endpoints

User Management

# Authentication
POST   /api/auth/login              # User login
POST   /api/auth/logout             # User logout
POST   /api/auth/refresh            # Refresh token
POST   /api/auth/forgot-password    # Password reset

# User Operations
GET    /api/users                   # List users
POST   /api/users                   # Create user
GET    /api/users/:id               # Get user details
PUT    /api/users/:id               # Update user
DELETE /api/users/:id               # Delete user
PUT    /api/users/:id/password      # Change password

Account Management

# Account Operations
GET    /api/accounts                # List accounts
POST   /api/accounts                # Create account
GET    /api/accounts/:id            # Get account details
PUT    /api/accounts/:id            # Update account
DELETE /api/accounts/:id            # Delete account

# Account Settings
GET    /api/accounts/:id/settings   # Get account settings
PUT    /api/accounts/:id/settings   # Update account settings

Suit Management

# Suit Operations
GET    /api/suits                   # List suits
POST   /api/suits                   # Create suit
GET    /api/suits/:id               # Get suit details
PUT    /api/suits/:id               # Update suit
DELETE /api/suits/:id               # Delete suit

# Suit Configuration
GET    /api/suits/:id/config        # Get suit configuration
PUT    /api/suits/:id/config        # Update suit configuration
POST   /api/suits/:id/deploy        # Deploy suit

Analytics & Reporting

# Analytics Data
GET    /api/analytics/users         # User analytics
GET    /api/analytics/engagement    # Engagement metrics
GET    /api/analytics/revenue       # Revenue analytics
GET    /api/analytics/performance   # Performance metrics

# Reports
GET    /api/reports/daily           # Daily reports
GET    /api/reports/weekly          # Weekly reports
GET    /api/reports/monthly         # Monthly reports
POST   /api/reports/generate        # Generate custom report

🗄️ Database Schema

Users Collection

{
  "_id": "ObjectId",
  "email": "user@example.com",
      "password": "ask your direct manager for the access",
  "firstName": "John",
  "lastName": "Doe",
  "role": "user",
  "accountId": "account_id",
  "suitIds": ["suit_id_1", "suit_id_2"],
  "permissions": ["read", "write"],
  "status": "active|inactive|suspended",
  "lastLogin": "2024-01-01T00:00:00Z",
  "createdAt": "2024-01-01T00:00:00Z",
  "updatedAt": "2024-01-01T00:00:00Z"
}

Accounts Collection

{
  "_id": "ObjectId",
  "name": "Account Name",
  "domain": "account-domain",
  "plan": "basic|pro|enterprise",
  "status": "active|suspended|cancelled",
  "settings": {
    "features": ["feature1", "feature2"],
    "limits": {
      "users": 100,
      "storage": "10GB",
      "api_calls": 10000
    }
  },
  "billing": {
    "cycle": "monthly|yearly",
    "nextBilling": "2024-02-01T00:00:00Z"
  },
  "createdAt": "2024-01-01T00:00:00Z",
  "updatedAt": "2024-01-01T00:00:00Z"
}

Suits Collection

{
  "_id": "ObjectId",
  "name": "Suit Name",
  "accountId": "account_id",
  "type": "mobile|web|hybrid",
  "platform": "ios|android|web",
  "status": "active|inactive|maintenance",
  "config": {
    "parse": {
      "appId": "parse_app_id",
      "serverURL": "parse_server_url"
    },
    "notifications": {
      "enabled": true,
      "channels": ["push", "email", "sms"]
    }
  },
  "analytics": {
    "users": 1000,
    "sessions": 5000,
    "revenue": 10000
  },
  "createdAt": "2024-01-01T00:00:00Z",
  "updatedAt": "2024-01-01T00:00:00Z"
}

🔄 Business Logic

User Authentication Flow

// Login Process
1. Validate credentials
2. Check account status
3. Generate JWT token
4. Update last login
5. Return user data and token

// Token Validation
1. Verify JWT signature
2. Check expiration
3. Validate user status
4. Check account status
5. Verify permissions

Multi-tenant Data Isolation

// Data Isolation Strategy
- Account-based isolation
- Suit-based isolation
- User-based isolation
- Row-level security
- Database-level isolation

Analytics Processing

// Data Collection
1. Collect user events
2. Process in real-time
3. Store in analytics database
4. Generate aggregations
5. Update dashboards

// Metrics Calculation
- User engagement
- Revenue tracking
- Performance metrics
- Custom KPIs

📈 Performance & Scaling

Caching Strategy

// Redis Caching
- User sessions
- API responses
- Analytics data
- Configuration data
- Rate limiting

// Cache Invalidation
- Time-based expiration
- Event-based invalidation
- Manual invalidation

Database Optimization

// Indexes
- User email (unique)
- Account domain (unique)
- Suit accountId
- Analytics timestamps

// Query Optimization
- Aggregation pipelines
- Read replicas
- Connection pooling
- Query caching

Load Balancing

// Horizontal Scaling
- Multiple server instances
- Load balancer distribution
- Session sharing
- Database sharding

🔍 Monitoring & Logging

Health Checks

# Health Check Endpoint
GET /health

# Response Format
{
  "status": "healthy",
  "timestamp": "2024-01-01T00:00:00Z",
  "version": "1.0.0",
  "services": {
    "database": "connected",
    "redis": "connected",
    "parse_server": "connected"
  },
  "metrics": {
    "memory_usage": "512MB",
    "cpu_usage": "25%",
    "active_connections": 150
  }
}

Logging Configuration

// Log Levels
- ERROR: System errors and exceptions
- WARN: Warning conditions
- INFO: General information
- DEBUG: Detailed debugging information

// Log Format
{
  "timestamp": "2024-01-01T00:00:00Z",
  "level": "info",
  "message": "User logged in",
  "userId": "user_id",
  "accountId": "account_id",
      "ip": "client_ip_address",
  "userAgent": "Mozilla/5.0..."
}

Metrics Collection

// Prometheus Metrics
- HTTP request duration
- Database query duration
- Memory usage
- CPU usage
- Active connections
- Error rates

🚀 Deployment

Docker Configuration

# Dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

Docker Compose

# docker-compose.yml
version: '3.8'
services:
  appgain-server:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - MONGODB_URI=mongodb://mongo:27017/appgain
      - REDIS_HOST=redis
    depends_on:
      - mongo
      - redis
    networks:
      - appgain-net

  mongo:
    image: mongo:6.0
    volumes:
      - mongo-data:/data/db
    networks:
      - appgain-net

  redis:
    image: redis:7-alpine
    volumes:
      - redis-data:/data
    networks:
      - appgain-net

volumes:
  mongo-data:
  redis-data:

networks:
  appgain-net:
    driver: bridge

Environment Configuration

# Production Environment
NODE_ENV=production
PORT=3000
MONGODB_URI=mongodb://ovh-mongo-master:27017/appgain
REDIS_HOST=ovh-redis
JWT_SECRET=ask your direct manager for the access
SENTRY_DSN=ask your direct manager for the access

# Staging Environment
NODE_ENV=staging
PORT=3000
MONGODB_URI=mongodb://ovh-mongo-slave1:27017/appgain_staging
REDIS_HOST=ovh-redis
JWT_SECRET=ask your direct manager for the access
SENTRY_DSN=ask your direct manager for the access

🔧 Development

Local Development Setup

# Clone repository
git clone <repository>
cd appgain-server

# Install dependencies
npm install

# Environment setup
cp .env.example .env
# Edit .env with local configuration

# Start development server
npm run dev

# Run tests
npm test

# Run linting
npm run lint

API Testing

# Test authentication
curl -X POST http://localhost:3000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "password": "ask your direct manager for the access"}'

# Test protected endpoint
curl -X GET http://localhost:3000/api/users \
  -H "Authorization: Bearer <token>"

# Test health check
curl -X GET http://localhost:3000/health

🔒 Security

Input Validation

// Joi Schema Validation
const userSchema = Joi.object({
  email: Joi.string().email().required(),
  password: Joi.string().min(8).required(), // ask your direct manager for the access
  firstName: Joi.string().min(2).max(50).required(),
  lastName: Joi.string().min(2).max(50).required()
});

Rate Limiting

// Rate Limiting Configuration
const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP'
});

Data Encryption

// Password Hashing
const bcrypt = require('bcrypt');
const saltRounds = 12;

const hashedPassword = await bcrypt.hash(password, saltRounds);

// Data Encryption
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.scryptSync(password, 'salt', 32);

📞 Support & Resources

Documentation

Monitoring Tools

  • Sentry: Error tracking and performance monitoring
  • Prometheus: Metrics collection and alerting
  • Grafana: Dashboard visualization
  • Logs: Centralized logging system

Development Resources

  • GitHub Repository: Source code and issues
  • Postman Collection: API testing
  • Swagger Documentation: Interactive API docs
  • Development Environment: Docker setup

Last updated: January 2024

Ask Chehab GPT