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

51 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-10-12 21:36:14 -04:00
import { Request, Response, NextFunction } from 'express';
import { db } from '@server/db';
import { roles, userOrgs } from '@server/db/schema';
import { and, eq } from 'drizzle-orm';
import createHttpError from 'http-errors';
import HttpCode from '@server/types/HttpCode';
import logger from '@server/logger';
export async function verifyRoleAccess(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-12 21:36:14 -04:00
const roleId = parseInt(req.params.roleId || req.body.roleId || req.query.roleId);
if (!userId) {
return next(createHttpError(HttpCode.UNAUTHORIZED, 'User not authenticated'));
}
if (isNaN(roleId)) {
return next(createHttpError(HttpCode.BAD_REQUEST, 'Invalid role ID'));
}
try {
// Check if the role exists and belongs to the specified organization
const role = await db.select()
.from(roles)
.where(eq(roles.roleId, roleId))
.limit(1);
if (role.length === 0) {
return next(createHttpError(HttpCode.NOT_FOUND, `Role with ID ${roleId} not found`));
}
// Check if the user has a role in the organization
const userOrgRole = await db.select()
.from(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, role[0].orgId!)))
.limit(1);
if (userOrgRole.length === 0) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have access to this organization'));
}
req.userOrgRoleId = userOrgRole[0].roleId;
req.userOrgId = userOrgRole[0].orgId;
return next();
} catch (error) {
logger.error('Error verifying role access:', error);
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, 'Error verifying role access'));
}
2024-10-13 17:13:47 -04:00
}