All files / src/infrastructure/database tenant-isolation.plugin.ts

0% Statements 0/18
0% Branches 0/8
0% Functions 0/2
0% Lines 0/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                                                                     
import { Schema } from 'mongoose';
import { tenantContext } from './tenant.context';
 
export function tenantIsolationPlugin(schema: Schema) {
  // Add tenantId field if not present and if it's not a platform/global collection
  if (!schema.paths['tenantId']) {
    schema.add({
      tenantId: { type: String, required: true, index: true },
    });
  }
 
  // Intercept query hooks to filter by active tenant context
  const filterQueries = function (this: any, next: any) {
    const tenantId = tenantContext.getStore();
 
    // Enforce tenant scoping only if a tenantId is currently in request scope,
    // and if the query doesn't explicitly target or bypass it.
    if (tenantId && tenantId !== 'SYSTEM') {
      const query = this.getQuery();
      if (!query.tenantId) {
        this.where({ tenantId });
      }
    }
    next();
  };
 
  schema.pre('find', filterQueries);
  schema.pre('findOne', filterQueries);
  schema.pre('countDocuments', filterQueries);
  schema.pre('updateOne', filterQueries);
  schema.pre('updateMany', filterQueries);
  schema.pre('deleteOne', filterQueries);
  schema.pre('deleteMany', filterQueries);
}