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
Option 1: Use CLI (Recommended)
npm install -g @diagramers/cli
diagramers init api my-new-api
cd my-new-api
npm install
npm start
Option 2: Install API Package Only
npm install @diagramers/api
๐ Quick Start
1. Project Setup
diagramers init api my-ecommerce-api
cd my-ecommerce-api
cp .env.example .env
npm install
2. Generate Your First Module
diagramers extend --module products --crud
diagramers extend --table products:categories --fields name,description,slug
diagramers extend --table products:products --fields name,price,description,category_id
diagramers extend --relation products:category-product:one-to-many
3. Add Custom Endpoints
diagramers extend --endpoint products:search --method GET --description "Search products"
diagramers extend --endpoint products:featured --method GET --description "Get featured products"
4. Run the Application
npm run seed
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
diagramers extend --module products --crud
diagramers extend --module users --fields email,username,role --crud
Table Generation
diagramers extend --table products:categories --fields name,description,slug
diagramers extend --table users:profiles --fields bio,avatar,birth_date,is_verified
Endpoint Generation
diagramers extend --endpoint products:search --method GET
diagramers extend --endpoint users:reset-password --method POST --path /reset-password
Relation Generation
diagramers extend --relation products:category-product
diagramers extend --relation users:user-profile:one-to-one
diagramers extend --relation products:product-tag:many-to-many
Database Operations
npm run seed
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
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
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
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
GET /api/email/configs
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"
}
PUT /api/email/configs/{id}
{
"fromName": "Updated App Name"
}
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 /api/email/configs
GET /api/email/configs/{id}
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"
}
PUT /api/email/configs/{id}
{
"fromName": "Updated Name"
}
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
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
import { BaseEmailProvider } from './base-email-provider';
export class CustomEmailProvider extends BaseEmailProvider {
async send(options: any): Promise<void> {
const { to, subject, body, from } = options;
}
}
Email Service Usage
import { EmailService } from './modules/email/services/email.service';
const emailService = new EmailService();
await emailService.sendEmail(
'system',
'gmail',
'user@example.com',
'Welcome!',
'<h1>Welcome!</h1>'
);
๐ 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
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
POST /api/auth/register
{
"email": "user@example.com",
"password": "SecurePass123!",
"firstName": "John",
"lastName": "Doe",
"username": "johndoe"
}
2. User Profile Management
GET /api/users/profile
Authorization: Bearer your-jwt-token
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 /api/users
Authorization: Bearer admin-jwt-token
GET /api/users/{userId}
Authorization: Bearer admin-jwt-token
PUT /api/users/{userId}
Authorization: Bearer admin-jwt-token
{
"role": "moderator",
"isActive": true
}
DELETE /api/users/{userId}
Authorization: Bearer admin-jwt-token
๐ User API Endpoints
User Registration & Authentication
POST /api/auth/register
{
"email": "user@example.com",
"password": "SecurePass123!",
"firstName": "John",
"lastName": "Doe"
}
POST /api/auth/login
{
"email": "user@example.com",
"password": "SecurePass123!"
}
POST /api/auth/refresh
{
"refreshToken": "your-refresh-token"
}
POST /api/auth/logout
Authorization: Bearer your-jwt-token
User Profile Management
GET /api/users/profile
Authorization: Bearer your-jwt-token
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
}
}
POST /api/users/avatar
Authorization: Bearer your-jwt-token
Content-Type: multipart/form-data
User Administration (Admin Only)
GET /api/users?page=1&limit=10&search=john&role=user
GET /api/users/{userId}
POST /api/users
{
"email": "newuser@example.com",
"password": "SecurePass123!",
"firstName": "Jane",
"lastName": "Doe",
"role": "user"
}
PUT /api/users/{userId}
{
"role": "moderator",
"isActive": true,
"permissions": ["read:all", "write:own"]
}
DELETE /api/users/{userId}
POST /api/users/bulk
{
"action": "activate",
"userIds": ["user1", "user2", "user3"]
}
User Verification & Security
POST /api/auth/send-verification
{
"email": "user@example.com"
}
POST /api/auth/verify-email
{
"email": "user@example.com",
"code": "123456"
}
POST /api/auth/sms/send
{
"phone": "+1234567890"
}
POST /api/auth/sms/verify
{
"phone": "+1234567890",
"code": "123456"
}
POST /api/auth/change-password
Authorization: Bearer your-jwt-token
{
"currentPassword": "OldPassword123!",
"newPassword": "NewSecurePass123!"
}
POST /api/auth/forgot-password
{
"email": "user@example.com"
}
POST /api/auth/reset-password
{
"email": "user@example.com",
"code": "123456",
"newPassword": "NewSecurePass123!"
}
๐ง User Configuration
User Registration Settings
AUTH_ALLOW_REGISTRATION=true
AUTH_REQUIRE_EMAIL_VERIFICATION=true
AUTH_REQUIRE_PHONE_VERIFICATION=false
AUTH_ALLOW_USERNAME_REGISTRATION=true
AUTH_PASSWORD_MIN_LENGTH=8
User Profile Settings
USER_PROFILE_ENABLED=true
USER_AVATAR_ENABLED=true
USER_AVATAR_MAX_SIZE=5
USER_AVATAR_FORMATS=jpg,jpeg,png,gif
USER_PREFERENCES_ENABLED=true
User Roles & Permissions
AUTH_DEFAULT_ROLE=user
AUTH_ROLES=user,moderator,admin
AUTH_ROLE_HIERARCHY=user<moderator<admin
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();
const user = await userService.create({
email: 'user@example.com',
password: 'SecurePass123!',
firstName: 'John',
lastName: 'Doe'
});
const user = await userService.getById('user-id');
const updatedUser = await userService.update('user-id', {
firstName: 'John',
lastName: 'Smith'
});
await userService.delete('user-id');
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();
const result = await authService.register({
email: 'user@example.com',
password: 'SecurePass123!',
firstName: 'John',
lastName: 'Doe'
});
const loginResult = await authService.login({
email: 'user@example.com',
password: 'SecurePass123!'
});
await authService.verifyEmail('user@example.com', '123456');
await authService.changePassword('user-id', 'OldPass123!', 'NewPass123!');
๐ User Analytics & Reporting
User Statistics
GET /api/users/stats
Authorization: Bearer admin-jwt-token
{
"totalUsers": 1250,
"activeUsers": 1180,
"newUsersThisMonth": 45,
"usersByRole": {
"user": 1100,
"moderator": 120,
"admin": 30
},
"verificationStats": {
"emailVerified": 1150,
"phoneVerified": 800
}
}
User Activity Tracking
GET /api/users/{userId}/activity
Authorization: Bearer admin-jwt-token
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
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
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
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
POST /api/auth/register
{
"email": "user@example.com",
"password": "SecurePass123!",
"name": "John Doe"
}
POST /api/auth/login
{
"email": "user@example.com",
"password": "SecurePass123!",
"provider": "internal"
}
POST /api/auth/refresh
{
"refreshToken": "your-refresh-token"
}
POST /api/auth/logout
Authorization: Bearer your-jwt-token
Email Verification
POST /api/auth/send-verification
{
"email": "user@example.com"
}
POST /api/auth/verify-email
{
"email": "user@example.com",
"code": "123456"
}
Password Management
POST /api/auth/forgot-password
{
"email": "user@example.com"
}
POST /api/auth/reset-password
{
"email": "user@example.com",
"code": "123456",
"newPassword": "NewSecurePass123!"
}
POST /api/auth/change-password
Authorization: Bearer your-jwt-token
{
"currentPassword": "OldPassword123!",
"newPassword": "NewSecurePass123!"
}
SMS Authentication
POST /api/auth/sms/send
{
"phone": "+1234567890"
}
POST /api/auth/sms/verify
{
"phone": "+1234567890",
"code": "123456"
}
OAuth Authentication
GET /api/auth/oauth/google/url
GET /api/auth/oauth/google/callback?code=auth-code&state=state-value
WebAuthn (FIDO2)
POST /api/auth/webauthn/register/begin
Authorization: Bearer your-jwt-token
POST /api/auth/webauthn/register/finish
Authorization: Bearer your-jwt-token
{
"credential": { /* WebAuthn credential object */ }
}
POST /api/auth/webauthn/login/begin
{
"email": "user@example.com"
}
POST /api/auth/webauthn/login/finish
{
"email": "user@example.com",
"credential": { /* WebAuthn credential object */ }
}
User Profile & Token Management
GET /api/auth/profile
Authorization: Bearer your-jwt-token
GET /api/auth/validate
Authorization: Bearer your-jwt-token
๐ง Authentication Configuration
Password Policy Configuration
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
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_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
import { BaseAuthProvider } from './base-auth-provider';
export class CustomAuthProvider extends BaseAuthProvider {
async authenticate(credentials: any): Promise<any> {
}
}
Custom Middleware
export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
};
๐ 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
npm run seed
npm run seed --reset
npm run seed --force
Custom Seed Data
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
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
import { SocketManager } from './core/server/socket-manager';
const socketManager = new SocketManager(server);
socketManager.on('product:updated', (data) => {
socketManager.broadcast('product:updated', data);
});
Client Usage
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
const response = await fetch('/api/odoo/connect', {
method: 'POST'
});
const customers = await fetch('/api/odoo/customers?limit=50&filters[is_company]=true');
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
๐งช Testing
Unit Tests
npm test
npm run test:coverage
npm test -- --testNamePattern="ProductService"
Integration Tests
npm run test:integration
npm run test:integration -- --grep "Products API"
๐ Deployment
Production Build
npm run build:prod
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
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
GET /health
GET /health/database
GET /health/system
๐ค Contributing
We welcome contributions! Please see our Contributing Guide for details.
๐ License
MIT License - see LICENSE file for details.
๐ Related Packages
๐ Support