fosrl.pangolin/server/routers/auth/getUserOrgs.ts

33 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-10-03 22:31:20 -04:00
import { Request, Response, NextFunction } from 'express';
import { db } from '@server/db';
import { userOrgs, orgs } from '@server/db/schema';
import { eq } from 'drizzle-orm';
import createHttpError from 'http-errors';
import HttpCode from '@server/types/HttpCode';
export async function getUserOrgs(req: Request, res: Response, next: NextFunction) {
2024-10-06 18:05:20 -04:00
const userId = req.user?.id; // 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) {
return next(createHttpError(HttpCode.UNAUTHORIZED, 'User not authenticated'));
}
2024-10-03 22:31:20 -04:00
2024-10-06 18:05:20 -04:00
try {
const userOrganizations = await db.select({
orgId: userOrgs.orgId,
roleId: userOrgs.roleId,
})
.from(userOrgs)
.where(eq(userOrgs.userId, userId));
2024-10-03 22:31:20 -04:00
2024-10-06 18:05:20 -04:00
req.userOrgIds = userOrganizations.map(org => org.orgId);
// 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) {
next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, 'Error retrieving user organizations'));
}
2024-10-03 22:31:20 -04:00
}