import checkUserAccess from "@/src/functions/backend/auth/check-user-access"; import userAuth from "@/src/functions/backend/auth/user-auth"; import issueCertificate from "@/src/functions/backend/acme/issue-certificate"; import type { BUN_SQLITE_WGUI_CLIENT_ROUTES } from "@/db/types/db"; import BunSQLite from "@moduletrace/bun-sqlite"; import type { ApiReqParams, TableType } from "@/src/types"; import type { APIResponseObject, BunextAPIRouteHandler, } from "@moduletrace/bunext/types"; export const handler: BunextAPIRouteHandler = async ({ req, body, }) => { if (req.method !== "POST") { return { success: false }; } const { user, user_types } = await userAuth({ req }); if (!user?.logged_in_status) { return { success: false, msg: `Unauthorized`, logoutUser: true, }; } const is_admin = checkUserAccess({ user_types, includes: ["admin"], }); if (!is_admin.success) { return { success: false, msg: `Unauthorized` }; } const payload = body as | (ApiReqParams & { route_id?: number | ""; hostname?: string; staging?: boolean; force?: boolean; }) | undefined; let route: BUN_SQLITE_WGUI_CLIENT_ROUTES | undefined; if (payload?.route_id !== undefined && payload.route_id !== "") { const route_res = await BunSQLite.select< BUN_SQLITE_WGUI_CLIENT_ROUTES, TableType >({ table: "client_routes", targetId: payload.route_id, }); route = route_res.singleRes || undefined; } else if (payload?.hostname) { const route_res = await BunSQLite.select< BUN_SQLITE_WGUI_CLIENT_ROUTES, TableType >({ table: "client_routes", query: { query: { hostname: { value: payload.hostname.trim().toLowerCase(), }, }, }, }); route = route_res.singleRes || undefined; } if (!route || typeof route.id !== "number") { return { success: false, msg: `Route not found` }; } const is_super_admin = checkUserAccess({ user_types }).success; if (!is_super_admin && route.user_id != user.id) { return { success: false, msg: `Unauthorized` }; } return await issueCertificate({ route, route_id: route.id, hostname: route.hostname, user_id: user.id, staging: payload?.staging, force: Boolean(payload?.force), }); };