WIP - improve login to tenants by domains
This commit is contained in:
@@ -9,17 +9,68 @@ export class TenantDatabaseService {
|
||||
private tenantConnections: Map<string, Knex> = new Map();
|
||||
|
||||
async getTenantKnex(tenantIdOrSlug: string): Promise<Knex> {
|
||||
// Check if we have a cached connection
|
||||
if (this.tenantConnections.has(tenantIdOrSlug)) {
|
||||
// For domain-based lookups, validate the domain still exists before returning cached connection
|
||||
const centralPrisma = getCentralPrisma();
|
||||
|
||||
// Check if this looks like a domain (not a UUID)
|
||||
const isDomain = !tenantIdOrSlug.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
|
||||
|
||||
if (isDomain) {
|
||||
try {
|
||||
const domainRecord = await centralPrisma.domain.findUnique({
|
||||
where: { domain: tenantIdOrSlug },
|
||||
});
|
||||
|
||||
// If domain no longer exists, remove cached connection and continue to error
|
||||
if (!domainRecord) {
|
||||
this.logger.warn(`Domain ${tenantIdOrSlug} no longer exists, removing cached connection`);
|
||||
await this.disconnectTenant(tenantIdOrSlug);
|
||||
throw new Error(`Domain ${tenantIdOrSlug} not found`);
|
||||
}
|
||||
} catch (error) {
|
||||
// If domain doesn't exist, remove from cache and re-throw
|
||||
if (error.message.includes('not found')) {
|
||||
throw error;
|
||||
}
|
||||
// For other errors, log but continue with cached connection
|
||||
this.logger.warn(`Error validating domain ${tenantIdOrSlug}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
return this.tenantConnections.get(tenantIdOrSlug);
|
||||
}
|
||||
|
||||
const centralPrisma = getCentralPrisma();
|
||||
|
||||
// Try to find tenant by ID first, then by slug
|
||||
let tenant = await centralPrisma.tenant.findUnique({
|
||||
where: { id: tenantIdOrSlug },
|
||||
});
|
||||
let tenant = null;
|
||||
|
||||
// First, try to find by domain (most common case - subdomain lookup)
|
||||
try {
|
||||
const domainRecord = await centralPrisma.domain.findUnique({
|
||||
where: { domain: tenantIdOrSlug },
|
||||
include: { tenant: true },
|
||||
});
|
||||
|
||||
console.log('here:' + JSON.stringify(domainRecord));
|
||||
|
||||
if (domainRecord) {
|
||||
tenant = domainRecord.tenant;
|
||||
this.logger.log(`Found tenant by domain: ${tenantIdOrSlug} -> ${tenant.name}`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.debug(`No domain found for: ${tenantIdOrSlug}, trying ID/slug lookup`);
|
||||
}
|
||||
|
||||
// Fallback: Try to find tenant by ID
|
||||
if (!tenant) {
|
||||
tenant = await centralPrisma.tenant.findUnique({
|
||||
where: { id: tenantIdOrSlug },
|
||||
});
|
||||
}
|
||||
|
||||
// Fallback: Try to find by slug
|
||||
if (!tenant) {
|
||||
tenant = await centralPrisma.tenant.findUnique({
|
||||
where: { slug: tenantIdOrSlug },
|
||||
|
||||
Reference in New Issue
Block a user