fosrl.pangolin/server/routers/site/listSites.ts

167 lines
4.9 KiB
TypeScript
Raw Normal View History

2024-10-14 21:54:43 -04:00
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
import { db } from "@server/db";
import {
orgs,
roleSites,
sites,
userSites,
} from "@server/db/schema";
import HttpCode from "@server/types/HttpCode";
2024-10-02 21:17:38 -04:00
import response from "@server/utils/response";
2024-10-14 21:54:43 -04:00
import { and, eq, inArray, or, 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";
2024-10-02 21:17:38 -04:00
2024-10-02 22:05:21 -04:00
const listSitesParamsSchema = z.object({
2024-10-14 21:54:43 -04:00
orgId: z.string(),
2024-10-02 22:05:21 -04:00
});
2024-10-02 21:17:38 -04:00
const listSitesSchema = z.object({
2024-10-14 21:54:43 -04:00
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()),
2024-10-02 21:17:38 -04:00
});
2024-10-14 21:54:43 -04:00
function querySites(orgId: string, accessibleSiteIds: number[]) {
return db
.select({
siteId: sites.siteId,
name: sites.name,
subdomain: sites.subdomain,
pubKey: sites.pubKey,
subnet: sites.subnet,
megabytesIn: sites.megabytesIn,
megabytesOut: sites.megabytesOut,
orgName: orgs.name,
})
.from(sites)
.leftJoin(orgs, eq(sites.orgId, orgs.orgId))
.where(
and(
inArray(sites.siteId, accessibleSiteIds),
eq(sites.orgId, orgId),
),
);
}
export type ListSitesResponse = {
sites: Awaited<ReturnType<typeof querySites>>;
pagination: { total: number; limit: number; offset: number };
};
export async function listSites(
req: Request,
res: Response,
next: NextFunction,
): Promise<any> {
2024-10-06 18:05:20 -04:00
try {
const parsedQuery = listSitesSchema.safeParse(req.query);
if (!parsedQuery.success) {
2024-10-14 21:54:43 -04:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error),
),
);
2024-10-06 18:05:20 -04:00
}
const { limit, offset } = parsedQuery.data;
2024-10-02 22:05:21 -04:00
2024-10-06 18:05:20 -04:00
const parsedParams = listSitesParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
2024-10-14 21:54:43 -04:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedParams.error.errors.map((e) => e.message).join(", "),
),
);
2024-10-06 18:05:20 -04:00
}
const { orgId } = parsedParams.data;
2024-10-02 22:05:21 -04:00
2024-10-06 18:05:20 -04:00
// Check if the user has permission to list sites
2024-10-14 21:54:43 -04:00
const hasPermission = await checkUserActionPermission(
ActionsEnum.listSites,
req,
);
2024-10-06 18:05:20 -04:00
if (!hasPermission) {
2024-10-14 21:54:43 -04:00
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission to perform this action",
),
);
2024-10-06 18:05:20 -04:00
}
2024-10-02 21:17:38 -04:00
2024-10-06 18:05:20 -04:00
if (orgId && orgId !== req.userOrgId) {
2024-10-14 21:54:43 -04:00
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have access to this organization",
),
);
2024-10-06 18:05:20 -04:00
}
2024-10-02 21:17:38 -04:00
2024-10-06 18:05:20 -04:00
const accessibleSites = await db
2024-10-14 21:54:43 -04:00
.select({
siteId: sql<number>`COALESCE(${userSites.siteId}, ${roleSites.siteId})`,
})
2024-10-06 18:05:20 -04:00
.from(userSites)
.fullJoin(roleSites, eq(userSites.siteId, roleSites.siteId))
.where(
or(
2024-10-13 17:13:47 -04:00
eq(userSites.userId, req.user!.userId),
2024-10-14 21:54:43 -04:00
eq(roleSites.roleId, req.userOrgRoleId!),
),
2024-10-06 18:05:20 -04:00
);
2024-10-02 21:17:38 -04:00
2024-10-14 21:54:43 -04:00
const accessibleSiteIds = accessibleSites.map((site) => site.siteId);
const baseQuery = querySites(orgId, accessibleSiteIds);
2024-10-02 21:17:38 -04:00
2024-10-14 21:54:43 -04:00
let countQuery = db
2024-10-06 18:05:20 -04:00
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(sites)
2024-10-14 21:54:43 -04:00
.where(
and(
inArray(sites.siteId, accessibleSiteIds),
eq(sites.orgId, orgId),
),
);
2024-10-06 18:05:20 -04:00
const sitesList = await baseQuery.limit(limit).offset(offset);
const totalCountResult = await countQuery;
const totalCount = totalCountResult[0].count;
2024-10-14 21:54:43 -04:00
return response<ListSitesResponse>(res, {
2024-10-06 18:05:20 -04:00
data: {
sites: sitesList,
pagination: {
total: totalCount,
limit,
offset,
},
},
success: true,
error: false,
message: "Sites retrieved successfully",
status: HttpCode.OK,
});
} catch (error) {
2024-10-14 21:54:43 -04:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred...",
),
);
2024-10-06 18:05:20 -04:00
}
2024-10-13 17:13:47 -04:00
}