Socket
Book a DemoInstallSign in
Socket

@diagramers/api

Package Overview
Dependencies
Maintainers
1
Versions
113
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@diagramers/api

Diagramers API - A comprehensive Node.js API template with TypeScript, Firebase Functions, and Socket.io

Source
npmnpm
Version
4.0.22
Version published
Weekly downloads
22
46.67%
Maintainers
1
Weekly downloads
ย 
Created
Source

Diagramers API

A comprehensive, modular, and extensible Node.js API framework built with TypeScript, featuring multi-provider authentication, plugin system, unified response handling, Swagger documentation, Socket.IO real-time communication, and MongoDB support.

๐Ÿš€ Features

Core Features

  • Modular Architecture - Clean separation of concerns with modules, plugins, and shared components
  • Multi-Provider Authentication - Internal, Firebase, OAuth, SMS OTP, Email OTP
  • Unified Response Format - Consistent API responses using the Result model
  • Swagger Documentation - Auto-generated API documentation
  • Database Seeding - Comprehensive seeding system with environment-specific data
  • Plugin System - Extensible plugin architecture for custom functionality
  • Environment Management - Multi-environment configuration with .env support
  • Audit Logging - Pluggable audit system supporting multiple backends
  • Socket.IO Integration - Real-time communication with event handling
  • Auto Database Creation - Automatically creates collections and indexes on startup
  • CLI Integration - Full CLI support for module, table, and endpoint generation
  • Odoo ERP Integration - Complete CRM, Sales, and Inventory management through RESTful API

Database Support

  • MongoDB - Primary database with Mongoose ODM
  • SQL Databases - MySQL, PostgreSQL, SQLite, MariaDB (configurable)
  • Connection Pooling - Optimized database connections
  • Migration Support - Database schema management
  • Auto-Collection Creation - Creates collections and indexes automatically
  • Automatic Seeding - Generated tables include sample data and seeding

Authentication & Security

  • JWT Tokens - Secure token-based authentication
  • Role-Based Access Control - Granular permission system
  • Rate Limiting - Built-in request throttling
  • CORS Support - Configurable cross-origin requests
  • Helmet Security - Security headers and protection

Real-Time Communication

  • Socket.IO Server - WebSocket support with event handling
  • Room Management - Group-based messaging
  • Event Registration - Custom event handlers
  • Connection Management - Client tracking and management

ERP Integration

  • Odoo Integration - Complete CRM, Sales, and Inventory management
  • Customer Management - CRUD operations for customers/partners
  • Lead Management - Create, read, update leads and opportunities
  • Product Management - Product catalog and inventory access
  • Sales Management - Order tracking and invoice management
  • Bidirectional Sync - Real-time data synchronization with Odoo

๐Ÿ“ฆ Installation

# Install CLI globally
npm install -g @diagramers/cli

# Create new API project
diagramers init api my-new-api
cd my-new-api

# Install dependencies
npm install

# Start development
npm start

Option 2: Install API Package Only

npm install @diagramers/api

๐Ÿš€ Quick Start

1. Project Setup

# Create new project
diagramers init api my-ecommerce-api
cd my-ecommerce-api

# Set up environment
cp .env.example .env
# Edit .env with your configuration

# Install dependencies
npm install

2. Generate Your First Module

# Create products module with CRUD operations
diagramers extend --module products --crud

# Add categories table to products module
diagramers extend --table products:categories --fields name,description,slug

# Add products table to products module
diagramers extend --table products:products --fields name,price,description,category_id

# Create relationship between categories and products
diagramers extend --relation products:category-product:one-to-many

3. Add Custom Endpoints

# Add search endpoint
diagramers extend --endpoint products:search --method GET --description "Search products"

# Add featured products endpoint
diagramers extend --endpoint products:featured --method GET --description "Get featured products"

4. Run the Application

# Seed the database
npm run seed

# Start development server
npm start

Your API will be available at http://localhost:3000 with:

  • API Documentation: http://localhost:3000/api-docs
  • Health Check: http://localhost:3000/health
  • Generated Endpoints: http://localhost:3000/api/products/*

๐Ÿ› ๏ธ CLI Commands

Module Management

# Generate module with CRUD operations
diagramers extend --module products --crud

# Generate module with custom fields
diagramers extend --module users --fields email,username,role --crud

Table Generation

# Add table to existing module
diagramers extend --table products:categories --fields name,description,slug

# Add table with various field types
diagramers extend --table users:profiles --fields bio,avatar,birth_date,is_verified

Endpoint Generation

# Add GET endpoint
diagramers extend --endpoint products:search --method GET

# Add POST endpoint with custom path
diagramers extend --endpoint users:reset-password --method POST --path /reset-password

Relation Generation

# One-to-many relation (default)
diagramers extend --relation products:category-product

# One-to-one relation
diagramers extend --relation users:user-profile:one-to-one

# Many-to-many relation
diagramers extend --relation products:product-tag:many-to-many

Database Operations

# Run database seeding
npm run seed

# Reset and reseed database
npm run seed --reset

๐Ÿ“ Project Structure

