workspace-v1/shared/libs/multi-tenancy/_reference/tenant.guard.reference.ts
rckrdmrd 66161b1566 feat: Workspace-v1 complete migration with NEXUS v3.4
Sistema NEXUS v3.4 migrado con:

Estructura principal:
- core/orchestration: Sistema SIMCO + CAPVED (27 directivas, 28 perfiles)
- core/catalog: Catalogo de funcionalidades reutilizables
- shared/knowledge-base: Base de conocimiento compartida
- devtools/scripts: Herramientas de desarrollo
- control-plane/registries: Control de servicios y CI/CD
- orchestration/: Configuracion de orquestacion de agentes

Proyectos incluidos (11):
- gamilit (submodule -> GitHub)
- trading-platform (OrbiquanTIA)
- erp-suite con 5 verticales:
  - erp-core, construccion, vidrio-templado
  - mecanicas-diesel, retail, clinicas
- betting-analytics
- inmobiliaria-analytics
- platform_marketing_content
- pos-micro, erp-basico

Configuracion:
- .gitignore completo para Node.js/Python/Docker
- gamilit como submodule (git@github.com:rckrdmrd/gamilit-workspace.git)
- Sistema de puertos estandarizado (3005-3199)

Generated with NEXUS v3.4 Migration System
EPIC-010: Configuracion Git y Repositorios
2026-01-04 03:37:42 -06:00

145 lines
3.7 KiB
TypeScript

/**
* TENANT GUARD - REFERENCE IMPLEMENTATION
*
* @description Guard para validación de multi-tenancy.
* Asegura que el usuario pertenece al tenant correcto.
*
* @usage
* ```typescript
* @UseGuards(JwtAuthGuard, TenantGuard)
* @Get('data')
* getData(@CurrentTenant() tenant: Tenant) { ... }
* ```
*
* @origin gamilit/apps/backend/src/shared/guards/tenant.guard.ts
*/
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
// Adaptar imports según proyecto
// import { Tenant } from '../entities';
/**
* Metadata key para configuración de tenant
*/
export const TENANT_KEY = 'tenant';
export const SKIP_TENANT_KEY = 'skipTenant';
@Injectable()
export class TenantGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
@InjectRepository(Tenant, 'auth')
private readonly tenantRepository: Repository<Tenant>,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
// Verificar si la ruta debe saltarse la validación de tenant
const skipTenant = this.reflector.getAllAndOverride<boolean>(SKIP_TENANT_KEY, [
context.getHandler(),
context.getClass(),
]);
if (skipTenant) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
if (!user) {
throw new ForbiddenException('Usuario no autenticado');
}
// Obtener tenant del usuario (asumiendo que está en el JWT o perfil)
const tenantId = user.tenant_id || request.headers['x-tenant-id'];
if (!tenantId) {
throw new ForbiddenException('Tenant no especificado');
}
// Validar que el tenant existe y está activo
const tenant = await this.tenantRepository.findOne({
where: { id: tenantId, is_active: true },
});
if (!tenant) {
throw new ForbiddenException('Tenant inválido o inactivo');
}
// Inyectar tenant en request para uso posterior
request.tenant = tenant;
return true;
}
}
// ============ DECORADORES ============
import { SetMetadata, createParamDecorator } from '@nestjs/common';
/**
* Decorador para saltar validación de tenant
*/
export const SkipTenant = () => SetMetadata(SKIP_TENANT_KEY, true);
/**
* Decorador para obtener el tenant actual
*/
export const CurrentTenant = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.tenant;
},
);
// ============ RLS HELPER ============
/**
* Helper para aplicar Row-Level Security en queries
*
* @usage
* ```typescript
* const users = await this.userRepo
* .createQueryBuilder('user')
* .where(withTenant('user', tenantId))
* .getMany();
* ```
*/
export function withTenant(alias: string, tenantId: string): string {
return `${alias}.tenant_id = '${tenantId}'`;
}
/**
* Interceptor para inyectar tenant_id automáticamente en creates
*
* @usage En el servicio base
* ```typescript
* async create(dto: CreateDto, tenantId: string) {
* const entity = this.repo.create({
* ...dto,
* tenant_id: tenantId,
* });
* return this.repo.save(entity);
* }
* ```
*/
export function injectTenantId<T extends { tenant_id?: string }>(
entity: T,
tenantId: string,
): T {
return { ...entity, tenant_id: tenantId };
}
// ============ TIPOS ============
interface Tenant {
id: string;
name: string;
slug: string;
is_active: boolean;
}