mirror of
https://github.com/fosrl/pangolin.git
synced 2025-08-31 15:09:39 +02:00
Add verify middleware
This commit is contained in:
parent
e89ee4042a
commit
a8f944fc78
17 changed files with 1230 additions and 40 deletions
36
server/routers/auth/verifyOrgAccess.ts
Normal file
36
server/routers/auth/verifyOrgAccess.ts
Normal file
|
@ -0,0 +1,36 @@
|
|||
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) {
|
||||
const userId = req.user.id; // Assuming you have user information in the request
|
||||
const orgId = parseInt(req.params.orgId);
|
||||
|
||||
if (!userId) {
|
||||
return next(createHttpError(HttpCode.UNAUTHORIZED, 'User not authenticated'));
|
||||
}
|
||||
|
||||
if (isNaN(orgId)) {
|
||||
return next(createHttpError(HttpCode.BAD_REQUEST, 'Invalid organization ID'));
|
||||
}
|
||||
|
||||
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.userOrgRole = result[0].role;
|
||||
next();
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, 'Error verifying organization access'));
|
||||
});
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue