23 lines
867 B
TypeScript
23 lines
867 B
TypeScript
import type { Request, Response, NextFunction } from 'express'
|
|
import { sendForbidden, sendUnauthorized } from './authHelpers'
|
|
import type { EmployeeRole } from '@rentaldrivego/database'
|
|
import { CompanyPolicy, type CompanyPolicyAction } from '../security/policies/companyPolicy'
|
|
|
|
export function requireCompanyPolicy(action: CompanyPolicyAction) {
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
|
const employee = req.employee
|
|
if (!employee) return sendUnauthorized(res, 'unauthenticated', 'Authentication required')
|
|
|
|
const allowedRoles: readonly EmployeeRole[] = CompanyPolicy[action]
|
|
if (!allowedRoles.includes(employee.role)) {
|
|
return sendForbidden(res, 'forbidden', 'You do not have permission to perform this action', {
|
|
action,
|
|
allowedRoles,
|
|
yourRole: employee.role,
|
|
})
|
|
}
|
|
|
|
next()
|
|
}
|
|
}
|