my-api-project/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ modules/                    # Feature modules
โ”‚   โ”‚   โ”œโ”€โ”€ products/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ controllers/        # HTTP request handlers
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ entities/           # TypeScript interfaces
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ schemas/            # Database schemas
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ services/           # Business logic
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ routes/             # API routes
โ”‚   โ”‚   โ””โ”€โ”€ users/
โ”‚   โ”œโ”€โ”€ core/                       # Core functionality
โ”‚   โ”‚   โ”œโ”€โ”€ app.ts                  # Application setup
โ”‚   โ”‚   โ”œโ”€โ”€ config/                 # Configuration management
โ”‚   โ”‚   โ”œโ”€โ”€ database/               # Database connection & seeding
โ”‚   โ”‚   โ”œโ”€โ”€ logging/                # Logging system
โ”‚   โ”‚   โ””โ”€โ”€ server/                 # Server management
โ”‚   โ”œโ”€โ”€ shared/                     # Shared utilities
โ”‚   โ”‚   โ”œโ”€โ”€ constants/              # Application constants
โ”‚   โ”‚   โ”œโ”€โ”€ types/                  # TypeScript types
โ”‚   โ”‚   โ””โ”€โ”€ utils/                  # Utility functions
โ”‚   โ””โ”€โ”€ main.ts                     # Application entry point
โ”œโ”€โ”€ scripts/                        # Build and utility scripts
โ”œโ”€โ”€ certs/                          # SSL certificates
โ”œโ”€โ”€ .env.example                    # Environment template
โ””โ”€โ”€ package.json

๐Ÿ”ง Configuration

Environment Variables

# Database Configuration
DATABASE_URL=mongodb://localhost:27017/my-api
DATABASE_NAME=my-api

# Server Configuration
PORT=3000
NODE_ENV=development

# Authentication
JWT_SECRET=your-secret-key
JWT_EXPIRATION=24h

# Firebase (optional)
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_PRIVATE_KEY=your-private-key
FIREBASE_CLIENT_EMAIL=your-client-email

# Third-party Services
TWILIO_ACCOUNT_SID=your-twilio-sid
TWILIO_AUTH_TOKEN=your-twilio-token
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-email-password

# Odoo ERP Integration
ODOO_ENABLED=true
ODOO_URL=your-odoo-server.com
ODOO_PORT=8069
ODOO_PROTOCOL=http
ODOO_USERNAME=your-odoo-username
ODOO_PASSWORD=your-odoo-password
ODOO_DATABASE=your-odoo-database
ODOO_COMPANY=1

Database Configuration

// src/core/config/index.ts
export const config = {
  database: {
    url: process.env.DATABASE_URL || 'mongodb://localhost:27017/my-api',
    name: process.env.DATABASE_NAME || 'my-api',
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }
  },
  server: {
    port: parseInt(process.env.PORT || '3000'),
    cors: {
      origin: process.env.CORS_ORIGIN || '*',
      credentials: true
    }
  }
};

๐Ÿ“ง Email System

The Diagramers API provides a comprehensive email system with multi-provider support, template management, and flexible configuration. The email system is designed to handle transactional emails, notifications, and marketing communications with high deliverability and reliability.

๐ŸŽฏ Supported Email Providers

SMTP Providers

  • Gmail - Google's SMTP service with OAuth2 support
  • Outlook/Hotmail - Microsoft's email service
  • Yahoo Mail - Yahoo's SMTP service
  • Custom SMTP - Any SMTP server (Office 365, Exchange, etc.)

Cloud Email Services

  • SendGrid - High-deliverability cloud email service
  • AWS SES - Amazon's scalable email service
  • Mailgun - Developer-focused email API
  • Postmark - Transactional email service
  • Resend - Modern email API for developers
  • Brevo (Sendinblue) - All-in-one email marketing platform

Enterprise Email

  • Microsoft Exchange - Enterprise email server
  • Google Workspace - Business email and collaboration
  • Custom Enterprise - On-premise email solutions

๐Ÿš€ Quick Email Setup

1. Configure Email Provider

# In your .env file
EMAIL_ENABLED=true
EMAIL_DEFAULT_PROVIDER=smtp
EMAIL_SMTP_HOST=smtp.gmail.com
EMAIL_SMTP_PORT=587
EMAIL_SMTP_SECURE=false
EMAIL_SMTP_USER=your-email@gmail.com
EMAIL_SMTP_PASS=your-app-password
EMAIL_FROM_NAME=Your App Name
EMAIL_FROM_EMAIL=noreply@yourapp.com

2. Send Your First Email

# Using the email API endpoint
curl -X POST http://localhost:3000/api/email/send \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "system",
    "code": "gmail",
    "to": "user@example.com",
    "subject": "Welcome to Our App!",
    "body": "<h1>Welcome!</h1><p>Thank you for joining our platform.</p>"
  }'

3. Manage Email Configurations

# List all email configurations
GET /api/email/configs

# Create new email configuration
POST /api/email/configs
{
  "provider": "smtp",
  "code": "gmail",
  "credentials": {
    "service": "gmail",
    "auth": {
      "user": "your-email@gmail.com",
      "pass": "your-app-password"
    }
  },
  "fromName": "Your App",
  "fromEmail": "your-email@gmail.com"
}

