mirror of
https://github.com/fosrl/pangolin.git
synced 2026-03-06 02:36:38 +00:00
Format files and fix http response
This commit is contained in:
@@ -7,99 +7,98 @@ 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';
|
||||
|
||||
const API_BASE_URL = "http://localhost:3000";
|
||||
|
||||
const createSiteParamsSchema = z.object({
|
||||
const createSiteParamsSchema = z.object({
|
||||
orgId: z.number().int().positive(),
|
||||
});
|
||||
|
||||
// Define Zod schema for request body validation
|
||||
const createSiteSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
subdomain: z.string().min(1).max(255).optional(),
|
||||
pubKey: z.string().optional(),
|
||||
subnet: z.string().optional(),
|
||||
name: z.string().min(1).max(255),
|
||||
subdomain: z.string().min(1).max(255).optional(),
|
||||
pubKey: z.string().optional(),
|
||||
subnet: z.string().optional(),
|
||||
});
|
||||
|
||||
export async function createSite(req: Request, res: Response, next: NextFunction): Promise<any> {
|
||||
try {
|
||||
// Validate request body
|
||||
const parsedBody = createSiteSchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedBody.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
try {
|
||||
// Validate request body
|
||||
const parsedBody = createSiteSchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedBody.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { name, subdomain, pubKey, subnet } = parsedBody.data;
|
||||
|
||||
// Validate request params
|
||||
const parsedParams = createSiteParamsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedParams.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId } = parsedParams.data;
|
||||
|
||||
// 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'));
|
||||
}
|
||||
|
||||
// Create new site in the database
|
||||
const newSite = await db.insert(sites).values({
|
||||
orgId,
|
||||
name,
|
||||
subdomain,
|
||||
pubKey,
|
||||
subnet,
|
||||
}).returning();
|
||||
|
||||
return response(res, {
|
||||
data: newSite[0],
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Site created successfully",
|
||||
status: HttpCode.CREATED,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
|
||||
}
|
||||
|
||||
const { name, subdomain, pubKey, subnet } = parsedBody.data;
|
||||
|
||||
// Validate request params
|
||||
const parsedParams = createSiteParamsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedParams.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId } = parsedParams.data;
|
||||
|
||||
// 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'));
|
||||
}
|
||||
|
||||
// Create new site in the database
|
||||
const newSite = await db.insert(sites).values({
|
||||
orgId,
|
||||
name,
|
||||
subdomain,
|
||||
pubKey,
|
||||
subnet,
|
||||
}).returning();
|
||||
|
||||
return res.status(HttpCode.CREATED).send(
|
||||
response(res, {
|
||||
data: newSite[0],
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Site created successfully",
|
||||
status: HttpCode.CREATED,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function addPeer(peer: string) {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/peer`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(peer),
|
||||
});
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/peer`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(peer),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data: any = await response.json();
|
||||
logger.info('Peer added successfully:', data.status);
|
||||
return data;
|
||||
} catch (error: any) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const data: any = await response.json();
|
||||
console.log('Peer added successfully:', data.status);
|
||||
return data;
|
||||
} catch (error: any) {
|
||||
console.error('Error adding peer:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,80 +7,80 @@ import response from "@server/utils/response";
|
||||
import HttpCode from '@server/types/HttpCode';
|
||||
import createHttpError from 'http-errors';
|
||||
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
|
||||
import logger from '@server/logger';
|
||||
|
||||
|
||||
const API_BASE_URL = "http://localhost:3000";
|
||||
|
||||
// Define Zod schema for request parameters validation
|
||||
const deleteSiteSchema = z.object({
|
||||
siteId: z.string().transform(Number).pipe(z.number().int().positive())
|
||||
siteId: z.string().transform(Number).pipe(z.number().int().positive())
|
||||
});
|
||||
|
||||
export async function deleteSite(req: Request, res: Response, next: NextFunction): Promise<any> {
|
||||
try {
|
||||
// Validate request parameters
|
||||
const parsedParams = deleteSiteSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedParams.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
try {
|
||||
// Validate request parameters
|
||||
const parsedParams = deleteSiteSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedParams.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { siteId } = parsedParams.data;
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(ActionsEnum.deleteSite, req);
|
||||
if (!hasPermission) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
|
||||
}
|
||||
|
||||
// Delete the site from the database
|
||||
const deletedSite = await db.delete(sites)
|
||||
.where(eq(sites.siteId, siteId))
|
||||
.returning();
|
||||
|
||||
if (deletedSite.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Site with ID ${siteId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: null,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Site deleted successfully",
|
||||
status: HttpCode.OK,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
|
||||
}
|
||||
|
||||
const { siteId } = parsedParams.data;
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(ActionsEnum.deleteSite, req);
|
||||
if (!hasPermission) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
|
||||
}
|
||||
|
||||
// Delete the site from the database
|
||||
const deletedSite = await db.delete(sites)
|
||||
.where(eq(sites.siteId, siteId))
|
||||
.returning();
|
||||
|
||||
if (deletedSite.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Site with ID ${siteId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return res.status(HttpCode.OK).send(
|
||||
response(res, {
|
||||
data: null,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Site deleted successfully",
|
||||
status: HttpCode.OK,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function removePeer(publicKey: string) {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/peer?public_key=${encodeURIComponent(publicKey)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/peer?public_key=${encodeURIComponent(publicKey)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Peer removed successfully:', data.status);
|
||||
return data;
|
||||
} catch (error: any) {
|
||||
console.error('Error removing peer:', error.message);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Peer removed successfully:', data.status);
|
||||
return data;
|
||||
} catch (error: any) {
|
||||
console.error('Error removing peer:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,58 +7,58 @@ import response from "@server/utils/response";
|
||||
import HttpCode from '@server/types/HttpCode';
|
||||
import createHttpError from 'http-errors';
|
||||
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
|
||||
import logger from '@server/logger';
|
||||
|
||||
// Define Zod schema for request parameters validation
|
||||
const getSiteSchema = z.object({
|
||||
siteId: z.string().transform(Number).pipe(z.number().int().positive())
|
||||
siteId: z.string().transform(Number).pipe(z.number().int().positive())
|
||||
});
|
||||
|
||||
export async function getSite(req: Request, res: Response, next: NextFunction): Promise<any> {
|
||||
try {
|
||||
// Validate request parameters
|
||||
const parsedParams = getSiteSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedParams.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
try {
|
||||
// Validate request parameters
|
||||
const parsedParams = getSiteSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedParams.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { siteId } = parsedParams.data;
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(ActionsEnum.updateSite, req);
|
||||
if (!hasPermission) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
|
||||
}
|
||||
|
||||
// Fetch the site from the database
|
||||
const site = await db.select()
|
||||
.from(sites)
|
||||
.where(eq(sites.siteId, siteId))
|
||||
.limit(1);
|
||||
|
||||
if (site.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Site with ID ${siteId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: site[0],
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Site retrieved successfully",
|
||||
status: HttpCode.OK,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
|
||||
}
|
||||
|
||||
const { siteId } = parsedParams.data;
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(ActionsEnum.updateSite, req);
|
||||
if (!hasPermission) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
|
||||
}
|
||||
|
||||
// Fetch the site from the database
|
||||
const site = await db.select()
|
||||
.from(sites)
|
||||
.where(eq(sites.siteId, siteId))
|
||||
.limit(1);
|
||||
|
||||
if (site.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Site with ID ${siteId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return res.status(HttpCode.OK).send(
|
||||
response(res, {
|
||||
data: site[0],
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Site retrieved successfully",
|
||||
status: HttpCode.OK,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,101 +7,101 @@ import HttpCode from '@server/types/HttpCode';
|
||||
import createHttpError from 'http-errors';
|
||||
import { sql, eq, and, or, inArray } from 'drizzle-orm';
|
||||
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
|
||||
import logger from '@server/logger';
|
||||
|
||||
const listSitesParamsSchema = z.object({
|
||||
orgId: z.string().optional().transform(Number).pipe(z.number().int().positive()),
|
||||
});
|
||||
|
||||
const listSitesSchema = z.object({
|
||||
limit: z.string().optional().transform(Number).pipe(z.number().int().positive().default(10)),
|
||||
offset: z.string().optional().transform(Number).pipe(z.number().int().nonnegative().default(0)),
|
||||
limit: z.string().optional().transform(Number).pipe(z.number().int().positive().default(10)),
|
||||
offset: z.string().optional().transform(Number).pipe(z.number().int().nonnegative().default(0)),
|
||||
});
|
||||
|
||||
export async function listSites(req: Request, res: Response, next: NextFunction): Promise<any> {
|
||||
try {
|
||||
const parsedQuery = listSitesSchema.safeParse(req.query);
|
||||
if (!parsedQuery.success) {
|
||||
return next(createHttpError(HttpCode.BAD_REQUEST, parsedQuery.error.errors.map(e => e.message).join(', ')));
|
||||
try {
|
||||
const parsedQuery = listSitesSchema.safeParse(req.query);
|
||||
if (!parsedQuery.success) {
|
||||
return next(createHttpError(HttpCode.BAD_REQUEST, parsedQuery.error.errors.map(e => e.message).join(', ')));
|
||||
}
|
||||
const { limit, offset } = parsedQuery.data;
|
||||
|
||||
|
||||
const parsedParams = listSitesParamsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(createHttpError(HttpCode.BAD_REQUEST, parsedParams.error.errors.map(e => e.message).join(', ')));
|
||||
}
|
||||
const { orgId } = parsedParams.data;
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(ActionsEnum.listSites, req);
|
||||
if (!hasPermission) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
|
||||
}
|
||||
|
||||
if (orgId && orgId !== req.userOrgId) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have access to this organization'));
|
||||
}
|
||||
|
||||
const accessibleSites = await db
|
||||
.select({ siteId: sql<number>`COALESCE(${userSites.siteId}, ${roleSites.siteId})` })
|
||||
.from(userSites)
|
||||
.fullJoin(roleSites, eq(userSites.siteId, roleSites.siteId))
|
||||
.where(
|
||||
or(
|
||||
eq(userSites.userId, req.user!.id),
|
||||
eq(roleSites.roleId, req.userOrgRoleId!)
|
||||
)
|
||||
);
|
||||
|
||||
const accessibleSiteIds = accessibleSites.map(site => site.siteId);
|
||||
|
||||
let baseQuery: any = db
|
||||
.select({
|
||||
siteId: sites.siteId,
|
||||
name: sites.name,
|
||||
subdomain: sites.subdomain,
|
||||
pubKey: sites.pubKey,
|
||||
subnet: sites.subnet,
|
||||
megabytesIn: sites.megabytesIn,
|
||||
megabytesOut: sites.megabytesOut,
|
||||
orgName: orgs.name,
|
||||
exitNodeName: exitNodes.name,
|
||||
})
|
||||
.from(sites)
|
||||
.leftJoin(orgs, eq(sites.orgId, orgs.orgId))
|
||||
.where(inArray(sites.siteId, accessibleSiteIds));
|
||||
|
||||
let countQuery: any = db
|
||||
.select({ count: sql<number>`cast(count(*) as integer)` })
|
||||
.from(sites)
|
||||
.where(inArray(sites.siteId, accessibleSiteIds));
|
||||
|
||||
if (orgId) {
|
||||
baseQuery = baseQuery.where(eq(sites.orgId, orgId));
|
||||
countQuery = countQuery.where(eq(sites.orgId, orgId));
|
||||
}
|
||||
|
||||
const sitesList = await baseQuery.limit(limit).offset(offset);
|
||||
const totalCountResult = await countQuery;
|
||||
const totalCount = totalCountResult[0].count;
|
||||
|
||||
return response(res, {
|
||||
data: {
|
||||
sites: sitesList,
|
||||
pagination: {
|
||||
total: totalCount,
|
||||
limit,
|
||||
offset,
|
||||
},
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Sites retrieved successfully",
|
||||
status: HttpCode.OK,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
|
||||
}
|
||||
const { limit, offset } = parsedQuery.data;
|
||||
|
||||
|
||||
const parsedParams = listSitesParamsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(createHttpError(HttpCode.BAD_REQUEST, parsedParams.error.errors.map(e => e.message).join(', ')));
|
||||
}
|
||||
const { orgId } = parsedParams.data;
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(ActionsEnum.listSites, req);
|
||||
if (!hasPermission) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
|
||||
}
|
||||
|
||||
if (orgId && orgId !== req.userOrgId) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have access to this organization'));
|
||||
}
|
||||
|
||||
const accessibleSites = await db
|
||||
.select({ siteId: sql<number>`COALESCE(${userSites.siteId}, ${roleSites.siteId})` })
|
||||
.from(userSites)
|
||||
.fullJoin(roleSites, eq(userSites.siteId, roleSites.siteId))
|
||||
.where(
|
||||
or(
|
||||
eq(userSites.userId, req.user!.id),
|
||||
eq(roleSites.roleId, req.userOrgRoleId!)
|
||||
)
|
||||
);
|
||||
|
||||
const accessibleSiteIds = accessibleSites.map(site => site.siteId);
|
||||
|
||||
let baseQuery: any = db
|
||||
.select({
|
||||
siteId: sites.siteId,
|
||||
name: sites.name,
|
||||
subdomain: sites.subdomain,
|
||||
pubKey: sites.pubKey,
|
||||
subnet: sites.subnet,
|
||||
megabytesIn: sites.megabytesIn,
|
||||
megabytesOut: sites.megabytesOut,
|
||||
orgName: orgs.name,
|
||||
exitNodeName: exitNodes.name,
|
||||
})
|
||||
.from(sites)
|
||||
.leftJoin(orgs, eq(sites.orgId, orgs.orgId))
|
||||
.where(inArray(sites.siteId, accessibleSiteIds));
|
||||
|
||||
let countQuery: any = db
|
||||
.select({ count: sql<number>`cast(count(*) as integer)` })
|
||||
.from(sites)
|
||||
.where(inArray(sites.siteId, accessibleSiteIds));
|
||||
|
||||
if (orgId) {
|
||||
baseQuery = baseQuery.where(eq(sites.orgId, orgId));
|
||||
countQuery = countQuery.where(eq(sites.orgId, orgId));
|
||||
}
|
||||
|
||||
const sitesList = await baseQuery.limit(limit).offset(offset);
|
||||
const totalCountResult = await countQuery;
|
||||
const totalCount = totalCountResult[0].count;
|
||||
|
||||
return res.status(HttpCode.OK).send(
|
||||
response(res, {
|
||||
data: {
|
||||
sites: sitesList,
|
||||
pagination: {
|
||||
total: totalCount,
|
||||
limit,
|
||||
offset,
|
||||
},
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Sites retrieved successfully",
|
||||
status: HttpCode.OK,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -7,83 +7,83 @@ import response from "@server/utils/response";
|
||||
import HttpCode from '@server/types/HttpCode';
|
||||
import createHttpError from 'http-errors';
|
||||
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
|
||||
import logger from '@server/logger';
|
||||
|
||||
// Define Zod schema for request parameters validation
|
||||
const updateSiteParamsSchema = z.object({
|
||||
siteId: z.string().transform(Number).pipe(z.number().int().positive())
|
||||
siteId: z.string().transform(Number).pipe(z.number().int().positive())
|
||||
});
|
||||
|
||||
// Define Zod schema for request body validation
|
||||
const updateSiteBodySchema = z.object({
|
||||
name: z.string().min(1).max(255).optional(),
|
||||
subdomain: z.string().min(1).max(255).optional(),
|
||||
pubKey: z.string().optional(),
|
||||
subnet: z.string().optional(),
|
||||
exitNode: z.number().int().positive().optional(),
|
||||
megabytesIn: z.number().int().nonnegative().optional(),
|
||||
megabytesOut: z.number().int().nonnegative().optional(),
|
||||
name: z.string().min(1).max(255).optional(),
|
||||
subdomain: z.string().min(1).max(255).optional(),
|
||||
pubKey: z.string().optional(),
|
||||
subnet: z.string().optional(),
|
||||
exitNode: z.number().int().positive().optional(),
|
||||
megabytesIn: z.number().int().nonnegative().optional(),
|
||||
megabytesOut: z.number().int().nonnegative().optional(),
|
||||
}).refine(data => Object.keys(data).length > 0, {
|
||||
message: "At least one field must be provided for update"
|
||||
message: "At least one field must be provided for update"
|
||||
});
|
||||
|
||||
export async function updateSite(req: Request, res: Response, next: NextFunction): Promise<any> {
|
||||
try {
|
||||
// Validate request parameters
|
||||
const parsedParams = updateSiteParamsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedParams.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
try {
|
||||
// Validate request parameters
|
||||
const parsedParams = updateSiteParamsSchema.safeParse(req.params);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedParams.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Validate request body
|
||||
const parsedBody = updateSiteBodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedBody.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { siteId } = parsedParams.data;
|
||||
const updateData = parsedBody.data;
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(ActionsEnum.updateSite, req);
|
||||
if (!hasPermission) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
|
||||
}
|
||||
|
||||
// Update the site in the database
|
||||
const updatedSite = await db.update(sites)
|
||||
.set(updateData)
|
||||
.where(eq(sites.siteId, siteId))
|
||||
.returning();
|
||||
|
||||
if (updatedSite.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Site with ID ${siteId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: updatedSite[0],
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Site updated successfully",
|
||||
status: HttpCode.OK,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
|
||||
}
|
||||
|
||||
// Validate request body
|
||||
const parsedBody = updateSiteBodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
parsedBody.error.errors.map(e => e.message).join(', ')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { siteId } = parsedParams.data;
|
||||
const updateData = parsedBody.data;
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(ActionsEnum.updateSite, req);
|
||||
if (!hasPermission) {
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to list sites'));
|
||||
}
|
||||
|
||||
// Update the site in the database
|
||||
const updatedSite = await db.update(sites)
|
||||
.set(updateData)
|
||||
.where(eq(sites.siteId, siteId))
|
||||
.returning();
|
||||
|
||||
if (updatedSite.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Site with ID ${siteId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return res.status(HttpCode.OK).send(
|
||||
response(res, {
|
||||
data: updatedSite[0],
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Site updated successfully",
|
||||
status: HttpCode.OK,
|
||||
})
|
||||
);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user