fosrl.pangolin/server/middlewares/getUserOrgs.ts

46 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-10-19 16:37:40 -04:00
import { Request, Response, NextFunction } from "express";
import { db } from "@server/db";
2025-03-23 17:11:48 -04:00
import { userOrgs, orgs } from "@server/db/schemas";
2024-10-19 16:37:40 -04:00
import { eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
2024-10-03 22:31:20 -04:00
2024-10-19 16:37:40 -04:00
export async function getUserOrgs(
req: Request,
res: Response,
next: NextFunction,
) {
2024-10-13 17:13:47 -04:00
const userId = req.user?.userId; // Assuming you have user information in the request
2024-10-03 22:31:20 -04:00
2024-10-06 18:05:20 -04:00
if (!userId) {
2024-10-19 16:37:40 -04:00
return next(
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated"),
);
2024-10-06 18:05:20 -04:00
}
2024-10-03 22:31:20 -04:00
2024-10-06 18:05:20 -04:00
try {
2024-10-19 16:37:40 -04:00
const userOrganizations = await db
.select({
orgId: userOrgs.orgId,
roleId: userOrgs.roleId,
})
2024-10-06 18:05:20 -04:00
.from(userOrgs)
.where(eq(userOrgs.userId, userId));
2024-10-03 22:31:20 -04:00
2024-10-19 16:37:40 -04:00
req.userOrgIds = userOrganizations.map((org) => org.orgId);
2024-10-06 18:05:20 -04:00
// req.userOrgRoleIds = userOrganizations.reduce((acc, org) => {
// acc[org.orgId] = org.role;
// return acc;
// }, {} as Record<number, string>);
2024-10-03 22:31:20 -04:00
2024-10-06 18:05:20 -04:00
next();
} catch (error) {
2024-10-19 16:37:40 -04:00
next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Error retrieving user organizations",
),
);
2024-10-06 18:05:20 -04:00
}
2024-10-13 17:13:47 -04:00
}