Add role aware updates & endpoints

This commit is contained in:
Owen Schwartz 2024-10-12 21:36:14 -04:00
parent 41cbde1474
commit 364b2c26c3
No known key found for this signature in database
GPG key ID: 8271FDFFD9E0CCBD
49 changed files with 1587 additions and 79 deletions

View file

@ -30,7 +30,7 @@ export async function deleteUser(req: Request, res: Response, next: NextFunction
// Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.deleteUser, req);
if (!hasPermission) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
}
const deletedUser = await db.delete(users)

View file

@ -1,3 +1,5 @@
export * from "./getUser";
export * from "./deleteUser";
export * from "./listUsers";
export * from "./listUsers";
export * from "./listUserRoles";
export * from "./setUserRole";

View file

@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { users } from '@server/db/schema';
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';
@ -10,59 +10,67 @@ import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
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().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 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(', ')
)
);
}
const { limit, offset } = parsedQuery.data;
// Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.listUsers, req);
if (!hasPermission) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
}
const usersList = await db.select()
.from(users)
.limit(limit)
.offset(offset);
const totalCountResult = await db
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(users);
const totalCount = totalCountResult[0].count;
// Remove passwordHash from each user object
const usersWithoutPassword = usersList.map(({ passwordHash, ...userWithoutPassword }) => userWithoutPassword);
return response(res, {
data: {
users: usersWithoutPassword,
pagination: {
total: totalCount,
limit,
offset,
},
},
success: true,
error: false,
message: "Users retrieved successfully",
status: HttpCode.OK,
});
} catch (error) {
logger.error(error);
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
try {
const parsedQuery = listUsersSchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedQuery.error.errors.map(e => e.message).join(', ')
)
);
}
const { limit, offset } = parsedQuery.data;
// Check if the user has permission to list users
const hasPermission = await checkUserActionPermission(ActionsEnum.listUsers, req);
if (!hasPermission) {
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.id,
email: users.email,
emailVerified: users.emailVerified,
dateCreated: users.dateCreated,
orgId: userOrgs.orgId,
roleId: userOrgs.roleId,
roleName: roles.name,
})
.from(users)
.leftJoin(userOrgs, sql`${users.id} = ${userOrgs.userId}`)
.leftJoin(roles, sql`${userOrgs.roleId} = ${roles.roleId}`)
.limit(limit)
.offset(offset);
// Count total users
const [{ count }] = await db
.select({ count: sql<number>`count(*)` })
.from(users);
return response(res, {
data: {
users: usersWithRoles,
pagination: {
total: count,
limit,
offset,
},
},
success: true,
error: false,
message: "Users retrieved successfully",
status: HttpCode.OK,
});
} catch (error) {
logger.error(error);
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
}
}

View file

@ -0,0 +1,64 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { userOrgs, roles } from '@server/db/schema';
import { eq, and } 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';
const addUserRoleSchema = z.object({
userId: z.string(),
roleId: z.number().int().positive(),
orgId: z.number().int().positive(),
});
export async function addUserRole(req: Request, res: Response, next: NextFunction): Promise<any> {
try {
const parsedBody = addUserRoleSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedBody.error.errors.map(e => e.message).join(', ')
)
);
}
const { userId, roleId, orgId } = parsedBody.data;
// Check if the user has permission to add user roles
const hasPermission = await checkUserActionPermission(ActionsEnum.addUserRole, req);
if (!hasPermission) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
}
// Check if the role exists and belongs to the specified org
const roleExists = await db.select()
.from(roles)
.where(and(eq(roles.roleId, roleId), eq(roles.orgId, orgId)))
.limit(1);
if (roleExists.length === 0) {
return next(createHttpError(HttpCode.NOT_FOUND, 'Role not found or does not belong to the specified organization'));
}
const newUserRole = await db.update(userOrgs)
.set({ roleId })
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.returning();
return response(res, {
data: newUserRole[0],
success: true,
error: false,
message: "Role added to user successfully",
status: HttpCode.CREATED,
});
} catch (error) {
logger.error(error);
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
}
}