show resources table, check org access, and handle redirects on root

This commit is contained in:
Milo Schwartz 2024-10-19 15:49:16 -04:00
parent edde7a247a
commit f6c7c017cb
No known key found for this signature in database
14 changed files with 416 additions and 95 deletions

View file

@ -91,7 +91,6 @@ declare global {
interface Request {
user?: User;
userOrgRoleId?: number;
orgId?: string;
userOrgId?: string;
userOrgIds?: string[];
}

View file

@ -1,39 +1,56 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { orgs } from '@server/db/schema';
import { eq } from 'drizzle-orm';
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { Org, orgs } from "@server/db/schema";
import { eq } from "drizzle-orm";
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
import logger from "@server/logger";
const getOrgSchema = z.object({
orgId: z.string()
orgId: z.string(),
});
export async function getOrg(req: Request, res: Response, next: NextFunction): Promise<any> {
export type GetOrgResponse = {
org: Org;
}
export async function getOrg(
req: Request,
res: Response,
next: NextFunction,
): Promise<any> {
try {
const parsedParams = getOrgSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedParams.error.errors.map(e => e.message).join(', ')
)
parsedParams.error.errors.map((e) => e.message).join(", "),
),
);
}
const { orgId } = parsedParams.data;
// Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.getOrg, req);
const hasPermission = await checkUserActionPermission(
ActionsEnum.getOrg,
req,
);
if (!hasPermission) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission to perform this action",
),
);
}
const org = await db.select()
const org = await db
.select()
.from(orgs)
.where(eq(orgs.orgId, orgId))
.limit(1);
@ -42,13 +59,15 @@ export async function getOrg(req: Request, res: Response, next: NextFunction): P
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Organization with ID ${orgId} not found`
)
`Organization with ID ${orgId} not found`,
),
);
}
return response(res, {
data: org[0],
return response<GetOrgResponse>(res, {
data: {
org: org[0],
},
success: true,
error: false,
message: "Organization retrieved successfully",
@ -56,6 +75,11 @@ export async function getOrg(req: Request, res: Response, next: NextFunction): P
});
} 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

@ -1,79 +1,98 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { orgs } from '@server/db/schema';
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { Org, orgs } from "@server/db/schema";
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
import { sql, inArray } from 'drizzle-orm';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import { sql, inArray } from "drizzle-orm";
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
import logger from "@server/logger";
const listOrgsSchema = 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()
.transform(Number)
.pipe(z.number().int().positive().default(10)),
offset: z
.string()
.optional()
.transform(Number)
.pipe(z.number().int().nonnegative().default(0)),
});
export async function listOrgs(req: Request, res: Response, next: NextFunction): Promise<any> {
export type ListOrgsResponse = {
organizations: Org[];
pagination: { total: number; limit: number; offset: number };
};
export async function listOrgs(
req: Request,
res: Response,
next: NextFunction,
): Promise<any> {
try {
const parsedQuery = listOrgsSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedQuery.error.errors.map(e => e.message).join(', ')
)
parsedQuery.error.errors.map((e) => e.message).join(", "),
),
);
}
const { limit, offset } = parsedQuery.data;
// Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.listOrgs, req);
const hasPermission = await checkUserActionPermission(
ActionsEnum.listOrgs,
req,
);
if (!hasPermission) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission to perform this action",
),
);
}
// Use the userOrgs passed from the middleware
const userOrgIds = req.userOrgIds;
if (!userOrgIds || userOrgIds.length === 0) {
return res.status(HttpCode.OK).send(
response(res, {
data: {
organizations: [],
pagination: {
total: 0,
limit,
offset,
},
return response<ListOrgsResponse>(res, {
data: {
organizations: [],
pagination: {
total: 0,
limit,
offset,
},
success: true,
error: false,
message: "No organizations found for the user",
status: HttpCode.OK,
})
);
},
success: true,
error: false,
message: "No organizations found for the user",
status: HttpCode.OK,
});
}
const organizations = await db.select()
const organizations = await db
.select()
.from(orgs)
.where(inArray(orgs.orgId, userOrgIds))
.limit(limit)
.offset(offset);
const totalCountResult = await db.select({ count: sql<number>`cast(count(*) as integer)` })
const totalCountResult = await db
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(orgs)
.where(inArray(orgs.orgId, userOrgIds));
const totalCount = totalCountResult[0].count;
// // Add the user's role for each organization
// const organizationsWithRoles = organizations.map(org => ({
// ...org,
// userRole: req.userOrgRoleIds[org.orgId],
// }));
return response(res, {
return response<ListOrgsResponse>(res, {
data: {
organizations,
pagination: {
@ -89,6 +108,11 @@ export async function listOrgs(req: Request, res: Response, next: NextFunction):
});
} 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

@ -79,7 +79,7 @@ function queryResources(
}
}
export type ListSitesResponse = {
export type ListResourcesResponse = {
resources: NonNullable<Awaited<ReturnType<typeof queryResources>>>;
pagination: { total: number; limit: number; offset: number };
};
@ -126,7 +126,7 @@ export async function listResources(
);
}
if (orgId && orgId !== req.orgId) {
if (orgId && orgId !== req.userOrgId) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
@ -167,7 +167,7 @@ export async function listResources(
const totalCountResult = await countQuery;
const totalCount = totalCountResult[0].count;
return response<ListSitesResponse>(res, {
return response<ListResourcesResponse>(res, {
data: {
resources: resourcesList,
pagination: {