# Update email configuration
PUT /api/email/configs/{id}
{
  "fromName": "Updated App Name"
}

# Delete email configuration
DELETE /api/email/configs/{id}

๐Ÿ“‹ Email API Endpoints

Send Email

POST /api/email/send
{
  "userId": "system",
  "code": "gmail",
  "to": "recipient@example.com",
  "subject": "Email Subject",
  "body": "<h1>Email Content</h1><p>This is the email body.</p>"
}

Email Configuration Management

# Get all configurations
GET /api/email/configs

# Get specific configuration
GET /api/email/configs/{id}

# Create configuration
POST /api/email/configs
{
  "provider": "smtp",
  "code": "gmail",
  "credentials": {
    "service": "gmail",
    "auth": {
      "user": "your-email@gmail.com",
      "pass": "your-app-password"
    }
  },
  "fromName": "Your App",
  "fromEmail": "your-email@gmail.com"
}

# Update configuration
PUT /api/email/configs/{id}
{
  "fromName": "Updated Name"
}

# Delete configuration
DELETE /api/email/configs/{id}

๐Ÿ”ง Email Configuration

Gmail SMTP Setup

  • Enable 2-factor authentication on your Google account
  • Generate an App Password:
    • Go to Google Account settings
    • Security โ†’ 2-Step Verification โ†’ App passwords
    • Generate password for "Mail"
  • Configure environment variables:
EMAIL_SMTP_HOST=smtp.gmail.com
EMAIL_SMTP_PORT=587
EMAIL_SMTP_SECURE=false
EMAIL_SMTP_USER=your-email@gmail.com
EMAIL_SMTP_PASS=your-16-digit-app-password

SendGrid Setup

  • Create SendGrid account
  • Get API key from SendGrid dashboard
  • Configure environment variables:
EMAIL_PROVIDER=sendgrid
EMAIL_SENDGRID_API_KEY=your-sendgrid-api-key
EMAIL_FROM_EMAIL=verified-sender@yourdomain.com

AWS SES Setup

  • Create AWS account and SES service
  • Verify your email domain or email address
  • Get AWS credentials
  • Configure environment variables:
EMAIL_PROVIDER=ses
EMAIL_AWS_REGION=us-east-1
EMAIL_AWS_ACCESS_KEY_ID=your-access-key
EMAIL_AWS_SECRET_ACCESS_KEY=your-secret-key
EMAIL_FROM_EMAIL=verified@yourdomain.com

๐ŸŽจ Email Templates

HTML Email Template

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{subject}}</title>
</head>
<body>
    <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
        <h1 style="color: #333;">{{title}}</h1>
        <p style="color: #666;">{{content}}</p>
        <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;">
            <p style="font-size: 12px; color: #999;">
                This email was sent from {{appName}}
            </p>
        </div>
    </div>
</body>
</html>

Template Usage

// In your email service
const emailData = {
  to: 'user@example.com',
  subject: 'Welcome to Our Platform',
  body: `
    <h1>Welcome!</h1>
    <p>Thank you for joining our platform.</p>
    <a href="${verificationLink}">Verify your email</a>
  `
};

await emailService.sendEmail('system', 'gmail', emailData);

๐Ÿ”Œ Email Provider Integration

Custom Email Provider

// src/modules/email/providers/custom-email-provider.ts
import { BaseEmailProvider } from './base-email-provider';

export class CustomEmailProvider extends BaseEmailProvider {
  async send(options: any): Promise<void> {
    // Your custom email sending logic
    const { to, subject, body, from } = options;
    
    // Implement your email sending here
    // Example: API call to your email service
  }
}

Email Service Usage

// In your application code
import { EmailService } from './modules/email/services/email.service';

const emailService = new EmailService();

// Send email using configured provider
await emailService.sendEmail(
  'system',           // userId
  'gmail',           // provider code
  'user@example.com', // to
  'Welcome!',        // subject
  '<h1>Welcome!</h1>' // body
);

๐Ÿ“Š Email Monitoring & Analytics

Delivery Tracking

  • Send Status - Track email delivery status
  • Bounce Handling - Automatic bounce processing
  • Spam Reports - Monitor spam complaints
  • Open Tracking - Track email opens (if supported)

Performance Metrics

  • Delivery Rate - Percentage of emails delivered
  • Open Rate - Percentage of emails opened
  • Click Rate - Percentage of links clicked
  • Bounce Rate - Percentage of emails bounced

๐Ÿ›ก๏ธ Email Security & Best Practices

Security Features

  • SPF/DKIM - Email authentication protocols
  • DMARC - Domain-based message authentication
  • Rate Limiting - Prevent email abuse
  • Content Filtering - Spam and malware protection

Best Practices

  • Use App Passwords - For Gmail and other providers
  • Verify Sender Domains - For cloud email services
  • Monitor Bounce Rates - Keep lists clean
  • Respect Unsubscribes - Honor opt-out requests
  • Test Before Sending - Use test environments

๐Ÿ” Troubleshooting Email Issues

Common Problems

  • Authentication Failed - Check credentials and app passwords
  • Connection Timeout - Verify SMTP settings and firewall
  • Email Not Delivered - Check spam filters and sender reputation
  • Template Errors - Validate HTML and template syntax

