Api changes

This commit is contained in:
Owen Schwartz
2024-10-19 18:47:41 -04:00
parent 94da55450e
commit 0fa3382cda
20 changed files with 319 additions and 154 deletions

View File

@@ -36,13 +36,15 @@ app.prepare().then(() => {
externalServer.use(cors());
externalServer.use(cookieParser());
externalServer.use(express.json());
externalServer.use(
rateLimitMiddleware({
windowMin: 1,
max: 100,
type: "IP_ONLY",
}),
);
if (!dev) {
externalServer.use(
rateLimitMiddleware({
windowMin: 1,
max: 100,
type: "IP_ONLY",
}),
);
}
const prefix = `/api/v1`;
externalServer.use(prefix, unauthenticated);

View File

@@ -8,9 +8,10 @@ import createHttpError from 'http-errors';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
import { eq, and } from 'drizzle-orm';
import stoi from '@server/utils/stoi';
const createResourceParamsSchema = z.object({
siteId: z.string().transform(Number).pipe(z.number().int().positive()),
siteId: z.string().optional().transform(stoi).pipe(z.number().int().positive().optional()),
orgId: z.string()
});

View File

@@ -13,10 +13,11 @@ import createHttpError from "http-errors";
import { sql, eq, or, inArray, and, count } from "drizzle-orm";
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
import logger from "@server/logger";
import stoi from "@server/utils/stoi";
const listResourcesParamsSchema = z
.object({
siteId: z.string().optional().transform(Number).pipe(z.number().int().positive()),
siteId: z.string().optional().transform(stoi).pipe(z.number().int().positive().optional()),
orgId: z.string().optional(),
})
.refine((data) => !!data.siteId !== !!data.orgId, {
@@ -27,7 +28,7 @@ const listResourcesSchema = z.object({
limit: z
.string()
.optional()
.default("0")
.default("1000")
.transform(Number)
.pipe(z.number().int().nonnegative()),
@@ -90,6 +91,8 @@ export async function listResources(
next: NextFunction,
): Promise<any> {
try {
logger.info(JSON.stringify(req.query, null, 2));
logger.info(JSON.stringify(req.params, null, 2));
const parsedQuery = listResourcesSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(

View File

@@ -9,7 +9,7 @@ import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
const createRoleParamsSchema = z.object({
orgId: z.number().int().positive()
orgId: z.string()
});
const createRoleSchema = z.object({

View File

@@ -9,7 +9,6 @@ import createHttpError from 'http-errors';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
const API_BASE_URL = "http://localhost:3000";
// Define Zod schema for request parameters validation

View File

@@ -8,10 +8,11 @@ import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
import stoi from '@server/utils/stoi';
// Define Zod schema for request parameters validation
const getSiteSchema = z.object({
siteId: z.string().transform(Number).pipe(z.number().int().positive()).optional(),
siteId: z.string().optional().transform(stoi).pipe(z.number().int().positive().optional()).optional(),
niceId: z.string().optional(),
orgId: z.string().optional(),
});

View File

@@ -9,7 +9,7 @@ import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
const createTargetParamsSchema = z.object({
resourceId: z.string().uuid(),
resourceId: z.string(),
});
const createTargetSchema = z.object({

View File

@@ -1,35 +1,73 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { targets, resources } from '@server/db/schema';
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
import { db } from "@server/db";
import { targets, resources } from "@server/db/schema";
import HttpCode from "@server/types/HttpCode";
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
import { sql, eq } from 'drizzle-orm';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
import { eq, sql } from "drizzle-orm";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import logger from "@server/logger";
const listTargetsParamsSchema = z.object({
resourceId: z.string().optional()
resourceId: z.string()
});
const listTargetsSchema = z.object({
limit: z.string().optional().transform(Number).pipe(z.number().int().positive().default(10)),
offset: z.string().optional().transform(Number).pipe(z.number().int().nonnegative().default(0)),
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.number().int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative()),
});
export async function listTargets(req: Request, res: Response, next: NextFunction): Promise<any> {
function queryTargets(resourceId: string) {
let baseQuery = db
.select({
targetId: targets.targetId,
ip: targets.ip,
method: targets.method,
port: targets.port,
protocol: targets.protocol,
enabled: targets.enabled,
resourceId: targets.resourceId,
// resourceName: resources.name,
})
.from(targets)
// .leftJoin(resources, eq(targets.resourceId, resources.resourceId))
.where(eq(targets.resourceId, resourceId));
return baseQuery;
}
export type ListTargetsResponse = {
targets: Awaited<ReturnType<typeof queryTargets>>;
pagination: { total: number; limit: number; offset: number };
};
export async function listTargets(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = listTargetsSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedQuery.error.errors.map(e => e.message).join(', ')
fromError(parsedQuery.error)
)
);
}
const { limit, offset } = parsedQuery.data;
const parsedParams = listTargetsParamsSchema.safeParse(req.params);
@@ -37,44 +75,38 @@ export async function listTargets(req: Request, res: Response, next: NextFunctio
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedParams.error.errors.map(e => e.message).join(', ')
fromError(parsedParams.error)
)
);
}
const { resourceId } = parsedParams.data;
// Check if the user has permission to list targets
const hasPermission = await checkUserActionPermission(
ActionsEnum.listTargets,
req
);
if (!hasPermission) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission to perform this action"
)
);
}
const { resourceId } = parsedParams.data;
const baseQuery = queryTargets(resourceId);
// Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.listTargets, req);
if (!hasPermission) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
}
let baseQuery: any = db
.select({
targetId: targets.targetId,
ip: targets.ip,
method: targets.method,
port: targets.port,
protocol: targets.protocol,
enabled: targets.enabled,
resourceName: resources.name,
})
let countQuery = db
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(targets)
.leftJoin(resources, eq(targets.resourceId, resources.resourceId));
let countQuery: any = db.select({ count: sql<number>`cast(count(*) as integer)` }).from(targets);
if (resourceId) {
baseQuery = baseQuery.where(eq(targets.resourceId, resourceId));
countQuery = countQuery.where(eq(targets.resourceId, resourceId));
}
.where(eq(targets.resourceId, resourceId));
const targetsList = await baseQuery.limit(limit).offset(offset);
const totalCountResult = await countQuery;
const totalCount = totalCountResult[0].count;
return response(res, {
return response<ListTargetsResponse>(res, {
data: {
targets: targetsList,
pagination: {
@@ -90,6 +122,11 @@ export async function listTargets(req: Request, res: Response, next: NextFunctio
});
} catch (error) {
logger.error(error);
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred..."
)
);
}
}

View File

@@ -11,7 +11,7 @@ import { eq } from 'drizzle-orm';
const addUserSiteSchema = z.object({
userId: z.string(),
siteId: z.string().transform(Number).pipe(z.number().int().positive()),
siteId: z.string().optional().transform(stoi).pipe(z.number().int().positive().optional()),
});
export async function addUserSite(req: Request, res: Response, next: NextFunction): Promise<any> {

8
server/utils/stoi.ts Normal file
View File

@@ -0,0 +1,8 @@
export default function stoi(val: any) {
if (typeof val === "string") {
return parseInt(val)
}
else {
return val;
}
}