Add role aware updates & endpoints

This commit is contained in:
Owen Schwartz
2024-10-12 21:36:14 -04:00
parent 41cbde1474
commit 364b2c26c3
49 changed files with 1587 additions and 79 deletions

View File

@@ -1,13 +1,14 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { sites } from '@server/db/schema';
import { roles, userSites, sites, roleSites } from '@server/db/schema';
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
import fetch from 'node-fetch';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
import { eq, and } from 'drizzle-orm';
const API_BASE_URL = "http://localhost:3000";
@@ -54,7 +55,11 @@ export async function createSite(req: Request, res: Response, next: NextFunction
// Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.createSite, req);
if (!hasPermission) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission perform this action'));
}
if (!req.userOrgRoleId) {
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have a role'));
}
// Create new site in the database
@@ -65,7 +70,34 @@ export async function createSite(req: Request, res: Response, next: NextFunction
pubKey,
subnet,
}).returning();
// find the superuser roleId and also add the resource to the superuser role
const superuserRole = await db.select()
.from(roles)
.where(and(eq(roles.isSuperuserRole, true), eq(roles.orgId, orgId)))
.limit(1);
if (superuserRole.length === 0) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Superuser role not found`
)
);
}
await db.insert(roleSites).values({
roleId: superuserRole[0].roleId,
siteId: newSite[0].siteId,
});
if (req.userOrgRoleId != superuserRole[0].roleId) {
// make sure the user can access the site
db.insert(userSites).values({
userId: req.user?.id!,
siteId: newSite[0].siteId,
});
}
return response(res, {
data: newSite[0],
success: true,