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

38 lines
1.4 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 } from '@server/db/schema';
import { and, eq } from 'drizzle-orm';
import createHttpError from 'http-errors';
import HttpCode from '@server/types/HttpCode';
import { AuthenticatedRequest } from '@server/types/Auth';
export function verifyOrgAccess(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-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) {
return next(createHttpError(HttpCode.UNAUTHORIZED, 'User not authenticated'));
}
2024-10-03 22:31:20 -04:00
2024-10-14 15:11:18 -04:00
if (!orgId) {
2024-10-06 18:05:20 -04:00
return next(createHttpError(HttpCode.BAD_REQUEST, 'Invalid organization ID'));
}
2024-10-03 22:31:20 -04:00
2024-10-06 18:05:20 -04:00
db.select()
.from(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.then((result) => {
if (result.length === 0) {
next(createHttpError(HttpCode.FORBIDDEN, 'User does not have access to this organization'));
} else {
// User has access, attach the user's role to the request for potential future use
req.userOrgRoleId = result[0].roleId;
req.userOrgId = orgId;
next();
}
})
.catch((error) => {
next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, 'Error verifying organization access'));
});
2024-10-06 09:55:45 -04:00
}