mirror of
https://github.com/docmost/docmost.git
synced 2026-05-07 06:23:06 +08:00
57 lines
1.7 KiB
TypeScript
57 lines
1.7 KiB
TypeScript
import { Injectable, NestMiddleware } from '@nestjs/common';
|
|
import { FastifyRequest, FastifyReply } from 'fastify';
|
|
import { EnvironmentService } from '../../integrations/environment/environment.service';
|
|
import { WorkspaceRepo } from '@docmost/db/repos/workspace/workspace.repo';
|
|
|
|
@Injectable()
|
|
export class DomainMiddleware implements NestMiddleware {
|
|
constructor(
|
|
private workspaceRepo: WorkspaceRepo,
|
|
private environmentService: EnvironmentService,
|
|
) {}
|
|
async use(
|
|
req: FastifyRequest['raw'],
|
|
res: FastifyReply['raw'],
|
|
next: () => void,
|
|
) {
|
|
if (this.environmentService.isSelfHosted()) {
|
|
const workspace = await this.workspaceRepo.findFirst();
|
|
if (!workspace) {
|
|
//throw new NotFoundException('Workspace not found');
|
|
(req as any).workspaceId = null;
|
|
return next();
|
|
}
|
|
|
|
// TODO: unify
|
|
(req as any).workspaceId = workspace.id;
|
|
(req as any).workspace = workspace;
|
|
} else if (this.environmentService.isCloud()) {
|
|
const header = req.headers.host;
|
|
|
|
// First, try to find workspace by custom domain
|
|
const workspaceByCustomDomain =
|
|
await this.workspaceRepo.findByCustomDomain(header);
|
|
|
|
if (workspaceByCustomDomain) {
|
|
(req as any).workspaceId = workspaceByCustomDomain.id;
|
|
(req as any).workspace = workspaceByCustomDomain;
|
|
return next();
|
|
}
|
|
|
|
// Fall back to subdomain logic
|
|
const subdomain = header.split('.')[0];
|
|
const workspace = await this.workspaceRepo.findByHostname(subdomain);
|
|
|
|
if (!workspace) {
|
|
(req as any).workspaceId = null;
|
|
return next();
|
|
}
|
|
|
|
(req as any).workspaceId = workspace.id;
|
|
(req as any).workspace = workspace;
|
|
}
|
|
|
|
next();
|
|
}
|
|
}
|