mirror of
https://github.com/fosrl/pangolin.git
synced 2025-08-03 01:24:58 +02:00
move middlewares out of auth
This commit is contained in:
parent
cc674c2b9c
commit
c565c14aa0
15 changed files with 15 additions and 19 deletions
62
server/middlewares/verifyAdmin.ts
Normal file
62
server/middlewares/verifyAdmin.ts
Normal file
|
@ -0,0 +1,62 @@
|
|||
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";
|
||||
|
||||
export async function verifyAdmin(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const userId = req.user?.userId;
|
||||
const orgId = req.userOrgId;
|
||||
|
||||
if (!userId) {
|
||||
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!)))
|
||||
.limit(1);
|
||||
req.userOrg = userOrgRes[0];
|
||||
}
|
||||
|
||||
if (!req.userOrg) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"User does not have access to this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const userRole = await db
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(eq(roles.roleId, req.userOrg.roleId))
|
||||
.limit(1);
|
||||
|
||||
if (userRole.length === 0 || !userRole[0].isAdmin) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"User does not have Admin access"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return next();
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue