Files
carmanagement/apps/api/src/middleware/requireTenant.ts
T
2026-05-21 12:35:49 -04:00

26 lines
845 B
TypeScript

import { Request, Response, NextFunction } from 'express'
import { prisma } from '../lib/prisma'
import { sendUnauthorized } from './authHelpers'
/**
* Loads the company record and validates it exists.
* Must be applied after `requireCompanyAuth`.
*
* Guarantees on success:
* req.company — full Company record
* req.companyId — string id (already set by requireCompanyAuth)
*/
export async function requireTenant(req: Request, res: Response, next: NextFunction) {
if (!req.companyId) {
return sendUnauthorized(res, 'unauthenticated', 'Tenant context missing — requireCompanyAuth must run first')
}
const company = await prisma.company.findUnique({ where: { id: req.companyId } })
if (!company) {
return sendUnauthorized(res, 'company_not_found', 'Company not found')
}
req.company = company
next()
}