Add auth.middleware and Pool to category router
This commit is contained in:
1 parent
f27d87531c
commit
3d7be239d6
1 file changed
+8
-3
@@ -1,18 +1,23 @@
|
|||||||
import { Router, Request, Response } from 'express';
|
import { Router, Request, Response } from 'express';
|
||||||
import { CategoryRepository } from './category.repository.ts';
|
import { CategoryRepository } from './category.repository.ts';
|
||||||
import { buildCategoryTree } from './tree.utility.ts';
|
import { buildCategoryTree } from './tree.utility.ts';
|
||||||
|
import { createAuthMiddleware } from './auth.middleware.ts';
|
||||||
|
import { Pool } from 'pg';
|
||||||
|
|
||||||
// Clean regex pattern matching valid Postgres ltree structures
|
// Clean regex pattern matching valid Postgres ltree structures
|
||||||
const LTREE_REGEX = /^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$/;
|
const LTREE_REGEX = /^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$/;
|
||||||
|
|
||||||
export function createCategoryRouter(repository: CategoryRepository): Router {
|
export function createCategoryRouter(repository: CategoryRepository, db: Pool): Router {
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
const auth = createAuthMiddleware(db);
|
||||||
|
|
||||||
router.get('/tree{/:path}', async (req: Request, res: Response): Promise<void> => {
|
router.get('/tree{/:path}', auth, async (req: Request, res: Response): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const rawPath = req.params.path;
|
const rawPath = req.params.path;
|
||||||
const parentPath = Array.isArray(rawPath) ? rawPath[0] : (rawPath || 'Top');
|
const parentPath = Array.isArray(rawPath) ? rawPath[0] : (rawPath || 'Top');
|
||||||
|
|
||||||
|
const userId = (req as any).userId;
|
||||||
|
|
||||||
// 1. INPUT VALIDATION: Stop malicious or broken ltree strings early
|
// 1. INPUT VALIDATION: Stop malicious or broken ltree strings early
|
||||||
if (!LTREE_REGEX.test(parentPath)) {
|
if (!LTREE_REGEX.test(parentPath)) {
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
@@ -22,7 +27,7 @@ export function createCategoryRouter(repository: CategoryRepository): Router {
|
|||||||
return; // Break execution early
|
return; // Break execution early
|
||||||
}
|
}
|
||||||
|
|
||||||
const flatRows = await repository.findAllDescendants(parentPath);
|
const flatRows = await repository.findAllDescendants(parentPath, userId);
|
||||||
const nestedTree = flatRows.length > 0 ? buildCategoryTree(flatRows) : [];
|
const nestedTree = flatRows.length > 0 ? buildCategoryTree(flatRows) : [];
|
||||||
|
|
||||||
res.json({ success: true, data: nestedTree });
|
res.json({ success: true, data: nestedTree });
|
||||||
|
|||||||
Reference in new issue
Block a user