Initial Commit
This commit is contained in:
68
backend/src/core/config/tenant.ts
Normal file
68
backend/src/core/config/tenant.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// Simple in-memory cache for tenant validation
|
||||
const tenantValidityCache = new Map<string, { ok: boolean; ts: number }>();
|
||||
const TENANT_CACHE_TTL_MS = 60_000; // 1 minute
|
||||
|
||||
/**
|
||||
* Tenant-aware configuration for multi-tenant architecture
|
||||
*/
|
||||
|
||||
export interface TenantConfig {
|
||||
tenantId: string;
|
||||
databaseUrl: string;
|
||||
redisUrl: string;
|
||||
platformServicesUrl: string;
|
||||
isAdminTenant: boolean;
|
||||
}
|
||||
|
||||
export const getTenantConfig = (): TenantConfig => {
|
||||
const tenantId = process.env.TENANT_ID || 'admin';
|
||||
|
||||
const databaseUrl = tenantId === 'admin'
|
||||
? `postgresql://${process.env.DB_USER || 'motovault_user'}:${process.env.DB_PASSWORD}@${process.env.DB_HOST || 'postgres'}:${process.env.DB_PORT || '5432'}/${process.env.DB_NAME || 'motovault'}`
|
||||
: `postgresql://motovault_user:${process.env.DB_PASSWORD}@${tenantId}-postgres:5432/motovault`;
|
||||
|
||||
const redisUrl = tenantId === 'admin'
|
||||
? `redis://${process.env.REDIS_HOST || 'redis'}:${process.env.REDIS_PORT || '6379'}`
|
||||
: `redis://${tenantId}-redis:6379`;
|
||||
|
||||
const platformServicesUrl = process.env.PLATFORM_TENANTS_API_URL || 'http://mvp-platform-tenants:8000';
|
||||
|
||||
return {
|
||||
tenantId,
|
||||
databaseUrl,
|
||||
redisUrl,
|
||||
platformServicesUrl,
|
||||
isAdminTenant: tenantId === 'admin'
|
||||
};
|
||||
};
|
||||
|
||||
export const isValidTenant = async (tenantId: string): Promise<boolean> => {
|
||||
// Check cache
|
||||
const now = Date.now();
|
||||
const cached = tenantValidityCache.get(tenantId);
|
||||
if (cached && (now - cached.ts) < TENANT_CACHE_TTL_MS) {
|
||||
return cached.ok;
|
||||
}
|
||||
|
||||
let ok = false;
|
||||
try {
|
||||
const baseUrl = process.env.PLATFORM_TENANTS_API_URL || 'http://mvp-platform-tenants:8000';
|
||||
const url = `${baseUrl}/api/v1/tenants/${encodeURIComponent(tenantId)}`;
|
||||
const resp = await axios.get(url, { timeout: 2000 });
|
||||
ok = resp.status === 200;
|
||||
} catch { ok = false; }
|
||||
|
||||
tenantValidityCache.set(tenantId, { ok, ts: now });
|
||||
return ok;
|
||||
};
|
||||
|
||||
export const extractTenantId = (options: {
|
||||
envTenantId?: string;
|
||||
jwtTenantId?: string;
|
||||
subdomain?: string;
|
||||
}): string => {
|
||||
const { envTenantId, jwtTenantId, subdomain } = options;
|
||||
return envTenantId || jwtTenantId || subdomain || 'admin';
|
||||
};
|
||||
Reference in New Issue
Block a user