more user role stuff

This commit is contained in:
Milo Schwartz 2024-11-09 23:59:19 -05:00
parent bb17d30c9e
commit 231e1d2e2d
No known key found for this signature in database
32 changed files with 897 additions and 138 deletions

View file

@ -9,19 +9,20 @@ import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
const addUserRoleSchema = z.object({
const addUserRoleParamsSchema = z.object({
userId: z.string(),
roleId: z.number().int().positive(),
orgId: z.string(),
});
export type AddUserRoleResponse = z.infer<typeof addUserRoleParamsSchema>;
export async function addUserRole(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedBody = addUserRoleSchema.safeParse(req.body);
const parsedBody = addUserRoleParamsSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
@ -31,7 +32,42 @@ export async function addUserRole(
);
}
const { userId, roleId, orgId } = parsedBody.data;
const { userId, roleId } = parsedBody.data;
if (!req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"You do not have access to this organization"
)
);
}
const orgId = req.userOrg.orgId;
const existingUser = await db
.select()
.from(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.limit(1);
if (existingUser.length === 0) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
"User not found or does not belong to the specified organization"
)
);
}
if (existingUser[0].isOwner) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"Cannot change the role of the owner of the organization"
)
);
}
const roleExists = await db
.select()
@ -59,7 +95,7 @@ export async function addUserRole(
success: true,
error: false,
message: "Role added to user successfully",
status: HttpCode.CREATED,
status: HttpCode.OK,
});
} catch (error) {
logger.error(error);

View file

@ -0,0 +1,120 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { roles, userOrgs, users } from "@server/db/schema";
import { and, eq } from "drizzle-orm";
import response from "@server/utils/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
async function queryUser(orgId: string, userId: string) {
const [user] = await db
.select({
orgId: userOrgs.orgId,
userId: users.userId,
email: users.email,
roleId: userOrgs.roleId,
roleName: roles.name,
isOwner: userOrgs.isOwner,
isAdmin: roles.isAdmin,
})
.from(userOrgs)
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
.leftJoin(users, eq(userOrgs.userId, users.userId))
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.limit(1);
return user;
}
export type GetOrgUserResponse = NonNullable<
Awaited<ReturnType<typeof queryUser>>
>;
const getOrgUserParamsSchema = z.object({
userId: z.string(),
orgId: z.string(),
});
export async function getOrgUser(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = getOrgUserParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { orgId, userId } = parsedParams.data;
if (!req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"You do not have access to this organization"
)
);
}
let user;
user = await queryUser(orgId, userId);
if (!user) {
const [fullUser] = await db
.select()
.from(users)
.where(eq(users.email, userId))
.limit(1);
if (fullUser) {
user = await queryUser(orgId, fullUser.userId);
}
}
if (!user) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`User with ID ${userId} not found in org`
)
);
}
if (user.userId !== req.userOrg.userId) {
const hasPermission = await checkUserActionPermission(
ActionsEnum.getOrgUser,
req
);
if (!hasPermission) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission perform this action"
)
);
}
}
return response<GetOrgUserResponse>(res, {
data: user,
success: true,
error: false,
message: "User retrieved successfully",
status: HttpCode.OK,
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -8,11 +8,23 @@ import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
export type GetUserResponse = {
email: string;
twoFactorEnabled: boolean;
emailVerified: boolean;
};
async function queryUser(userId: string) {
const [user] = await db
.select({
userId: users.userId,
email: users.email,
twoFactorEnabled: users.twoFactorEnabled,
emailVerified: users.emailVerified,
})
.from(users)
.where(eq(users.userId, userId))
.limit(1);
return user;
}
export type GetUserResponse = NonNullable<
Awaited<ReturnType<typeof queryUser>>
>;
export async function getUser(
req: Request,
@ -28,13 +40,9 @@ export async function getUser(
);
}
const user = await db
.select()
.from(users)
.where(eq(users.userId, userId))
.limit(1);
const user = await queryUser(userId);
if (user.length === 0) {
if (!user) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
@ -44,11 +52,7 @@ export async function getUser(
}
return response<GetUserResponse>(res, {
data: {
email: user[0].email,
twoFactorEnabled: user[0].twoFactorEnabled,
emailVerified: user[0].emailVerified,
},
data: user,
success: true,
error: false,
message: "User retrieved successfully",
@ -57,10 +61,7 @@ export async function getUser(
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred..."
)
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -1,6 +1,7 @@
export * from "./getUser";
export * from "./removeUserOrg";
export * from "./listUsers";
export * from "./setUserRole";
export * from "./addUserRole";
export * from "./inviteUser";
export * from "./acceptInvite";
export * from "./acceptInvite";
export * from "./getOrgUser";