display users table

This commit is contained in:
Milo Schwartz 2024-11-02 16:12:20 -04:00
parent d6387de21b
commit a83a3e88bb
No known key found for this signature in database
6 changed files with 337 additions and 40 deletions

View file

@ -1,31 +1,69 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { roles, userOrgs, users } from '@server/db/schema';
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { roles, userOrgs, users } from "@server/db/schema";
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
import { sql } 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 } from "drizzle-orm";
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
import logger from "@server/logger";
const listUsersParamsSchema = z.object({
orgId: z.string().optional().transform(Number).pipe(z.number().int().positive()),
orgId: z.string(),
});
const listUsersSchema = 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().nonnegative()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.number().int().nonnegative()),
});
export async function listUsers(req: Request, res: Response, next: NextFunction): Promise<any> {
async function queryUsers(orgId: string, limit: number, offset: number) {
return await db
.select({
id: users.userId,
email: users.email,
emailVerified: users.emailVerified,
dateCreated: users.dateCreated,
orgId: userOrgs.orgId,
roleId: userOrgs.roleId,
roleName: roles.name,
})
.from(users)
.leftJoin(userOrgs, sql`${users.userId} = ${userOrgs.userId}`)
.leftJoin(roles, sql`${userOrgs.roleId} = ${roles.roleId}`)
.where(sql`${userOrgs.orgId} = ${orgId}`)
.limit(limit)
.offset(offset);
}
export type ListUsersResponse = {
users: NonNullable<Awaited<ReturnType<typeof queryUsers>>>;
pagination: { total: number; limit: number; offset: number };
};
export async function listUsers(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = listUsersSchema.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(", ")
)
);
}
@ -36,7 +74,7 @@ export async function listUsers(req: Request, res: Response, next: NextFunction)
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedParams.error.errors.map(e => e.message).join(', ')
parsedParams.error.errors.map((e) => e.message).join(", ")
)
);
}
@ -44,35 +82,31 @@ export async function listUsers(req: Request, res: Response, next: NextFunction)
const { orgId } = parsedParams.data;
// Check if the user has permission to list users
const hasPermission = await checkUserActionPermission(ActionsEnum.listUsers, req);
const hasPermission = await checkUserActionPermission(
ActionsEnum.listUsers,
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"
)
);
}
// Query to join users, userOrgs, and roles tables
const usersWithRoles = await db
.select({
id: users.userId,
email: users.email,
emailVerified: users.emailVerified,
dateCreated: users.dateCreated,
orgId: userOrgs.orgId,
roleId: userOrgs.roleId,
roleName: roles.name,
})
.from(users)
.leftJoin(userOrgs, sql`${users.userId} = ${userOrgs.userId}`)
.leftJoin(roles, sql`${userOrgs.roleId} = ${roles.roleId}`)
.where(sql`${userOrgs.orgId} = ${orgId}`)
.limit(limit)
.offset(offset);
const usersWithRoles = await queryUsers(
orgId.toString(),
limit,
offset
);
// Count total users
const [{ count }] = await db
.select({ count: sql<number>`count(*)` })
.from(users);
return response(res, {
return response<ListUsersResponse>(res, {
data: {
users: usersWithRoles,
pagination: {
@ -88,6 +122,8 @@ export async function listUsers(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")
);
}
}