fosrl.pangolin/server/middlewares/verifyUserIsOrgOwner.ts

69 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Request, Response, NextFunction } from "express";
import { db } from "@server/db";
2025-06-04 12:02:07 -04:00
import { userOrgs } from "@server/db";
import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
export async function verifyUserIsOrgOwner(
req: Request,
res: Response,
next: NextFunction
) {
const userId = req.user!.userId;
const orgId = req.params.orgId;
if (!userId) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated")
);
}
if (!orgId) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Organization ID not provided"
)
);
}
try {
2024-11-09 23:59:19 -05:00
if (!req.userOrg) {
const res = await db
.select()
.from(userOrgs)
.where(
and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId))
);
2024-11-09 23:59:19 -05:00
req.userOrg = res[0];
}
2024-11-09 23:59:19 -05:00
if (!req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have access to this organization"
)
);
}
2024-11-09 23:59:19 -05:00
if (!req.userOrg.isOwner) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User is not an organization owner"
)
);
}
2025-03-23 17:11:48 -04:00
2024-12-24 12:08:31 -05:00
return next();
} catch (e) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Error verifying organization access"
)
);
}
}