64 lines
1.6 KiB
TypeScript
64 lines
1.6 KiB
TypeScript
import { Request, Response, NextFunction } from "express";
|
|
import { db } from "@server/db";
|
|
import { roles, userOrgs } from "@server/db/schemas";
|
|
import { and, eq, inArray } from "drizzle-orm";
|
|
import createHttpError from "http-errors";
|
|
import HttpCode from "@server/types/HttpCode";
|
|
|
|
export async function verifyAdmin(
|
|
req: Request,
|
|
res: Response,
|
|
next: NextFunction
|
|
) {
|
|
const userId = req.user?.userId;
|
|
const orgId = req.userOrgId;
|
|
|
|
if (!orgId) {
|
|
return next(
|
|
createHttpError(HttpCode.UNAUTHORIZED, "User does not have orgId")
|
|
);
|
|
}
|
|
|
|
if (!userId) {
|
|
return next(
|
|
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated")
|
|
);
|
|
}
|
|
|
|
if (!req.userOrg) {
|
|
const userOrgRes = await db
|
|
.select()
|
|
.from(userOrgs)
|
|
.where(
|
|
and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId!))
|
|
);
|
|
req.userOrg = userOrgRes[0];
|
|
req.userRoleIds = userOrgRes.map((r) => r.roleId);
|
|
}
|
|
|
|
if (!req.userOrg) {
|
|
return next(
|
|
createHttpError(
|
|
HttpCode.FORBIDDEN,
|
|
"User does not have access to this organization"
|
|
)
|
|
);
|
|
}
|
|
|
|
const userAdminRole = await db
|
|
.select()
|
|
.from(roles)
|
|
.where(and(inArray(roles.roleId, req.userRoleIds!), roles.isAdmin))
|
|
.limit(1);
|
|
|
|
if (userAdminRole.length === 0) {
|
|
return next(
|
|
createHttpError(
|
|
HttpCode.FORBIDDEN,
|
|
"User does not have Admin access"
|
|
)
|
|
);
|
|
}
|
|
|
|
return next();
|
|
}
|