Debug Mode

# Enable email debugging
EMAIL_DEBUG=true
LOG_LEVEL=debug

๐Ÿ“š Complete Email Configuration

For a complete list of all email environment variables, see the .env.example file which includes:

  • 50+ email configuration options
  • Provider-specific settings
  • Template configuration
  • Security settings
  • Monitoring options

๐Ÿ‘ฅ User Management

The Diagramers API provides comprehensive user management capabilities with role-based access control, profile management, and flexible user data handling. The user system is designed to scale from simple applications to complex enterprise solutions.

๐ŸŽฏ User Management Features

Core User Features

  • User Registration - Email/password registration with validation
  • Profile Management - Complete user profile system
  • Role-Based Access Control - Granular permission system
  • Account Verification - Email and phone verification
  • Password Management - Secure password reset and change
  • Account Status - Active, inactive, suspended, banned states

Advanced User Features

  • Multi-Provider Profiles - Link accounts from different providers
  • Social Login Integration - OAuth provider account linking
  • User Preferences - Customizable user settings
  • Activity Tracking - User activity and session management
  • Audit Logging - Complete user action history
  • Data Export - GDPR-compliant data export

๐Ÿš€ Quick User Setup

1. User Registration

# Register new user
POST /api/auth/register
{
  "email": "user@example.com",
  "password": "SecurePass123!",
  "firstName": "John",
  "lastName": "Doe",
  "username": "johndoe"
}

2. User Profile Management

# Get user profile
GET /api/users/profile
Authorization: Bearer your-jwt-token

# Update user profile
PUT /api/users/profile
Authorization: Bearer your-jwt-token
{
  "firstName": "John",
  "lastName": "Smith",
  "bio": "Software developer",
  "avatar": "https://example.com/avatar.jpg"
}

3. User Administration

# Get all users (admin only)
GET /api/users
Authorization: Bearer admin-jwt-token

# Get specific user
GET /api/users/{userId}
Authorization: Bearer admin-jwt-token

# Update user (admin only)
PUT /api/users/{userId}
Authorization: Bearer admin-jwt-token
{
  "role": "moderator",
  "isActive": true
}

# Delete user (admin only)
DELETE /api/users/{userId}
Authorization: Bearer admin-jwt-token

๐Ÿ“‹ User API Endpoints

User Registration & Authentication

# User registration
POST /api/auth/register
{
  "email": "user@example.com",
  "password": "SecurePass123!",
  "firstName": "John",
  "lastName": "Doe"
}

# User login
POST /api/auth/login
{
  "email": "user@example.com",
  "password": "SecurePass123!"
}

# Refresh token
POST /api/auth/refresh
{
  "refreshToken": "your-refresh-token"
}

# Logout
POST /api/auth/logout
Authorization: Bearer your-jwt-token

User Profile Management

# Get own profile
GET /api/users/profile
Authorization: Bearer your-jwt-token

# Update own profile
PUT /api/users/profile
Authorization: Bearer your-jwt-token
{
  "firstName": "John",
  "lastName": "Smith",
  "bio": "Software developer",
  "avatar": "https://example.com/avatar.jpg",
  "preferences": {
    "theme": "dark",
    "notifications": true
  }
}

# Upload avatar
POST /api/users/avatar
Authorization: Bearer your-jwt-token
Content-Type: multipart/form-data

User Administration (Admin Only)

# List all users
GET /api/users?page=1&limit=10&search=john&role=user

# Get user by ID
GET /api/users/{userId}

# Create user (admin)
POST /api/users
{
  "email": "newuser@example.com",
  "password": "SecurePass123!",
  "firstName": "Jane",
  "lastName": "Doe",
  "role": "user"
}

# Update user (admin)
PUT /api/users/{userId}
{
  "role": "moderator",
  "isActive": true,
  "permissions": ["read:all", "write:own"]
}

# Delete user (admin)
DELETE /api/users/{userId}

# Bulk operations
POST /api/users/bulk
{
  "action": "activate",
  "userIds": ["user1", "user2", "user3"]
}

User Verification & Security

# Send email verification
POST /api/auth/send-verification
{
  "email": "user@example.com"
}

# Verify email
POST /api/auth/verify-email
{
  "email": "user@example.com",
  "code": "123456"
}

# Send phone verification
POST /api/auth/sms/send
{
  "phone": "+1234567890"
}

# Verify phone
POST /api/auth/sms/verify
{
  "phone": "+1234567890",
  "code": "123456"
}

# Change password
POST /api/auth/change-password
Authorization: Bearer your-jwt-token
{
  "currentPassword": "OldPassword123!",
  "newPassword": "NewSecurePass123!"
}

# Forgot password
POST /api/auth/forgot-password
{
  "email": "user@example.com"
}

# Reset password
POST /api/auth/reset-password
{
  "email": "user@example.com",
  "code": "123456",
  "newPassword": "NewSecurePass123!"
}

๐Ÿ”ง User Configuration

User Registration Settings

# Enable/disable registration
AUTH_ALLOW_REGISTRATION=true

# Require email verification
AUTH_REQUIRE_EMAIL_VERIFICATION=true

# Require phone verification
AUTH_REQUIRE_PHONE_VERIFICATION=false

