fosrl.pangolin/server/middlewares/verifyUserAccess.ts

60 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2024-11-03 17:28:12 -05:00
import { Request, Response, NextFunction } from "express";
import { db } from "@server/db";
2025-06-04 12:02:07 -04:00
import { userOrgs } from "@server/db";
2024-11-03 17:28:12 -05:00
import { and, eq, or } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
export async function verifyUserAccess(
req: Request,
res: Response,
next: NextFunction
) {
const userId = req.user!.userId;
2024-10-12 22:31:24 -04:00
const reqUserId = req.params.userId || req.body.userId || req.query.userId;
if (!userId) {
2024-11-03 17:28:12 -05:00
return next(
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated")
);
2024-10-12 22:31:24 -04:00
}
if (!reqUserId) {
2024-11-03 17:28:12 -05:00
return next(createHttpError(HttpCode.BAD_REQUEST, "Invalid user ID"));
2024-10-12 22:31:24 -04:00
}
try {
2024-11-09 23:59:19 -05:00
if (!req.userOrg) {
const res = await db
.select()
.from(userOrgs)
.where(
and(
eq(userOrgs.userId, reqUserId),
eq(userOrgs.orgId, req.userOrgId!)
)
2024-11-03 17:28:12 -05:00
)
.limit(1);
2024-11-09 23:59:19 -05:00
req.userOrg = res[0];
}
2024-10-12 22:31:24 -04:00
2024-11-10 21:19:41 -05:00
if (!req.userOrg) {
2024-11-03 17:28:12 -05:00
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have access to this user"
)
);
2024-10-12 22:31:24 -04:00
}
2024-11-03 17:28:12 -05:00
return next();
2024-10-12 22:31:24 -04:00
} catch (error) {
2024-11-03 17:28:12 -05:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Error checking if user has access to this user"
)
);
2024-10-12 22:31:24 -04:00
}
2024-10-13 17:13:47 -04:00
}