Dev.to WebDev 🛠 Dev 👁 2 📖 5 min read

Structuring a NestJS CRM: Modules, Roles and Record-Level Permissions

Most CRM projects we take on start the same way: "We need customers, deals, orders… and sales staff should only see their own customers." That last sentence is where things get messy. After building several custom CRMs

Most CRM projects we take on start the same way: "We need customers, deals, orders… and sales staff should only see their own customers." That last sentence is where things get messy.

After building several custom CRMs for SMEs with NestJS + PostgreSQL, we've settled on a structure that keeps permissions out of the controllers and makes "who can see what" easy to change later. Here's the setup.

What we'll cover:

  1. A module layout that scales past 10 modules
  2. Roles vs permissions (and why we store permissions, not roles, in checks)
  3. A @RequirePermissions() decorator + guard
  4. Record-level scoping: "own", "team", "all"
  5. An audit log interceptor

Examples use NestJS 10+, TypeScript and Prisma, but the ideas work with TypeORM too.

1. Module layout

One NestJS module per business domain, plus a core folder for cross-cutting concerns:

src/
├── core/
│   ├── auth/           # JWT, login, current user
│   ├── access/         # permissions, guard, scoping helpers
│   └── audit/          # audit log interceptor + service
├── modules/
│   ├── customers/
│   ├── deals/
│   ├── orders/
│   ├── products/
│   └── reports/
└── main.ts

Rule of thumb: a business module may import core, but never another business module's repository. If orders needs customer data, it calls CustomersService. This keeps scoping rules in one place per domain.

2. Roles vs permissions

Clients talk in roles: Admin, Sales Manager, Sales, Accountant. But roles change constantly ("can Sales export to Excel now?"). If your code checks role === 'manager', every change is a deploy.

So we check permissions in code and map roles to permissions in the database:

// core/access/permissions.ts
export const Permission = {
  CustomerRead: 'customer:read',
  CustomerWrite: 'customer:write',
  CustomerExport: 'customer:export',
  DealRead: 'deal:read',
  DealWrite: 'deal:write',
  OrderApprove: 'order:approve',
  ReportView: 'report:view',
} as const;

export type Permission = (typeof Permission)[keyof typeof Permission];
// schema.prisma (simplified)
model Role {
  id          Int      @id @default(autoincrement())
  name        String   @unique
  permissions String[] // e.g. ["customer:read", "deal:read"]
  scope       Scope    @default(OWN)
  users       User[]
}

enum Scope {
  OWN
  TEAM
  ALL
}

model User {
  id     Int    @id @default(autoincrement())
  email  String @unique
  teamId Int?
  roleId Int
  role   Role   @relation(fields: [roleId], references: [id])
}

Now "let Sales export customers" is a row update in an admin screen, not a code change.

3. Decorator + guard

// core/access/require-permissions.decorator.ts
import { SetMetadata } from '@nestjs/common';
import { Permission } from './permissions';

export const PERMISSIONS_KEY = 'permissions';
export const RequirePermissions = (...perms: Permission[]) =>
  SetMetadata(PERMISSIONS_KEY, perms);
// core/access/permissions.guard.ts
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { PERMISSIONS_KEY } from './require-permissions.decorator';
import { Permission } from './permissions';

@Injectable()
export class PermissionsGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(ctx: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride<Permission[]>(PERMISSIONS_KEY, [
      ctx.getHandler(),
      ctx.getClass(),
    ]);
    if (!required?.length) return true;

    const user = ctx.switchToHttp().getRequest().user;
    const granted: string[] = user?.role?.permissions ?? [];

    const ok = required.every((p) => granted.includes(p));
    if (!ok) throw new ForbiddenException('Missing permission');
    return true;
  }
}

Register it globally after your JWT guard, so every route is protected by default:

// app.module.ts
providers: [
  { provide: APP_GUARD, useClass: JwtAuthGuard },
  { provide: APP_GUARD, useClass: PermissionsGuard },
],

Controllers stay readable:

@Controller('customers')
export class CustomersController {
  constructor(private readonly customers: CustomersService) {}

  @Get()
  @RequirePermissions(Permission.CustomerRead)
  list(@CurrentUser() user: AuthUser, @Query() q: ListCustomersDto) {
    return this.customers.list(user, q);
  }

  @Get('export')
  @RequirePermissions(Permission.CustomerRead, Permission.CustomerExport)
  export(@CurrentUser() user: AuthUser, @Query() q: ListCustomersDto) {
    return this.customers.export(user, q);
  }
}

Tip: load the role's permissions once at login and put them in the JWT payload (or cache them per user). Don't hit the database on every request just to check permissions — and remember to force a re-login or cache bust when an admin edits a role.

4. Record-level scoping: own / team / all

The guard answers "can this user read customers?" It does not answer "which customers?" That's where most CRM data leaks happen: a list endpoint that filters correctly, and a GET /customers/:id that doesn't.

We solve it with one helper that every service uses to build its where clause:

// core/access/scope.ts
export function ownershipWhere(user: AuthUser): { ownerId?: number; owner?: { teamId: number } } {
  switch (user.role.scope) {
    case 'ALL':
      return {};
    case 'TEAM':
      return { owner: { teamId: user.teamId! } };
    case 'OWN':
    default:
      return { ownerId: user.id };
  }
}
// modules/customers/customers.service.ts
@Injectable()
export class CustomersService {
  constructor(private readonly prisma: PrismaService) {}

  list(user: AuthUser, q: ListCustomersDto) {
    return this.prisma.customer.findMany({
      where: { ...ownershipWhere(user), ...this.filters(q) },
      take: q.limit ?? 20,
      skip: q.offset ?? 0,
    });
  }

  async findOne(user: AuthUser, id: number) {
    const customer = await this.prisma.customer.findFirst({
      where: { id, ...ownershipWhere(user) },
    });
    // 404, not 403: don't confirm the record exists
    if (!customer) throw new NotFoundException();
    return customer;
  }
}

Two details that matter:

  • Use findFirst with the scope, not findUnique + a check afterwards. It's impossible to forget the check if it's part of the query.
  • Return 404 instead of 403 for records outside the user's scope, so IDs can't be probed.

Write an e2e test per module: create two sales users, give each a customer, and assert user A gets 404 on user B's customer. It's the cheapest way to prove scoping actually works.

5. Audit log interceptor

Every CRM client eventually asks "who changed this deal's value?" Add it on day one:

// core/audit/audit.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { tap } from 'rxjs';
import { AuditService } from './audit.service';

const WRITE_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];

@Injectable()
export class AuditInterceptor implements NestInterceptor {
  constructor(private readonly audit: AuditService) {}

  intercept(ctx: ExecutionContext, next: CallHandler) {
    const req = ctx.switchToHttp().getRequest();
    if (!WRITE_METHODS.includes(req.method)) return next.handle();

    return next.handle().pipe(
      tap((result) =>
        this.audit.record({
          userId: req.user?.id,
          action: `${req.method} ${req.route?.path}`,
          entityId: result?.id ?? req.params?.id,
          payload: req.body,
        }),
      ),
    );
  }
}

Strip passwords and tokens from payload before saving, and write the log asynchronously (a queue, or at least fire-and-forget) so it never slows down the request.

Checklist before handing a CRM to a client

  • [ ] Every route has a permission, or is explicitly public
  • [ ] Every findOne / update / delete uses the scoping helper
  • [ ] Cross-user e2e tests for each module
  • [ ] Role editor in the admin UI, with permission cache invalidation
  • [ ] Audit log for every write, with sensitive fields stripped
  • [ ] Exports (Excel/CSV) require their own permission — they're the easiest way for data to leave the company

The same access layer works whether the CRM has 5 modules or 8+ (customers, deals, orders, inventory, projects, reports…): new modules just add permissions and reuse the guard and scoping helper.

What does your permission model look like — RBAC, ABAC, or something like CASL? I'd love to hear in the comments.

I'm Phát, founder of Tấn Phát Digital, a web & software agency in Ho Chi Minh City. We build custom CRMs and Next.js + Strapi websites for SMEs.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.