# Allow username registration
AUTH_ALLOW_USERNAME_REGISTRATION=true

# Minimum password length
AUTH_PASSWORD_MIN_LENGTH=8

User Profile Settings

# Enable profile features
USER_PROFILE_ENABLED=true

# Allow avatar uploads
USER_AVATAR_ENABLED=true

# Maximum avatar size (MB)
USER_AVATAR_MAX_SIZE=5

# Allowed avatar formats
USER_AVATAR_FORMATS=jpg,jpeg,png,gif

# Enable user preferences
USER_PREFERENCES_ENABLED=true

User Roles & Permissions

# Default user role
AUTH_DEFAULT_ROLE=user

# Available roles
AUTH_ROLES=user,moderator,admin

# Role hierarchy
AUTH_ROLE_HIERARCHY=user<moderator<admin

# Enable permission system
AUTH_PERMISSIONS_ENABLED=true

๐ŸŽจ User Data Models

User Schema

interface User {
  _id: string;
  email: string;
  username?: string;
  firstName: string;
  lastName: string;
  password: string;
  role: string;
  isActive: boolean;
  emailVerified: boolean;
  phoneVerified: boolean;
  avatar?: string;
  bio?: string;
  preferences?: UserPreferences;
  lastLogin?: Date;
  createdAt: Date;
  updatedAt: Date;
}

interface UserPreferences {
  theme: 'light' | 'dark';
  notifications: boolean;
  language: string;
  timezone: string;
  [key: string]: any;
}

User Profile Schema

interface UserProfile {
  _id: string;
  userId: string;
  bio?: string;
  avatar?: string;
  socialLinks?: {
    twitter?: string;
    linkedin?: string;
    github?: string;
  };
  location?: string;
  website?: string;
  birthDate?: Date;
  preferences: UserPreferences;
  createdAt: Date;
  updatedAt: Date;
}

๐Ÿ”Œ User Service Integration

User Service Usage

import { UserService } from './modules/users/services/user.service';

const userService = new UserService();

// Create user
const user = await userService.create({
  email: 'user@example.com',
  password: 'SecurePass123!',
  firstName: 'John',
  lastName: 'Doe'
});

// Get user by ID
const user = await userService.getById('user-id');

// Update user
const updatedUser = await userService.update('user-id', {
  firstName: 'John',
  lastName: 'Smith'
});

// Delete user
await userService.delete('user-id');

// Search users
const users = await userService.search({
  query: 'john',
  role: 'user',
  isActive: true,
  page: 1,
  limit: 10
});

User Authentication Integration

import { AuthService } from './modules/auth/services/auth.service';

const authService = new AuthService();

// Register user
const result = await authService.register({
  email: 'user@example.com',
  password: 'SecurePass123!',
  firstName: 'John',
  lastName: 'Doe'
});

// Login user
const loginResult = await authService.login({
  email: 'user@example.com',
  password: 'SecurePass123!'
});

// Verify email
await authService.verifyEmail('user@example.com', '123456');

// Change password
await authService.changePassword('user-id', 'OldPass123!', 'NewPass123!');

๐Ÿ“Š User Analytics & Reporting

User Statistics

# Get user statistics
GET /api/users/stats
Authorization: Bearer admin-jwt-token

# Response includes:
{
  "totalUsers": 1250,
  "activeUsers": 1180,
  "newUsersThisMonth": 45,
  "usersByRole": {
    "user": 1100,
    "moderator": 120,
    "admin": 30
  },
  "verificationStats": {
    "emailVerified": 1150,
    "phoneVerified": 800
  }
}

User Activity Tracking

# Get user activity
GET /api/users/{userId}/activity
Authorization: Bearer admin-jwt-token

# Get user sessions
GET /api/users/{userId}/sessions
Authorization: Bearer admin-jwt-token

๐Ÿ›ก๏ธ User Security & Privacy

Data Protection

  • Password Hashing - bcrypt with configurable rounds
  • Data Encryption - Sensitive data encryption at rest
  • GDPR Compliance - Data export and deletion
  • Privacy Controls - User privacy settings
  • Audit Logging - Complete user action history

Account Security

  • Account Lockout - Automatic protection against brute force
  • Session Management - Secure session handling
  • Device Tracking - Track and manage user devices
  • Suspicious Activity - Detect and alert on suspicious behavior
  • Two-Factor Authentication - Enhanced account security

๐Ÿ” User Troubleshooting

Common User Issues

  • Registration Fails - Check email format and password requirements
  • Login Issues - Verify credentials and account status
  • Email Not Received - Check spam folder and email configuration
  • Profile Update Fails - Validate input data and permissions
  • Avatar Upload Issues - Check file size and format restrictions

Admin Troubleshooting

  • User Search Issues - Verify search parameters and permissions
  • Bulk Operations Fail - Check user IDs and operation permissions
  • Statistics Not Loading - Verify database connection and permissions

๐Ÿ“š Complete User Configuration

For a complete list of all user management environment variables, see the .env.example file which includes:

  • 100+ user configuration options
  • Role and permission settings
  • Profile customization options
  • Security and privacy settings
  • Integration configurations

๐Ÿ” Authentication

The Diagramers API provides comprehensive authentication support with multiple providers and security features. Developers can enable any combination of authentication methods by simply providing the required configuration keys.

๐ŸŽฏ Supported Authentication Providers

Internal Authentication (Database-based)

  • Username/password with JWT tokens
  • User registration and email verification
  • Password reset functionality
  • Configurable password policies
  • Account lockout protection

Firebase Authentication

  • Google Firebase integration
  • Firebase Admin SDK support
  • Custom token generation
  • User management through Firebase console

OAuth Providers

Complete OAuth 2.0 support for major platforms:

  • Google - Gmail, Google Workspace integration
  • GitHub - Developer-focused authentication
  • Facebook - Social media integration
  • Twitter - Social platform access
  • LinkedIn - Professional network integration
  • Microsoft - Office 365, Azure AD integration
  • Apple - iOS and macOS integration
  • Discord - Gaming community integration
  • Spotify - Music platform integration
  • Twitch - Streaming platform integration

SMS Authentication

Multi-provider SMS support:

  • Twilio - Global SMS delivery
  • AWS SNS - Amazon's SMS service
  • Vonage (Nexmo) - Enterprise SMS
  • MessageBird - International SMS
  • Custom SMS Provider - Bring your own SMS API

Email Authentication

Multi-provider email support:

  • Nodemailer - SMTP-based email
  • SendGrid - Cloud email service
  • AWS SES - Amazon's email service
  • Mailgun - Developer-focused email
  • Postmark - Transactional email
  • Custom Email Provider - Bring your own email API

Enterprise Authentication

  • LDAP - Active Directory integration
  • SAML - Single Sign-On (SSO)
  • OAuth2 Generic - Custom OAuth2 providers
  • OpenID Connect - Modern SSO standard

Modern Authentication

  • WebAuthn (FIDO2) - Passwordless authentication
  • Biometric Authentication - Fingerprint, Face ID support
  • Hardware Security Keys - YubiKey, etc.

Social Media Authentication

Extended social platform support:

  • Instagram - Photo sharing platform
  • TikTok - Video sharing platform
  • Snapchat - Multimedia messaging
  • Pinterest - Visual discovery platform
  • Reddit - Community platform
  • Slack - Team collaboration
  • Zoom - Video conferencing
  • Dropbox - Cloud storage
  • Bitbucket - Code repository
  • GitLab - DevOps platform

๐Ÿš€ Quick Authentication Setup

1. Enable Internal Authentication

# In your .env file
AUTH_INTERNAL_ENABLED=true
AUTH_INTERNAL_ALLOW_REGISTRATION=true
AUTH_INTERNAL_REQUIRE_EMAIL_VERIFICATION=true
JWT_SECRET=your-super-secret-jwt-key

2. Enable Google OAuth

# In your .env file
AUTH_OAUTH_ENABLED=true
AUTH_OAUTH_GOOGLE_ENABLED=true
AUTH_OAUTH_GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
AUTH_OAUTH_GOOGLE_CLIENT_SECRET=your-google-client-secret
AUTH_OAUTH_GOOGLE_CALLBACK_URL=http://localhost:3000/api/auth/oauth/google/callback

3. Enable SMS Authentication

# In your .env file
AUTH_SMS_ENABLED=true
AUTH_SMS_PROVIDER=twilio
AUTH_SMS_TWILIO_ACCOUNT_SID=your-twilio-account-sid
AUTH_SMS_TWILIO_AUTH_TOKEN=your-twilio-auth-token
AUTH_SMS_TWILIO_FROM_NUMBER=+1234567890

๐Ÿ“‹ Authentication Endpoints

Basic Authentication

# User Registration
POST /api/auth/register
{
  "email": "user@example.com",
  "password": "SecurePass123!",
  "name": "John Doe"
}

# User Login
POST /api/auth/login
{
  "email": "user@example.com",
  "password": "SecurePass123!",
  "provider": "internal"
}

# Refresh Token
POST /api/auth/refresh
{
  "refreshToken": "your-refresh-token"
}

# Logout
POST /api/auth/logout
Authorization: Bearer your-jwt-token

Email Verification

# Send Verification Code
POST /api/auth/send-verification
{
  "email": "user@example.com"
}

# Verify Email
POST /api/auth/verify-email
{
  "email": "user@example.com",
  "code": "123456"
}

Password Management

# Forgot Password
POST /api/auth/forgot-password
{
  "email": "user@example.com"
}

# Reset Password
POST /api/auth/reset-password
{
  "email": "user@example.com",
  "code": "123456",
  "newPassword": "NewSecurePass123!"
}

# Change Password
POST /api/auth/change-password
Authorization: Bearer your-jwt-token
{
  "currentPassword": "OldPassword123!",
  "newPassword": "NewSecurePass123!"
}

SMS Authentication

# Send SMS Code
POST /api/auth/sms/send
{
  "phone": "+1234567890"
}

# Verify SMS Code
POST /api/auth/sms/verify
{
  "phone": "+1234567890",
  "code": "123456"
}

OAuth Authentication

# Get OAuth Authorization URL
GET /api/auth/oauth/google/url
# Returns: { "authUrl": "https://accounts.google.com/oauth/authorize?..." }

# OAuth Callback (handled automatically)
GET /api/auth/oauth/google/callback?code=auth-code&state=state-value

WebAuthn (FIDO2)

# Begin WebAuthn Registration
POST /api/auth/webauthn/register/begin
Authorization: Bearer your-jwt-token

# Finish WebAuthn Registration
POST /api/auth/webauthn/register/finish
Authorization: Bearer your-jwt-token
{
  "credential": { /* WebAuthn credential object */ }
}

# Begin WebAuthn Authentication
POST /api/auth/webauthn/login/begin
{
  "email": "user@example.com"
}

# Finish WebAuthn Authentication
POST /api/auth/webauthn/login/finish
{
  "email": "user@example.com",
  "credential": { /* WebAuthn credential object */ }
}

User Profile & Token Management

# Get User Profile
GET /api/auth/profile
Authorization: Bearer your-jwt-token

# Validate Token
GET /api/auth/validate
Authorization: Bearer your-jwt-token

๐Ÿ”ง Authentication Configuration

Password Policy Configuration

# Configure password requirements
AUTH_PASSWORD_MIN_LENGTH=8
AUTH_PASSWORD_REQUIRE_UPPERCASE=true
AUTH_PASSWORD_REQUIRE_LOWERCASE=true
AUTH_PASSWORD_REQUIRE_NUMBERS=true
AUTH_PASSWORD_REQUIRE_SPECIAL_CHARS=true

Security Settings

# General auth settings
AUTH_DEFAULT_PROVIDER=internal
AUTH_ALLOW_MULTIPLE_PROVIDERS=true
AUTH_SESSION_TIMEOUT=3600
AUTH_MAX_LOGIN_ATTEMPTS=5
AUTH_LOCKOUT_DURATION=900

JWT Configuration

# JWT token settings
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
JWT_EXPIRES_IN=1h
REFRESH_TOKEN_EXPIRES_IN=7d

๐Ÿ›ก๏ธ Security Features

Built-in Security

  • JWT Token Management - Secure token-based authentication
  • Refresh Token Rotation - Enhanced security for long-lived sessions
  • Rate Limiting - Prevent brute force attacks
  • Account Lockout - Automatic account protection
  • Password Hashing - bcrypt with configurable rounds
  • CORS Protection - Configurable cross-origin requests
  • Helmet Security - Security headers and protection

Advanced Security

  • Multi-Factor Authentication - SMS, Email, WebAuthn
  • Session Management - Secure session handling
  • Token Blacklisting - Revoke compromised tokens
  • Audit Logging - Track authentication events
  • IP Whitelisting - Restrict access by IP
  • Device Fingerprinting - Track user devices

๐Ÿ”Œ Provider-Specific Setup

Firebase Setup

  • Create a Firebase project
  • Enable Authentication in Firebase console
  • Download service account key
  • Configure environment variables:
AUTH_FIREBASE_ENABLED=true
AUTH_FIREBASE_PROJECT_ID=your-project-id
AUTH_FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
AUTH_FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@your-project.iam.gserviceaccount.com

Google OAuth Setup

  • Go to Google Cloud Console
  • Create OAuth 2.0 credentials
  • Configure authorized redirect URIs
  • Set environment variables:
AUTH_OAUTH_GOOGLE_ENABLED=true
AUTH_OAUTH_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
AUTH_OAUTH_GOOGLE_CLIENT_SECRET=your-client-secret
AUTH_OAUTH_GOOGLE_CALLBACK_URL=http://localhost:3000/api/auth/oauth/google/callback

Twilio SMS Setup

  • Create Twilio account
  • Get Account SID and Auth Token
  • Purchase phone number
  • Configure environment variables:
AUTH_SMS_ENABLED=true
AUTH_SMS_PROVIDER=twilio
AUTH_SMS_TWILIO_ACCOUNT_SID=your-account-sid
AUTH_SMS_TWILIO_AUTH_TOKEN=your-auth-token
AUTH_SMS_TWILIO_FROM_NUMBER=+1234567890

๐ŸŽจ Customization

Custom Authentication Provider

// src/modules/auth/providers/custom-auth-provider.ts
import { BaseAuthProvider } from './base-auth-provider';

export class CustomAuthProvider extends BaseAuthProvider {
  async authenticate(credentials: any): Promise<any> {
    // Your custom authentication logic
  }
}

Custom Middleware

// src/middleware/auth-middleware.ts
export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
  // Your custom authentication middleware
};

๐Ÿ“š Complete Environment Configuration

For a complete list of all authentication environment variables, see the .env.example file which includes:

  • 200+ authentication configuration options
  • Detailed comments for each setting
  • Example values for all providers
  • Security best practices
  • Development and production configurations

๐Ÿ” Debugging Authentication

Enable Debug Logging

LOG_LEVEL=debug
DEBUG=auth:*

Common Issues

  • Invalid JWT Secret - Ensure JWT_SECRET is set and consistent
  • OAuth Callback Mismatch - Check callback URLs in provider settings
  • SMS/Email Not Sending - Verify provider credentials and quotas
  • Token Expiration - Check JWT_EXPIRES_IN and refresh token logic

๐Ÿ“– API Documentation

All authentication endpoints are automatically documented with Swagger. Visit /api-docs to explore:

  • Interactive API testing
  • Request/response schemas
  • Authentication examples
  • Error codes and responses

๐Ÿ“Š Database Seeding

Automatic Seeding

All generated tables automatically include:

  • Sample Data - 3 realistic sample records
  • Seeder Integration - Automatic database seeding
  • Environment-Specific Data - Different data for dev/staging/prod

Seeding Commands

# Run seeding
npm run seed

# Reset and reseed
npm run seed --reset

# Force reseed (skip existing data check)
npm run seed --force

Custom Seed Data

// src/core/database/seeder.ts
const defaultData: SeedData = {
  products: [
    {
      name: 'Sample Product 1',
      price: 29.99,
      description: 'Description for sample product 1',
      category_id: 'category-id-1'
    }
  ],
  categories: [
    {
      name: 'Electronics',
      description: 'Electronic devices and gadgets',
      slug: 'electronics'
    }
  ]
};

๐Ÿ”Œ Plugin System

Available Plugins

  • Audit Plugin - Activity logging and tracking
  • Email Plugin - Email sending with templates
  • SMS Plugin - SMS notifications
  • File Upload Plugin - File management
  • Cache Plugin - Redis caching

Plugin Usage

// Enable plugins in main.ts
import { AuditPlugin } from './plugins/audit';
import { EmailPlugin } from './plugins/email';

const app = new Application();
app.use(new AuditPlugin());
app.use(new EmailPlugin());

๐Ÿ“ก Real-Time Communication

Socket.IO Integration

// Socket event handling
import { SocketManager } from './core/server/socket-manager';

const socketManager = new SocketManager(server);

// Handle custom events
socketManager.on('product:updated', (data) => {
  // Broadcast to all clients
  socketManager.broadcast('product:updated', data);
});

Client Usage

// Frontend connection
const socket = io('http://localhost:3000');

socket.on('product:updated', (product) => {
  console.log('Product updated:', product);
});

๐Ÿ“š API Documentation

Swagger Integration

  • Auto-generated docs at /api-docs
  • Interactive testing interface
  • Schema validation documentation
  • Authentication examples

Odoo ERP Integration

The Diagramers API includes comprehensive Odoo ERP integration with the following endpoints:

Connection Management

POST /api/odoo/connect          # Initialize Odoo connection
GET  /api/odoo/status           # Get connection status

Customer Management

GET    /api/odoo/customers      # Get all customers
GET    /api/odoo/customers/:id  # Get customer by ID
POST   /api/odoo/customers      # Create customer
PUT    /api/odoo/customers/:id  # Update customer

Lead Management

GET    /api/odoo/leads          # Get all leads
GET    /api/odoo/leads/:id      # Get lead by ID
POST   /api/odoo/leads          # Create lead
PUT    /api/odoo/leads/:id      # Update lead

Opportunity Management

GET    /api/odoo/opportunities  # Get all opportunities

Product Management

GET    /api/odoo/products       # Get all products

Sales Management

GET    /api/odoo/orders         # Get all orders
GET    /api/odoo/invoices       # Get all invoices

Usage Example

// Initialize Odoo connection
const response = await fetch('/api/odoo/connect', {
  method: 'POST'
});

// Get customers with filters
const customers = await fetch('/api/odoo/customers?limit=50&filters[is_company]=true');

// Create a new lead
const leadData = {
  name: 'New Sales Lead',
  partner_name: 'ABC Company',
  contact_name: 'John Doe',
  email_from: 'john@abc.com',
  phone: '+1234567890',
  type: 'lead',
  description: 'Interested in our product'
};

const newLead = await fetch('/api/odoo/leads', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(leadData)
});

For complete Odoo integration documentation, see ODOO_MODULE.md.

Custom Documentation

/**
 * @openapi
 * /api/products:
 *   get:
 *     summary: Get all products
 *     tags: [Products]
 *     responses:
 *       200:
 *         description: List of products
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/Product'
 */

๐Ÿงช Testing

Unit Tests

# Run tests
npm test

# Run with coverage
npm run test:coverage

# Run specific test file
npm test -- --testNamePattern="ProductService"

Integration Tests

# Run integration tests
npm run test:integration

# Test specific endpoint
npm run test:integration -- --grep "Products API"

๐Ÿš€ Deployment

Production Build

# Build for production
npm run build:prod

# Start production server
npm run start:prod

Docker Deployment

FROM node:18-alpine

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

COPY . .
RUN npm run build:prod

EXPOSE 3000
CMD ["npm", "run", "start:prod"]

Environment Setup

# Production environment
NODE_ENV=production
DATABASE_URL=mongodb://prod-server:27017/my-api
JWT_SECRET=secure-production-secret

๐Ÿ” Monitoring & Logging

Built-in Logging

import { logger } from './core/logging';

logger.info('Application started');
logger.error('Database connection failed', error);
logger.warn('Rate limit exceeded', { ip: req.ip });

Health Checks

# Health endpoint
GET /health

# Database health
GET /health/database

# Detailed system info
GET /health/system

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ“ž Support

Keywords

diagramers

FAQs

Package last updated on 11 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts