refactor: edit API

This commit is contained in:
Ravinou 2025-03-24 20:45:19 +01:00
commit b7d3aec3b1
No known key found for this signature in database
GPG key ID: EEEE670C40F6A4D7
10 changed files with 172 additions and 187 deletions

View file

@ -5,7 +5,7 @@ import { promisify } from 'util';
import ApiResponse from '~/helpers/functions/apiResponse';
import { getRepoList, getUsersList, updateRepoList } from '~/helpers/functions/fileHelpers';
import nodemailerSMTP from '~/helpers/functions/nodemailerSMTP';
import { getLastSaveList } from '~/helpers/functions/shell.utils';
import { getLastSaveListShell } from '~/helpers/functions/shell.utils';
import emailAlertStatus from '~/helpers/templates/emailAlertStatus';
import { BorgWarehouseApiResponse } from '~/types/api/error.types';
@ -28,7 +28,7 @@ export default async function handler(
try {
const repoList = await getRepoList();
const lastSaveList = await getLastSaveList();
const lastSaveList = await getLastSaveListShell();
if (repoList.length === 0 || lastSaveList.length === 0) {
return ApiResponse.success(res, 'Status cron executed. No repository to check.');
}

View file

@ -1,7 +1,7 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { getRepoList, updateRepoList } from '~/helpers/functions';
import ApiResponse from '~/helpers/functions/apiResponse';
import { getStorageUsed } from '~/helpers/functions/shell.utils';
import { getStorageUsedShell } from '~/helpers/functions/shell.utils';
import { BorgWarehouseApiResponse } from '~/types/api/error.types';
export default async function handler(
@ -26,7 +26,7 @@ export default async function handler(
return ApiResponse.success(res, 'Storage cron executed. No repository to check.');
}
const storageUsed = await getStorageUsed();
const storageUsed = await getStorageUsedShell();
//Update the storageUsed value of each repository
const updatedRepoList = repoList.map((repo) => {

View file

@ -1,7 +1,7 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { getServerSession } from 'next-auth/next';
import { getRepoList, updateRepoList, tokenController } from '~/helpers/functions';
import { deleteRepo } from '~/helpers/functions/shell.utils';
import { deleteRepoShell } from '~/helpers/functions/shell.utils';
import ApiResponse from '~/helpers/functions/apiResponse';
import { BorgWarehouseApiResponse } from '~/types/api/error.types';
@ -52,7 +52,7 @@ export default async function handler(
return ApiResponse.notFound(res, 'Repository not found');
}
const { stderr } = await deleteRepo(repoList[indexToDelete].repositoryName);
const { stderr } = await deleteRepoShell(repoList[indexToDelete].repositoryName);
if (stderr) {
console.log('Delete repository error: ', stderr);

View file

@ -1,157 +0,0 @@
import { promises as fs } from 'fs';
import path from 'path';
import { authOptions } from '../../../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
import { alertOptions } from '../../../../../domain/constants';
import repoHistory from '../../../../../helpers/functions/repoHistory';
import tokenController from '../../../../../helpers/functions/tokenController';
import isSshPubKeyDuplicate from '../../../../../helpers/functions/isSshPubKeyDuplicate';
const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
export default async function handler(req, res) {
if (req.method !== 'PATCH') {
return res.status(405).json({ status: 405, message: 'Method Not Allowed' });
}
// AUTHENTICATION
const FROM_IP = req.headers['x-forwarded-for'] || 'unknown';
const session = await getServerSession(req, res, authOptions);
const { authorization } = req.headers;
if (!(await isAuthenticated(session, authorization, FROM_IP))) {
res.status(401).json({ message: 'Invalid API key' });
return;
}
// DATA CONTROL
const { alias, sshPublicKey, storageSize, comment, alert, lanCommand, appendOnlyMode } = req.body;
if (!isValidPatchData(req.body)) {
return res.status(422).json({ message: 'Unexpected data' });
}
try {
const repoList = await getRepoList();
const repoId = parseInt(req.query.slug);
const filteredRepoList = repoList.filter((repo) => repo.id !== repoId);
if (isSshKeyConflict(sshPublicKey, filteredRepoList)) {
return res.status(409).json({
message:
'The SSH key is already used in another repository. Please use another key or delete the key from the other repository.',
});
}
const repoIndex = repoList.findIndex((repo) => repo.id === repoId);
await updateRepoShell(repoList[repoIndex], sshPublicKey, storageSize, appendOnlyMode);
const newRepoList = updateRepoList(repoList, req.query.slug, {
alias,
sshPublicKey,
storageSize,
comment,
alert,
lanCommand,
appendOnlyMode,
});
await saveRepoList(newRepoList);
return res.status(200).json({ message: 'success' });
} catch (error) {
handleError(error, res);
}
}
// --------------
// Functions
// --------------
async function isAuthenticated(session, authorization, FROM_IP) {
if (session) return true;
if (authorization) {
const API_KEY = authorization.split(' ')[1];
const permissions = await tokenController(API_KEY, FROM_IP);
return permissions?.update;
}
return false;
}
function isValidPatchData(body) {
const { alias, sshPublicKey, storageSize, comment, alert, lanCommand, appendOnlyMode } = body;
const expectedKeys = [
'alias',
'sshPublicKey',
'storageSize',
'comment',
'alert',
'lanCommand',
'appendOnlyMode',
];
const hasAtLeastOneKey = expectedKeys.some((key) => body.hasOwnProperty(key));
const hasUnexpectedKeys = Object.keys(body).some((key) => !expectedKeys.includes(key));
return (
hasAtLeastOneKey &&
!hasUnexpectedKeys &&
(typeof alias === 'undefined' || (typeof alias === 'string' && alias.trim() !== '')) &&
(typeof sshPublicKey === 'undefined' ||
(typeof sshPublicKey === 'string' && sshPublicKey.trim() !== '')) &&
(typeof comment === 'undefined' || typeof comment === 'string') &&
(typeof storageSize === 'undefined' ||
(typeof storageSize === 'number' && Number.isInteger(storageSize) && storageSize > 0)) &&
(typeof alert === 'undefined' ||
(typeof alert === 'number' && alertOptions.some((option) => option.value === alert))) &&
(typeof lanCommand === 'undefined' || typeof lanCommand === 'boolean') &&
(typeof appendOnlyMode === 'undefined' || typeof appendOnlyMode === 'boolean')
);
}
async function getRepoList() {
const jsonDirectory = path.join(process.cwd(), '/config');
const repoData = await fs.readFile(jsonDirectory + '/repo.json', 'utf8');
return JSON.parse(repoData);
}
function isSshKeyConflict(sshPublicKey, repoList) {
return typeof sshPublicKey === 'string' && isSshPubKeyDuplicate(sshPublicKey, repoList);
}
async function updateRepoShell(repo, sshPublicKey, storageSize, appendOnlyMode) {
const shellsDirectory = path.join(process.cwd(), '/helpers');
await exec(
`${shellsDirectory}/shells/updateRepo.sh ${repo.repositoryName} "${sshPublicKey ?? repo.sshPublicKey}" ${storageSize ?? repo.storageSize} ${appendOnlyMode ?? repo.appendOnlyMode}`
);
}
function updateRepoList(repoList, slug, updates) {
return repoList.map((repo) =>
repo.id == slug
? {
...repo,
alias: updates.alias ?? repo.alias,
sshPublicKey: updates.sshPublicKey ?? repo.sshPublicKey,
storageSize:
updates.storageSize !== undefined ? Number(updates.storageSize) : repo.storageSize,
comment: updates.comment ?? repo.comment,
alert: updates.alert ?? repo.alert,
lanCommand: updates.lanCommand ?? repo.lanCommand,
appendOnlyMode: updates.appendOnlyMode ?? repo.appendOnlyMode,
}
: repo
);
}
async function saveRepoList(newRepoList) {
const jsonDirectory = path.join(process.cwd(), '/config');
await repoHistory(newRepoList);
await fs.writeFile(jsonDirectory + '/repo.json', JSON.stringify(newRepoList));
}
function handleError(error, res) {
console.log(error);
if (error.code == 'ENOENT') {
res.status(500).json({ message: 'No such file or directory' });
} else {
res.status(500).json({ message: error.stdout });
}
}

View file

@ -0,0 +1,127 @@
import { promises as fs } from 'fs';
import path from 'path';
import { authOptions } from '../../../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
import { alertOptions } from '~/types/domain/constants';
import {
getRepoList,
updateRepoList,
tokenController,
isSshPubKeyDuplicate,
} from '~/helpers/functions';
import { NextApiRequest, NextApiResponse } from 'next';
import ApiResponse from '~/helpers/functions/apiResponse';
import { Repository } from '~/types/domain/config.types';
import { updateRepoShell } from '~/helpers/functions/shell.utils';
const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
export default async function handler(
req: NextApiRequest & { body: Partial<Repository> },
res: NextApiResponse
) {
if (req.method !== 'PATCH') {
return ApiResponse.methodNotAllowed(res);
}
// AUTHENTICATION
const session = await getServerSession(req, res, authOptions);
const { authorization } = req.headers;
if (!session && !authorization) {
return ApiResponse.unauthorized(res);
}
try {
if (!session && authorization) {
const permissions = await tokenController(req.headers);
if (!permissions) {
return ApiResponse.unauthorized(res, 'Invalid API key');
}
if (!permissions.update) {
return ApiResponse.forbidden(res, 'Insufficient permissions');
}
}
} catch (error) {
return ApiResponse.serverError(res);
}
dataHandler(req, res);
try {
const { alias, sshPublicKey, storageSize, comment, alert, lanCommand, appendOnlyMode } =
req.body;
const slug = req.query.slug;
const repoList = await getRepoList();
const repoId = parseInt(slug as string, 10);
const repo = repoList.find((repo) => repo.id === repoId);
if (!repo) {
return ApiResponse.notFound(res, 'Repository not found');
}
const filteredRepoList = repoList.filter((repo) => repo.id !== repoId);
if (sshPublicKey && isSshPubKeyDuplicate(sshPublicKey, filteredRepoList)) {
return res.status(409).json({
message:
'The SSH key is already used in another repository. Please use another key or delete the key from the other repository.',
});
}
const updatedRepo: Repository = {
...repo,
alias: alias ?? repo.alias,
sshPublicKey: sshPublicKey ?? repo.sshPublicKey,
storageSize: storageSize ?? repo.storageSize,
comment: comment ?? repo.comment,
alert: alert ?? repo.alert,
lanCommand: lanCommand ?? repo.lanCommand,
appendOnlyMode: appendOnlyMode ?? repo.appendOnlyMode,
};
const { stderr } = await updateRepoShell(
updatedRepo.repositoryName,
updatedRepo.sshPublicKey,
updatedRepo.storageSize,
updatedRepo.appendOnlyMode ?? false
);
if (stderr) {
console.log('Update repository error: ', stderr);
return ApiResponse.serverError(res);
}
const updatedRepoList = [...filteredRepoList, updatedRepo];
await updateRepoList(updatedRepoList, true);
return res.status(200).json({ message: `Repository ${repo.repositoryName} has been edited` });
} catch (error) {
console.error(error);
return ApiResponse.serverError(res);
}
}
const dataHandler = (req: NextApiRequest, res: NextApiResponse) => {
const slug = req.query.slug;
if (!slug || Array.isArray(slug)) {
return ApiResponse.badRequest(res, 'Missing slug or slug is malformed');
}
const { alias, sshPublicKey, storageSize, comment, alert, lanCommand, appendOnlyMode } = req.body;
if (alias !== undefined && typeof alias !== 'string') {
return ApiResponse.badRequest(res, 'Alias must be a string');
}
if (sshPublicKey !== undefined && typeof sshPublicKey !== 'string') {
return ApiResponse.badRequest(res, 'SSH Public Key must be a string');
}
if (storageSize !== undefined && typeof storageSize !== 'number') {
return ApiResponse.badRequest(res, 'Storage Size must be a number');
}
if (comment !== undefined && typeof comment !== 'string') {
return ApiResponse.badRequest(res, 'Comment must be a string');
}
if (alert !== undefined && typeof alert !== 'number') {
return ApiResponse.badRequest(res, 'Alert must be a number');
}
if (lanCommand !== undefined && typeof lanCommand !== 'boolean') {
return ApiResponse.badRequest(res, 'Lan Command must be a boolean');
}
if (appendOnlyMode !== undefined && typeof appendOnlyMode !== 'boolean') {
return ApiResponse.badRequest(res, 'Append Only Mode must be a boolean');
}
};