Files
api/src/get-user/get-user.service.ts
T

92 lines
2.6 KiB
TypeScript
Raw Normal View History

2026-07-23 10:25:32 +03:30
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class GetUserService {
constructor(private readonly prisma: PrismaService) {}
async resolveByHost(hostHeader?: string, domainQuery?: string) {
const host = this.normalizeHost(domainQuery || hostHeader || '');
if (!host) {
throw new NotFoundException('domain required');
}
2026-07-23 19:41:21 +03:30
const tenants = await this.prisma.tenant.findMany({
where: { isActive: true },
2026-07-23 10:25:32 +03:30
});
2026-07-23 19:41:21 +03:30
const tenant = tenants.find((item) => this.matchesHost(item, host));
2026-07-23 10:25:32 +03:30
if (!tenant) {
throw new NotFoundException('tenant not found for domain');
}
const ui = (tenant.appUiConfig as Record<string, any> | null) || null;
const themeColors = ui?.app?.theme?.colors;
const branding = {
id: tenant.id,
2026-07-23 19:41:21 +03:30
name: tenant.nameEn || tenant.slug,
2026-07-23 10:25:32 +03:30
name_fa: tenant.nameFa,
name_en: tenant.nameEn,
avatar: tenant.avatarUrl,
color: themeColors?.primary || tenant.primaryColor,
secondary_color: themeColors?.secondary || tenant.secondaryColor,
background_color: themeColors?.background || tenant.backgroundColor,
node_server: tenant.nodeServer,
node_ws: tenant.nodeWs,
app_url: tenant.appUrl,
admin_url: tenant.adminUrl,
product: tenant.product,
2026-07-23 19:41:21 +03:30
theme: 'dynamicMode',
2026-07-23 10:25:32 +03:30
mode: 'dynamicMode',
app_ui_config: tenant.product === 'khanegi' ? ui : undefined,
};
return {
...branding,
user: { ...branding },
};
}
2026-07-23 19:41:21 +03:30
private matchesHost(
tenant: {
domain: string;
domains: unknown;
},
host: string,
) {
const candidates = new Set<string>();
for (const value of [tenant.domain, ...this.readDomains(tenant.domains)]) {
const normalized = this.normalizeHost(value);
if (!normalized) continue;
candidates.add(normalized);
candidates.add(normalized.replace(/^www\./, ''));
candidates.add(`www.${normalized.replace(/^www\./, '')}`);
}
return candidates.has(host) || candidates.has(host.replace(/^www\./, ''));
}
private readDomains(raw: unknown): string[] {
if (!raw) return [];
if (Array.isArray(raw)) return raw.map(String);
if (typeof raw === 'string') {
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed.map(String) : [];
} catch {
return [];
}
}
return [];
}
2026-07-23 10:25:32 +03:30
private normalizeHost(value: string) {
return value
.trim()
.toLowerCase()
.replace(/^https?:\/\//, '')
.split('/')[0]
.split(':')[0];
}
}