2024-11-03 17:28:12 -05:00
|
|
|
import { Request, Response, NextFunction } from "express";
|
|
|
|
import { db } from "@server/db";
|
|
|
|
import { userOrgs } from "@server/db/schema";
|
|
|
|
import { and, eq } from "drizzle-orm";
|
|
|
|
import createHttpError from "http-errors";
|
|
|
|
import HttpCode from "@server/types/HttpCode";
|
2024-10-03 22:31:20 -04:00
|
|
|
|
2024-11-05 22:38:57 -05:00
|
|
|
export async function verifyOrgAccess(
|
2024-11-03 17:28:12 -05:00
|
|
|
req: Request,
|
|
|
|
res: Response,
|
|
|
|
next: NextFunction
|
|
|
|
) {
|
2024-11-05 22:38:57 -05:00
|
|
|
const userId = req.user!.userId;
|
2024-10-14 15:11:18 -04:00
|
|
|
const orgId = req.params.orgId;
|
2024-10-03 22:31:20 -04:00
|
|
|
|
2024-10-06 18:05:20 -04:00
|
|
|
if (!userId) {
|
2024-11-03 17:28:12 -05: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-14 15:11:18 -04:00
|
|
|
if (!orgId) {
|
2024-11-03 17:28:12 -05:00
|
|
|
return next(
|
|
|
|
createHttpError(HttpCode.BAD_REQUEST, "Invalid organization ID")
|
|
|
|
);
|
2024-10-06 18:05:20 -04:00
|
|
|
}
|
2024-10-03 22:31:20 -04:00
|
|
|
|
2024-11-05 22:38:57 -05:00
|
|
|
try {
|
2024-11-09 23:59:19 -05:00
|
|
|
if (!req.userOrg) {
|
2024-11-05 22:38:57 -05:00
|
|
|
const userOrgRes = await db
|
|
|
|
.select()
|
|
|
|
.from(userOrgs)
|
|
|
|
.where(
|
|
|
|
and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId))
|
2024-11-03 17:28:12 -05:00
|
|
|
);
|
2024-11-09 23:59:19 -05:00
|
|
|
req.userOrg = userOrgRes[0];
|
2024-11-05 22:38:57 -05:00
|
|
|
}
|
|
|
|
|
2024-11-09 23:59:19 -05:00
|
|
|
if (!req.userOrg) {
|
2024-11-03 17:28:12 -05:00
|
|
|
next(
|
|
|
|
createHttpError(
|
2024-11-05 22:38:57 -05:00
|
|
|
HttpCode.FORBIDDEN,
|
|
|
|
"User does not have access to this organization"
|
2024-11-03 17:28:12 -05:00
|
|
|
)
|
|
|
|
);
|
2024-11-05 22:38:57 -05:00
|
|
|
} else {
|
|
|
|
// User has access, attach the user's role to the request for potential future use
|
2024-11-09 23:59:19 -05:00
|
|
|
req.userOrgRoleId = req.userOrg.roleId;
|
2024-11-05 22:38:57 -05:00
|
|
|
req.userOrgId = orgId;
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.INTERNAL_SERVER_ERROR,
|
|
|
|
"Error verifying organization access"
|
|
|
|
)
|
|
|
|
);
|
|
|
|
}
|
2024-10-06 09:55:45 -04:00
|
|
|
}
|