If you received this mail then the configuration seems to be correct.
@@ -92,12 +92,12 @@ export default function emailTest(mailTo, username) {
`,
- attachments: [
- {
- path: 'helpers/templates/attachments/valid-icon.png',
- cid: 'valid-icon',
- },
- ],
- };
- return template;
+ attachments: [
+ {
+ path: 'helpers/templates/attachments/valid-icon.png',
+ cid: 'valid-icon',
+ },
+ ],
+ };
+ return template;
}
diff --git a/package.json b/package.json
index 363f7f1..280a069 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,8 @@
"start": "next start",
"lint": "next lint",
"setup": "npm install && npm run setup:hooks",
- "setup:hooks": "npx husky install"
+ "setup:hooks": "npx husky install",
+ "format": "prettier --write \"{Components,Containers,helpers,pages,styles}/**/*.{js,jsx,ts,tsx,json,css,scss,md}\""
},
"dependencies": {
"@tabler/icons-react": "^3.14.0",
@@ -34,4 +35,5 @@
"husky": "^9.1.5",
"prettier": "^3.3.3"
}
+
}
diff --git a/pages/404.js b/pages/404.js
index ba7511a..6b04cf1 100644
--- a/pages/404.js
+++ b/pages/404.js
@@ -5,33 +5,29 @@ import { useRouter } from 'next/router';
import Image from 'next/image';
export default function Error404() {
- //Var
- const { status } = useSession();
- const router = useRouter();
+ //Var
+ const { status } = useSession();
+ const router = useRouter();
- if (status === 'authenticated') {
- return (
- <>
-
-
404 - Page not found
-
-
-
-
- >
- );
- } else {
- router.replace('/login');
- }
+ if (status === 'authenticated') {
+ return (
+ <>
+
+
404 - Page not found
+
+
+
+
+ >
+ );
+ } else {
+ router.replace('/login');
+ }
}
diff --git a/pages/_app.js b/pages/_app.js
index a553a82..ee0ce25 100644
--- a/pages/_app.js
+++ b/pages/_app.js
@@ -9,20 +9,17 @@ import { SessionProvider } from 'next-auth/react';
import Layout from '../Components/UI/Layout/Layout';
export default function MyApp({ Component, pageProps }) {
- return (
-
-
-
-
-
- BorgWarehouse
-
-
-
-
-
- );
+ return (
+
+
+
+
+
+ BorgWarehouse
+
+
+
+
+
+ );
}
diff --git a/pages/account/index.js b/pages/account/index.js
index 2593fef..d9bba6c 100644
--- a/pages/account/index.js
+++ b/pages/account/index.js
@@ -9,42 +9,38 @@ import { getServerSession } from 'next-auth/next';
import UserSettings from '../../Containers/UserSettings/UserSettings';
export default function Account() {
- ////Var
- const { status, data } = useSession();
+ ////Var
+ const { status, data } = useSession();
- //Function
- if (status == 'unauthenticated' || status == 'loading') {
- return
Loading...
;
- }
- return (
- <>
-
-
Account - BorgWarehouse
-
+ //Function
+ if (status == 'unauthenticated' || status == 'loading') {
+ return
Loading...
;
+ }
+ return (
+ <>
+
+
Account - BorgWarehouse
+
-
- >
- );
+
+ >
+ );
}
export async function getServerSideProps(context) {
- //Var
- const session = await getServerSession(
- context.req,
- context.res,
- authOptions
- );
-
- if (!session) {
- return {
- redirect: {
- destination: '/login',
- permanent: false,
- },
- };
- }
+ //Var
+ const session = await getServerSession(context.req, context.res, authOptions);
+ if (!session) {
return {
- props: {},
+ redirect: {
+ destination: '/login',
+ permanent: false,
+ },
};
+ }
+
+ return {
+ props: {},
+ };
}
diff --git a/pages/api/account/getAppriseAlert.js b/pages/api/account/getAppriseAlert.js
index 9254934..e3e1a2c 100644
--- a/pages/api/account/getAppriseAlert.js
+++ b/pages/api/account/getAppriseAlert.js
@@ -5,59 +5,53 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'GET') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
- try {
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- } else {
- //Send the appriseAlert bool
- res.status(200).json({
- appriseAlert: usersList[userIndex].appriseAlert,
- });
- return;
- }
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'GET') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+ try {
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ } else {
+ //Send the appriseAlert bool
+ res.status(200).json({
+ appriseAlert: usersList[userIndex].appriseAlert,
+ });
+ return;
+ }
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/getAppriseMode.js b/pages/api/account/getAppriseMode.js
index efd5b32..dd2beeb 100644
--- a/pages/api/account/getAppriseMode.js
+++ b/pages/api/account/getAppriseMode.js
@@ -5,61 +5,54 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'GET') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
- try {
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- } else {
- //Send the appriseMode object
- res.status(200).json({
- appriseMode: usersList[userIndex].appriseMode,
- appriseStatelessURL:
- usersList[userIndex].appriseStatelessURL,
- });
- return;
- }
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'GET') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+ try {
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ } else {
+ //Send the appriseMode object
+ res.status(200).json({
+ appriseMode: usersList[userIndex].appriseMode,
+ appriseStatelessURL: usersList[userIndex].appriseStatelessURL,
+ });
+ return;
+ }
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/getAppriseServices.js b/pages/api/account/getAppriseServices.js
index 56ce6ed..c02994a 100644
--- a/pages/api/account/getAppriseServices.js
+++ b/pages/api/account/getAppriseServices.js
@@ -5,59 +5,53 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'GET') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
- try {
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- } else {
- //Send the appriseServices array
- res.status(200).json({
- appriseServices: usersList[userIndex].appriseServices,
- });
- return;
- }
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'GET') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+ try {
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ } else {
+ //Send the appriseServices array
+ res.status(200).json({
+ appriseServices: usersList[userIndex].appriseServices,
+ });
+ return;
+ }
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/getEmailAlert.js b/pages/api/account/getEmailAlert.js
index fe22025..859f106 100644
--- a/pages/api/account/getEmailAlert.js
+++ b/pages/api/account/getEmailAlert.js
@@ -5,59 +5,53 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'GET') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
- try {
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- } else {
- //Send the emailAlert bool
- res.status(200).json({
- emailAlert: usersList[userIndex].emailAlert,
- });
- return;
- }
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'GET') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+ try {
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ } else {
+ //Send the emailAlert bool
+ res.status(200).json({
+ emailAlert: usersList[userIndex].emailAlert,
+ });
+ return;
+ }
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/getWizardEnv.js b/pages/api/account/getWizardEnv.js
index 8a6d618..9542926 100644
--- a/pages/api/account/getWizardEnv.js
+++ b/pages/api/account/getWizardEnv.js
@@ -3,47 +3,41 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'GET') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
- try {
- function getEnvVariable(envName, defaultValue = '') {
- return process.env[envName] || defaultValue;
- }
-
- const wizardEnv = {
- UNIX_USER: getEnvVariable('UNIX_USER', 'borgwarehouse'),
- FQDN: getEnvVariable('FQDN', 'localhost'),
- SSH_SERVER_PORT: getEnvVariable('SSH_SERVER_PORT', '22'),
- FQDN_LAN: getEnvVariable('FQDN_LAN'),
- SSH_SERVER_PORT_LAN: getEnvVariable('SSH_SERVER_PORT_LAN'),
- SSH_SERVER_FINGERPRINT_RSA: getEnvVariable(
- 'SSH_SERVER_FINGERPRINT_RSA'
- ),
- SSH_SERVER_FINGERPRINT_ED25519: getEnvVariable(
- 'SSH_SERVER_FINGERPRINT_ED25519'
- ),
- SSH_SERVER_FINGERPRINT_ECDSA: getEnvVariable(
- 'SSH_SERVER_FINGERPRINT_ECDSA'
- ),
- };
- res.status(200).json({ wizardEnv });
- return;
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'GET') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+ try {
+ function getEnvVariable(envName, defaultValue = '') {
+ return process.env[envName] || defaultValue;
+ }
+
+ const wizardEnv = {
+ UNIX_USER: getEnvVariable('UNIX_USER', 'borgwarehouse'),
+ FQDN: getEnvVariable('FQDN', 'localhost'),
+ SSH_SERVER_PORT: getEnvVariable('SSH_SERVER_PORT', '22'),
+ FQDN_LAN: getEnvVariable('FQDN_LAN'),
+ SSH_SERVER_PORT_LAN: getEnvVariable('SSH_SERVER_PORT_LAN'),
+ SSH_SERVER_FINGERPRINT_RSA: getEnvVariable('SSH_SERVER_FINGERPRINT_RSA'),
+ SSH_SERVER_FINGERPRINT_ED25519: getEnvVariable('SSH_SERVER_FINGERPRINT_ED25519'),
+ SSH_SERVER_FINGERPRINT_ECDSA: getEnvVariable('SSH_SERVER_FINGERPRINT_ECDSA'),
+ };
+ res.status(200).json({ wizardEnv });
+ return;
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/sendTestApprise.js b/pages/api/account/sendTestApprise.js
index 66e7b27..12e5918 100644
--- a/pages/api/account/sendTestApprise.js
+++ b/pages/api/account/sendTestApprise.js
@@ -6,158 +6,140 @@ import path from 'path';
const { exec } = require('child_process');
export default async function handler(req, res) {
- if (req.method == 'POST') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { sendTestApprise } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- }
-
- //2 : control the data
- if (sendTestApprise !== true) {
- res.status(422).json({ message: 'Unexpected data' });
- return;
- }
-
- //3 : if there is no service URLs, throw error
- if (
- !usersList[userIndex].appriseServices ||
- usersList[userIndex].appriseServices.length === 0
- ) {
- res.status(422).json({
- message:
- 'You must provide at least one Apprise URL to send a test.',
- });
- return;
- }
-
- ////4 : Send the notification to services
- //Build the URLs service list as a single string
- let appriseServicesURLs = '';
- for (let service of usersList[userIndex].appriseServices) {
- appriseServicesURLs = appriseServicesURLs + service + ' ';
- }
- //Mode : package
- if (usersList[userIndex].appriseMode === 'package') {
- try {
- //Check if apprise is installed as local package.
- exec('apprise -V', (error, stderr, stdout) => {
- if (error) {
- console.log(
- `Error when checking if Apprise is a local package : ${error}`
- );
- res.status(500).json({
- message:
- 'Apprise is not installed as local package on your server.',
- });
- return;
- } else {
- //Send notification via local package.
- exec(
- `apprise -v -b "This is a test notification from BorgWarehouse !" ${appriseServicesURLs}`,
- (error, stderr, stdout) => {
- if (stderr) {
- res.status(500).json({
- message:
- 'There are some errors : ' + stderr,
- });
- return;
- } else {
- res.status(200).json({
- message:
- 'Notifications successfully sent.',
- });
- return;
- }
- }
- );
- }
- });
- } catch (err) {
- console.log(err);
- res.status(500).json({
- message:
- 'Error on sending notification. Contact your administrator.',
- });
- return;
- }
-
- //Mode : stateless
- } else if (usersList[userIndex].appriseMode === 'stateless') {
- //If stateless URL is empty
- if (usersList[userIndex].appriseStatelessURL === '') {
- res.status(500).json({
- message: 'Please, provide an Apprise stateless API URL.',
- });
- return;
- }
- try {
- await fetch(
- usersList[userIndex].appriseStatelessURL + '/notify',
- {
- method: 'POST',
- headers: {
- 'Content-type': 'application/json',
- },
- body: JSON.stringify({
- urls: appriseServicesURLs,
- body: 'This is a test notification from BorgWarehouse !',
- }),
- }
- ).then((response) => {
- if (response.ok) {
- res.status(200).json({
- message: 'Notifications successfully sent.',
- });
- return;
- } else {
- console.log(response);
- res.status(500).json({
- message:
- 'There are some errors : ' +
- response.statusText,
- });
- return;
- }
- });
- } catch (err) {
- res.status(500).json({
- message: 'Error : ' + err.message,
- });
- return;
- }
-
- //Mode : unknown
- } else {
- res.status(422).json({
- message: 'No Apprise Mode selected or supported.',
- });
- }
+ if (req.method == 'POST') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { sendTestApprise } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ }
+
+ //2 : control the data
+ if (sendTestApprise !== true) {
+ res.status(422).json({ message: 'Unexpected data' });
+ return;
+ }
+
+ //3 : if there is no service URLs, throw error
+ if (
+ !usersList[userIndex].appriseServices ||
+ usersList[userIndex].appriseServices.length === 0
+ ) {
+ res.status(422).json({
+ message: 'You must provide at least one Apprise URL to send a test.',
+ });
+ return;
+ }
+
+ ////4 : Send the notification to services
+ //Build the URLs service list as a single string
+ let appriseServicesURLs = '';
+ for (let service of usersList[userIndex].appriseServices) {
+ appriseServicesURLs = appriseServicesURLs + service + ' ';
+ }
+ //Mode : package
+ if (usersList[userIndex].appriseMode === 'package') {
+ try {
+ //Check if apprise is installed as local package.
+ exec('apprise -V', (error, stderr, stdout) => {
+ if (error) {
+ console.log(`Error when checking if Apprise is a local package : ${error}`);
+ res.status(500).json({
+ message: 'Apprise is not installed as local package on your server.',
+ });
+ return;
+ } else {
+ //Send notification via local package.
+ exec(
+ `apprise -v -b "This is a test notification from BorgWarehouse !" ${appriseServicesURLs}`,
+ (error, stderr, stdout) => {
+ if (stderr) {
+ res.status(500).json({
+ message: 'There are some errors : ' + stderr,
+ });
+ return;
+ } else {
+ res.status(200).json({
+ message: 'Notifications successfully sent.',
+ });
+ return;
+ }
+ }
+ );
+ }
+ });
+ } catch (err) {
+ console.log(err);
+ res.status(500).json({
+ message: 'Error on sending notification. Contact your administrator.',
+ });
+ return;
+ }
+
+ //Mode : stateless
+ } else if (usersList[userIndex].appriseMode === 'stateless') {
+ //If stateless URL is empty
+ if (usersList[userIndex].appriseStatelessURL === '') {
+ res.status(500).json({
+ message: 'Please, provide an Apprise stateless API URL.',
+ });
+ return;
+ }
+ try {
+ await fetch(usersList[userIndex].appriseStatelessURL + '/notify', {
+ method: 'POST',
+ headers: {
+ 'Content-type': 'application/json',
+ },
+ body: JSON.stringify({
+ urls: appriseServicesURLs,
+ body: 'This is a test notification from BorgWarehouse !',
+ }),
+ }).then((response) => {
+ if (response.ok) {
+ res.status(200).json({
+ message: 'Notifications successfully sent.',
+ });
+ return;
+ } else {
+ console.log(response);
+ res.status(500).json({
+ message: 'There are some errors : ' + response.statusText,
+ });
+ return;
+ }
+ });
+ } catch (err) {
+ res.status(500).json({
+ message: 'Error : ' + err.message,
+ });
+ return;
+ }
+
+ //Mode : unknown
+ } else {
+ res.status(422).json({
+ message: 'No Apprise Mode selected or supported.',
+ });
+ }
+ }
}
diff --git a/pages/api/account/sendTestEmail.js b/pages/api/account/sendTestEmail.js
index 3bf0ea9..ea85204 100644
--- a/pages/api/account/sendTestEmail.js
+++ b/pages/api/account/sendTestEmail.js
@@ -5,44 +5,43 @@ import nodemailerSMTP from '../../../helpers/functions/nodemailerSMTP';
import emailTest from '../../../helpers/templates/emailTest';
export default async function handler(req, res) {
- if (req.method == 'POST') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //Create the SMTP Transporter
- const transporter = nodemailerSMTP();
-
- //Mail options
- const mailData = emailTest(session.user.email, session.user.name);
-
- //Send mail
- try {
- transporter.sendMail(mailData, function (err, info) {
- if (err) {
- console.log(err);
- res.status(400).json({
- message:
- 'An error occured while sending the email : ' + err,
- });
- return;
- } else {
- console.log(info);
- res.status(200).json({
- message: 'Mail successfully sent.',
- });
- return;
- }
- });
- } catch (err) {
- console.log(err);
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator.',
- });
- }
+ if (req.method == 'POST') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //Create the SMTP Transporter
+ const transporter = nodemailerSMTP();
+
+ //Mail options
+ const mailData = emailTest(session.user.email, session.user.name);
+
+ //Send mail
+ try {
+ transporter.sendMail(mailData, function (err, info) {
+ if (err) {
+ console.log(err);
+ res.status(400).json({
+ message: 'An error occured while sending the email : ' + err,
+ });
+ return;
+ } else {
+ console.log(info);
+ res.status(200).json({
+ message: 'Mail successfully sent.',
+ });
+ return;
+ }
+ });
+ } catch (err) {
+ console.log(err);
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator.',
+ });
+ }
+ }
}
diff --git a/pages/api/account/token-manager.js b/pages/api/account/token-manager.js
index 9b4f009..d19a8e5 100644
--- a/pages/api/account/token-manager.js
+++ b/pages/api/account/token-manager.js
@@ -5,252 +5,223 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'POST') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { name, token, creation, expiration, permissions } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : We check that we receive data for each variable.
- if (!name || !token || !creation || !permissions) {
- res.status(400).json({ message: 'A field is missing.' });
- return;
- }
-
- //Control the data
- const nameRegex = new RegExp('^[a-zA-Z0-9_-]{1,25}$');
- if (!nameRegex.test(name)) {
- res.status(400).json({ message: 'Your name is not valid' });
- return;
- }
-
- //2 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({ message: 'User is incorrect.' });
- return;
- }
- const user = usersList[userIndex];
-
- //3 : Check that the tokenName or tokenValue already exists
- const tokenExists =
- user.tokens &&
- user.tokens.some((existingToken) => existingToken.name === name);
- if (tokenExists) {
- res.status(400).json({
- message: 'A token with this name already exists.',
- });
- return;
- }
-
- //4 : Add the new token
- try {
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? {
- ...user,
- tokens: [
- ...(user.tokens || []),
- {
- name,
- token,
- creation,
- expiration,
- permissions,
- },
- ],
- }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else if (req.method == 'GET') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
- try {
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- } else {
- //Send the token list without tokens
- res.status(200).json([
- ...usersList[userIndex].tokens.map((token) => ({
- name: token.name,
- creation: token.creation,
- expiration: token.expiration,
- permissions: token.permissions,
- })),
- ]);
- return;
- }
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else if (req.method == 'DELETE') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { name } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : We check that we receive data for each variable.
- if (!name) {
- res.status(400).json({ message: 'A field is missing.' });
- return;
- }
-
- //2 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({ message: 'User is incorrect.' });
- return;
- }
- const user = usersList[userIndex];
-
- //Control the data
- const tokenExists = user.tokens.some(
- (existingToken) => existingToken.name === name
- );
- if (!tokenExists) {
- res.status(400).json({ message: 'Token not found.' });
- return;
- }
-
- //3 : Delete the token object if it exists
- try {
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? {
- ...user,
- tokens: user.tokens.filter(
- (token) => token.name != name
- ),
- }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'POST') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { name, token, creation, expiration, permissions } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : We check that we receive data for each variable.
+ if (!name || !token || !creation || !permissions) {
+ res.status(400).json({ message: 'A field is missing.' });
+ return;
+ }
+
+ //Control the data
+ const nameRegex = new RegExp('^[a-zA-Z0-9_-]{1,25}$');
+ if (!nameRegex.test(name)) {
+ res.status(400).json({ message: 'Your name is not valid' });
+ return;
+ }
+
+ //2 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({ message: 'User is incorrect.' });
+ return;
+ }
+ const user = usersList[userIndex];
+
+ //3 : Check that the tokenName or tokenValue already exists
+ const tokenExists =
+ user.tokens && user.tokens.some((existingToken) => existingToken.name === name);
+ if (tokenExists) {
+ res.status(400).json({
+ message: 'A token with this name already exists.',
+ });
+ return;
+ }
+
+ //4 : Add the new token
+ try {
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name
+ ? {
+ ...user,
+ tokens: [
+ ...(user.tokens || []),
+ {
+ name,
+ token,
+ creation,
+ expiration,
+ permissions,
+ },
+ ],
+ }
+ : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else if (req.method == 'GET') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
+ }
+ try {
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ } else {
+ //Send the token list without tokens
+ res.status(200).json([
+ ...usersList[userIndex].tokens.map((token) => ({
+ name: token.name,
+ creation: token.creation,
+ expiration: token.expiration,
+ permissions: token.permissions,
+ })),
+ ]);
+ return;
+ }
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else if (req.method == 'DELETE') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
+ }
+
+ //The data we expect to receive
+ let { name } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : We check that we receive data for each variable.
+ if (!name) {
+ res.status(400).json({ message: 'A field is missing.' });
+ return;
+ }
+
+ //2 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({ message: 'User is incorrect.' });
+ return;
+ }
+ const user = usersList[userIndex];
+
+ //Control the data
+ const tokenExists = user.tokens.some((existingToken) => existingToken.name === name);
+ if (!tokenExists) {
+ res.status(400).json({ message: 'Token not found.' });
+ return;
+ }
+
+ //3 : Delete the token object if it exists
+ try {
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name
+ ? {
+ ...user,
+ tokens: user.tokens.filter((token) => token.name != name),
+ }
+ : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/updateAppriseAlert.js b/pages/api/account/updateAppriseAlert.js
index 832e229..add2a7e 100644
--- a/pages/api/account/updateAppriseAlert.js
+++ b/pages/api/account/updateAppriseAlert.js
@@ -5,82 +5,70 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'PUT') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { appriseAlert } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : control the data
- if (typeof appriseAlert != 'boolean') {
- res.status(422).json({ message: 'Unexpected data' });
- return;
- }
-
- //2 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- }
-
- //3 : Change the appriseAlert settings
- try {
- //Modify the appriseAlert bool for the user
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? { ...user, appriseAlert: appriseAlert }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'PUT') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { appriseAlert } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : control the data
+ if (typeof appriseAlert != 'boolean') {
+ res.status(422).json({ message: 'Unexpected data' });
+ return;
+ }
+
+ //2 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ }
+
+ //3 : Change the appriseAlert settings
+ try {
+ //Modify the appriseAlert bool for the user
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name ? { ...user, appriseAlert: appriseAlert } : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/updateAppriseMode.js b/pages/api/account/updateAppriseMode.js
index 9c826eb..3acd6fa 100644
--- a/pages/api/account/updateAppriseMode.js
+++ b/pages/api/account/updateAppriseMode.js
@@ -5,86 +5,76 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'PUT') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { appriseMode, appriseStatelessURL } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : control the data
- if (appriseMode != 'package' && appriseMode != 'stateless') {
- res.status(422).json({ message: 'Unexpected data' });
- return;
- }
-
- //2 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- }
-
- //3 : Change the appriseMode
- try {
- //Modify the appriseMode for the user
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? {
- ...user,
- appriseMode: appriseMode,
- appriseStatelessURL: appriseStatelessURL,
- }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'PUT') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { appriseMode, appriseStatelessURL } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : control the data
+ if (appriseMode != 'package' && appriseMode != 'stateless') {
+ res.status(422).json({ message: 'Unexpected data' });
+ return;
+ }
+
+ //2 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ }
+
+ //3 : Change the appriseMode
+ try {
+ //Modify the appriseMode for the user
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name
+ ? {
+ ...user,
+ appriseMode: appriseMode,
+ appriseStatelessURL: appriseStatelessURL,
+ }
+ : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/updateAppriseServices.js b/pages/api/account/updateAppriseServices.js
index 83027bf..7253970 100644
--- a/pages/api/account/updateAppriseServices.js
+++ b/pages/api/account/updateAppriseServices.js
@@ -5,85 +5,75 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'PUT') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { appriseURLs } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- }
-
- //2 : Update Apprise URLs list
- try {
- //Build the services URLs list from form
- const appriseURLsArray = appriseURLs
- .replace(/ /g, '')
- .split('\n')
- .filter((el) => el != '');
-
- //Save the list for the user
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? {
- ...user,
- appriseServices: appriseURLsArray,
- }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'PUT') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { appriseURLs } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ }
+
+ //2 : Update Apprise URLs list
+ try {
+ //Build the services URLs list from form
+ const appriseURLsArray = appriseURLs
+ .replace(/ /g, '')
+ .split('\n')
+ .filter((el) => el != '');
+
+ //Save the list for the user
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name
+ ? {
+ ...user,
+ appriseServices: appriseURLsArray,
+ }
+ : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/updateEmail.js b/pages/api/account/updateEmail.js
index 33ff5ed..29a4bc5 100644
--- a/pages/api/account/updateEmail.js
+++ b/pages/api/account/updateEmail.js
@@ -5,92 +5,80 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'PUT') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { email } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : We check that we receive data.
- if (!email) {
- //If a variable is empty.
- res.status(400).json({ message: 'A field is missing.' });
- return;
- }
-
- //2 : control the data
- const emailRegex = new RegExp(
- /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
- );
- if (!emailRegex.test(email)) {
- res.status(400).json({ message: 'Your email is not valid' });
- return;
- }
-
- //3 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- }
-
- //4 : Change the email
- try {
- //Modify the email for the user
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? { ...user, email: email }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'PUT') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { email } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : We check that we receive data.
+ if (!email) {
+ //If a variable is empty.
+ res.status(400).json({ message: 'A field is missing.' });
+ return;
+ }
+
+ //2 : control the data
+ const emailRegex = new RegExp(
+ /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
+ );
+ if (!emailRegex.test(email)) {
+ res.status(400).json({ message: 'Your email is not valid' });
+ return;
+ }
+
+ //3 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ }
+
+ //4 : Change the email
+ try {
+ //Modify the email for the user
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name ? { ...user, email: email } : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/updateEmailAlert.js b/pages/api/account/updateEmailAlert.js
index fa8b28b..9a97c99 100644
--- a/pages/api/account/updateEmailAlert.js
+++ b/pages/api/account/updateEmailAlert.js
@@ -5,82 +5,70 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'PUT') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { emailAlert } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : control the data
- if (typeof emailAlert != 'boolean') {
- res.status(422).json({ message: 'Unexpected data' });
- return;
- }
-
- //2 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- }
-
- //3 : Change the emailAlert settings
- try {
- //Modify the email for the user
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? { ...user, emailAlert: emailAlert }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'PUT') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { emailAlert } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : control the data
+ if (typeof emailAlert != 'boolean') {
+ res.status(422).json({ message: 'Unexpected data' });
+ return;
+ }
+
+ //2 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ }
+
+ //3 : Change the emailAlert settings
+ try {
+ //Modify the email for the user
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name ? { ...user, emailAlert: emailAlert } : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/updatePassword.js b/pages/api/account/updatePassword.js
index 7359a63..26582f1 100644
--- a/pages/api/account/updatePassword.js
+++ b/pages/api/account/updatePassword.js
@@ -6,90 +6,79 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'PUT') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { oldPassword, newPassword } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : We check that we receive data for each variable.
- if (!oldPassword || !newPassword) {
- //If a variable is empty.
- res.status(400).json({ message: 'A field is missing.' });
- return;
- }
- //Hash the new password
- newPassword = await hashPassword(newPassword);
-
- //2 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({ message: 'User is incorrect.' });
- return;
- }
- const user = usersList[userIndex];
-
- //3 : Check that the old password is correct
- const isValid = await verifyPassword(oldPassword, user.password);
- if (!isValid) {
- res.status(400).json({ message: 'Old password is incorrect.' });
- return;
- }
-
- //4 : Change the password
- try {
- //Modify the password for the user
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? { ...user, password: newPassword }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'PUT') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { oldPassword, newPassword } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : We check that we receive data for each variable.
+ if (!oldPassword || !newPassword) {
+ //If a variable is empty.
+ res.status(400).json({ message: 'A field is missing.' });
+ return;
+ }
+ //Hash the new password
+ newPassword = await hashPassword(newPassword);
+
+ //2 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({ message: 'User is incorrect.' });
+ return;
+ }
+ const user = usersList[userIndex];
+
+ //3 : Check that the old password is correct
+ const isValid = await verifyPassword(oldPassword, user.password);
+ if (!isValid) {
+ res.status(400).json({ message: 'Old password is incorrect.' });
+ return;
+ }
+
+ //4 : Change the password
+ try {
+ //Modify the password for the user
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name ? { ...user, password: newPassword } : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/account/updateUsername.js b/pages/api/account/updateUsername.js
index 2d158d7..18077c6 100644
--- a/pages/api/account/updateUsername.js
+++ b/pages/api/account/updateUsername.js
@@ -5,92 +5,80 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'PUT') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- let { username } = req.body;
-
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
-
- //1 : We check that we receive data.
- if (!username) {
- //If a variable is empty.
- res.status(400).json({ message: 'A field is missing.' });
- return;
- }
-
- //2 : control the data
- const usernameRegex = new RegExp(/^[a-z]{5,15}$/);
- if (!usernameRegex.test(username)) {
- res.status(400).json({
- message: 'Only a-z characters are allowed (5 to 15 char.)',
- });
- return;
- }
-
- //3 : Verify that the user of the session exists
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(session.user.name);
- if (userIndex === -1) {
- res.status(400).json({
- message:
- 'User is incorrect. Please, logout to update your session.',
- });
- return;
- }
-
- //4 : Change the username
- try {
- //Modify the username for the user
- let newUsersList = usersList.map((user) =>
- user.username == session.user.name
- ? { ...user, username: username }
- : user
- );
- //Stringify the new users list
- newUsersList = JSON.stringify(newUsersList);
- //Write the new JSON
- await fs.writeFile(
- jsonDirectory + '/users.json',
- newUsersList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Successful API send' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({ message: 'Bad request on API' });
+ if (req.method == 'PUT') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ let { username } = req.body;
+
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+
+ //1 : We check that we receive data.
+ if (!username) {
+ //If a variable is empty.
+ res.status(400).json({ message: 'A field is missing.' });
+ return;
+ }
+
+ //2 : control the data
+ const usernameRegex = new RegExp(/^[a-z]{5,15}$/);
+ if (!usernameRegex.test(username)) {
+ res.status(400).json({
+ message: 'Only a-z characters are allowed (5 to 15 char.)',
+ });
+ return;
+ }
+
+ //3 : Verify that the user of the session exists
+ const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
+ if (userIndex === -1) {
+ res.status(400).json({
+ message: 'User is incorrect. Please, logout to update your session.',
+ });
+ return;
+ }
+
+ //4 : Change the username
+ try {
+ //Modify the username for the user
+ let newUsersList = usersList.map((user) =>
+ user.username == session.user.name ? { ...user, username: username } : user
+ );
+ //Stringify the new users list
+ newUsersList = JSON.stringify(newUsersList);
+ //Write the new JSON
+ await fs.writeFile(jsonDirectory + '/users.json', newUsersList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Successful API send' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({ message: 'Bad request on API' });
+ }
}
diff --git a/pages/api/auth/[...nextauth].js b/pages/api/auth/[...nextauth].js
index 1dcad01..e3d5dcd 100644
--- a/pages/api/auth/[...nextauth].js
+++ b/pages/api/auth/[...nextauth].js
@@ -6,100 +6,91 @@ import fs from 'fs';
import path from 'path';
const logLogin = async (message, req, success = false) => {
- const ipAddress = req.headers['x-forwarded-for'] || 'unknown';
- if (success) {
- console.log(`Login success from ${ipAddress} with user ${message}`);
- } else {
- console.log(`Login failed from ${ipAddress} : ${message}`);
- }
+ const ipAddress = req.headers['x-forwarded-for'] || 'unknown';
+ if (success) {
+ console.log(`Login success from ${ipAddress} with user ${message}`);
+ } else {
+ console.log(`Login failed from ${ipAddress} : ${message}`);
+ }
};
////Use if need getServerSideProps and therefore getServerSession
export const authOptions = {
- providers: [
- CredentialsProvider({
- async authorize(credentials, req) {
- const { username, password } = credentials;
- //Read the users file
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- //Check if the users.json file exists and initialize it if not with admin/admin.
- if (!fs.existsSync(jsonDirectory + '/users.json')) {
- fs.writeFileSync(
- jsonDirectory + '/users.json',
- JSON.stringify([
- {
- id: 0,
- email: '',
- username: 'admin',
- password:
- '$2a$12$20yqRnuaDBH6AE0EvIUcEOzqkuBtn1wDzJdw2Beg8w9S.vEqdso0a',
- roles: ['admin'],
- emailAlert: false,
- appriseAlert: false,
- },
- ])
- );
- }
- let usersList = await fs.promises.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
+ providers: [
+ CredentialsProvider({
+ async authorize(credentials, req) {
+ const { username, password } = credentials;
+ //Read the users file
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ //Check if the users.json file exists and initialize it if not with admin/admin.
+ if (!fs.existsSync(jsonDirectory + '/users.json')) {
+ fs.writeFileSync(
+ jsonDirectory + '/users.json',
+ JSON.stringify([
+ {
+ id: 0,
+ email: '',
+ username: 'admin',
+ password: '$2a$12$20yqRnuaDBH6AE0EvIUcEOzqkuBtn1wDzJdw2Beg8w9S.vEqdso0a',
+ roles: ['admin'],
+ emailAlert: false,
+ appriseAlert: false,
+ },
+ ])
+ );
+ }
+ let usersList = await fs.promises.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
- //Step 1 : does the user exist ?
- const userIndex = usersList
- .map((user) => user.username)
- .indexOf(username.toLowerCase());
- if (userIndex === -1) {
- await logLogin(`Bad username ${req.body.username}`, req);
- throw new Error('Incorrect credentials.');
- }
- const user = usersList[userIndex];
+ //Step 1 : does the user exist ?
+ const userIndex = usersList.map((user) => user.username).indexOf(username.toLowerCase());
+ if (userIndex === -1) {
+ await logLogin(`Bad username ${req.body.username}`, req);
+ throw new Error('Incorrect credentials.');
+ }
+ const user = usersList[userIndex];
- //Step 2 : Is the password correct ?
- const isValid = await verifyPassword(password, user.password);
- if (!isValid) {
- await logLogin(
- `Wrong password for ${req.body.username}`,
- req
- );
- throw new Error('Incorrect credentials.');
- }
+ //Step 2 : Is the password correct ?
+ const isValid = await verifyPassword(password, user.password);
+ if (!isValid) {
+ await logLogin(`Wrong password for ${req.body.username}`, req);
+ throw new Error('Incorrect credentials.');
+ }
- //Success
- const account = {
- name: user.username,
- email: user.email,
- id: user.id,
- roles: user.roles,
- };
+ //Success
+ const account = {
+ name: user.username,
+ email: user.email,
+ id: user.id,
+ roles: user.roles,
+ };
- await logLogin(req.body.username, req, true);
- return account;
- },
- }),
- ],
- callbacks: {
- async jwt({ token, user }) {
- // Persist the role and the ID to the token right after signin. "user" is the response from signin, and we return account.
- if (user) {
- token.roles = user.roles;
- token.id = user.id;
- }
- return token;
- },
- async session({ session, token }) {
- // Send properties to the client to access to the token info through session().
- if (token) {
- session.user.roles = token.roles;
- session.user.id = token.id;
- }
- return session;
- },
+ await logLogin(req.body.username, req, true);
+ return account;
+ },
+ }),
+ ],
+ callbacks: {
+ async jwt({ token, user }) {
+ // Persist the role and the ID to the token right after signin. "user" is the response from signin, and we return account.
+ if (user) {
+ token.roles = user.roles;
+ token.id = user.id;
+ }
+ return token;
},
- secret: process.env.NEXTAUTH_SECRET,
+ async session({ session, token }) {
+ // Send properties to the client to access to the token info through session().
+ if (token) {
+ session.user.roles = token.roles;
+ session.user.id = token.id;
+ }
+ return session;
+ },
+ },
+ secret: process.env.NEXTAUTH_SECRET,
};
export default NextAuth(authOptions);
diff --git a/pages/api/cronjob/checkStatus.js b/pages/api/cronjob/checkStatus.js
index 842aaa3..26658e8 100644
--- a/pages/api/cronjob/checkStatus.js
+++ b/pages/api/cronjob/checkStatus.js
@@ -10,239 +10,214 @@ import nodemailerSMTP from '../../../helpers/functions/nodemailerSMTP';
import emailAlertStatus from '../../../helpers/templates/emailAlertStatus';
export default async function handler(req, res) {
- if (req.headers.authorization == null) {
- res.status(401).json({
- status: 401,
- message: 'Unauthorized',
- });
- return;
- }
+ if (req.headers.authorization == null) {
+ res.status(401).json({
+ status: 401,
+ message: 'Unauthorized',
+ });
+ return;
+ }
- const CRONJOB_KEY = process.env.CRONJOB_KEY;
- const ACTION_KEY = req.headers.authorization.split(' ')[1];
+ const CRONJOB_KEY = process.env.CRONJOB_KEY;
+ const ACTION_KEY = req.headers.authorization.split(' ')[1];
- if (req.method == 'POST' && ACTION_KEY === CRONJOB_KEY) {
- //Var
- let newRepoList;
- let repoListToSendAlert = [];
- let usersList;
- const date = Math.round(Date.now() / 1000);
- const jsonDirectory = path.join(process.cwd(), '/config');
+ if (req.method == 'POST' && ACTION_KEY === CRONJOB_KEY) {
+ //Var
+ let newRepoList;
+ let repoListToSendAlert = [];
+ let usersList;
+ const date = Math.round(Date.now() / 1000);
+ const jsonDirectory = path.join(process.cwd(), '/config');
- ////PART 1 : Status
- try {
- //Check if there are some repositories
- let repoList = await fs.readFile(
- jsonDirectory + '/repo.json',
- 'utf8'
- );
- repoList = JSON.parse(repoList);
- if (repoList.length === 0) {
- res.status(200).json({
- success:
- 'Status cron has been executed. No repository to check.',
- });
- return;
- }
-
- //Call the shell : getLastSave.sh
- //Find the absolute path of the shells directory
- const shellsDirectory = path.join(process.cwd(), '/helpers');
- //Exec the shell
- const { stdout, stderr } = await exec(
- `${shellsDirectory}/shells/getLastSave.sh`
- );
- if (stderr) {
- console.log('stderr:', stderr);
- res.status(500).json({
- status: 500,
- message:
- 'Error on getting the date for last save, contact the administrator.',
- });
- return;
- }
- //Parse the JSON output of getLastSave.sh to use it
- const lastSave = JSON.parse(stdout);
-
- //Rebuild a newRepoList with the lastSave timestamp updated and the status updated.
- newRepoList = repoList;
- for (let index in newRepoList) {
- const repoFiltered = lastSave.filter(
- (x) =>
- x.repositoryName === newRepoList[index].repositoryName
- );
- if (repoFiltered.length === 1) {
- //Write the timestamp of the last save
- newRepoList[index].lastSave = repoFiltered[0].lastSave;
- //Trigger the status if the last save is older than alert setting.
- if (
- date - newRepoList[index].lastSave >
- newRepoList[index].alert
- ) {
- newRepoList[index].status = false;
- } else if (
- date - newRepoList[index].lastSave <
- newRepoList[index].alert
- ) {
- newRepoList[index].status = true;
- }
- }
- }
- } catch (err) {
- res.status(500).json({
- status: 500,
- message: "API error : can't update the status.",
- });
- return;
- }
-
- //// PART 2 : check if there is a repo that need an alert
- try {
- //Here, a mail is sent every 24H (90000) if a repo has down status
- for (let index in newRepoList) {
- if (
- !newRepoList[index].status &&
- newRepoList[index].alert !== 0 &&
- (!newRepoList[index].lastStatusAlertSend ||
- date - newRepoList[index].lastStatusAlertSend > 90000)
- ) {
- repoListToSendAlert.push(newRepoList[index].alias);
- newRepoList[index].lastStatusAlertSend = date;
- }
- }
- } catch (err) {
- res.status(500).json({
- status: 500,
- message:
- "API error : can't check if a repo needs an email alert.",
- });
- return;
- }
-
- //PART 3 : Save the new repoList
- try {
- //Stringify the repoList to write it into the json file.
- newRepoList = JSON.stringify(newRepoList);
- //Write the new json
- await fs.writeFile(
- jsonDirectory + '/repo.json',
- newRepoList,
- (err) => {
- if (err) console.log(err);
- }
- );
- } catch (err) {
- res.status(500).json({
- status: 500,
- message: "API error : can't write the new repoList.",
- });
- return;
- }
- //PART 4 : Send the alerts
- if (repoListToSendAlert.length > 0) {
- // Read user informations
- try {
- //Read the email of the user
- usersList = await fs.readFile(
- jsonDirectory + '/users.json',
- 'utf8'
- );
- //Parse the usersList
- usersList = JSON.parse(usersList);
- } catch (err) {
- res.status(500).json({
- status: 500,
- message: "API error : can't read user information.",
- });
- return;
- }
- ////EMAIL
- // If the user has enabled email alerts
- if (usersList[0].emailAlert) {
- //Send mail
- //Create the SMTP Transporter
- const transporter = nodemailerSMTP();
- //Mail options
- const mailData = emailAlertStatus(
- usersList[0].email,
- usersList[0].username,
- repoListToSendAlert
- );
- transporter.sendMail(mailData, function (err, info) {
- if (err) {
- console.log(err);
- } else {
- console.log(info);
- }
- });
- }
- ////APPRISE
- // If the user has enabled Apprise alerts
- if (usersList[0].appriseAlert) {
- let appriseServicesURLs = '';
- for (let service of usersList[0].appriseServices) {
- appriseServicesURLs = appriseServicesURLs + service + ' ';
- }
- //Mode : package
- if (usersList[0].appriseMode === 'package') {
- try {
- //Send notification via local package.
- await exec(
- `apprise -v -b '🔴 Some repositories on BorgWarehouse need attention !\nList of down repositories :\n ${repoListToSendAlert}' ${appriseServicesURLs}`
- );
- } catch (err) {
- console.log(err.stderr);
- res.status(500).json({
- message: 'Error : ' + err.stderr,
- });
- return;
- }
-
- //Mode : stateless
- } else if (usersList[0].appriseMode === 'stateless') {
- try {
- await fetch(
- usersList[0].appriseStatelessURL + '/notify',
- {
- method: 'POST',
- headers: {
- 'Content-type': 'application/json',
- },
- body: JSON.stringify({
- urls: appriseServicesURLs,
- body:
- '🔴 Some repositories on BorgWarehouse need attention !\nList of down repositories :\n' +
- repoListToSendAlert,
- }),
- }
- );
- } catch (err) {
- console.log(err);
- res.status(500).json({
- message: 'Error : ' + err.message,
- });
- return;
- }
-
- //Mode : unknown
- } else {
- res.status(422).json({
- message: 'No Apprise Mode selected or supported.',
- });
- }
- }
- }
-
- //PART 5 : Sucess
+ ////PART 1 : Status
+ try {
+ //Check if there are some repositories
+ let repoList = await fs.readFile(jsonDirectory + '/repo.json', 'utf8');
+ repoList = JSON.parse(repoList);
+ if (repoList.length === 0) {
res.status(200).json({
- success: 'Status cron has been executed.',
+ success: 'Status cron has been executed. No repository to check.',
});
return;
- } else {
- res.status(401).json({
- status: 401,
- message: 'Unauthorized',
+ }
+
+ //Call the shell : getLastSave.sh
+ //Find the absolute path of the shells directory
+ const shellsDirectory = path.join(process.cwd(), '/helpers');
+ //Exec the shell
+ const { stdout, stderr } = await exec(`${shellsDirectory}/shells/getLastSave.sh`);
+ if (stderr) {
+ console.log('stderr:', stderr);
+ res.status(500).json({
+ status: 500,
+ message: 'Error on getting the date for last save, contact the administrator.',
});
return;
+ }
+ //Parse the JSON output of getLastSave.sh to use it
+ const lastSave = JSON.parse(stdout);
+
+ //Rebuild a newRepoList with the lastSave timestamp updated and the status updated.
+ newRepoList = repoList;
+ for (let index in newRepoList) {
+ const repoFiltered = lastSave.filter(
+ (x) => x.repositoryName === newRepoList[index].repositoryName
+ );
+ if (repoFiltered.length === 1) {
+ //Write the timestamp of the last save
+ newRepoList[index].lastSave = repoFiltered[0].lastSave;
+ //Trigger the status if the last save is older than alert setting.
+ if (date - newRepoList[index].lastSave > newRepoList[index].alert) {
+ newRepoList[index].status = false;
+ } else if (date - newRepoList[index].lastSave < newRepoList[index].alert) {
+ newRepoList[index].status = true;
+ }
+ }
+ }
+ } catch (err) {
+ res.status(500).json({
+ status: 500,
+ message: "API error : can't update the status.",
+ });
+ return;
}
+
+ //// PART 2 : check if there is a repo that need an alert
+ try {
+ //Here, a mail is sent every 24H (90000) if a repo has down status
+ for (let index in newRepoList) {
+ if (
+ !newRepoList[index].status &&
+ newRepoList[index].alert !== 0 &&
+ (!newRepoList[index].lastStatusAlertSend ||
+ date - newRepoList[index].lastStatusAlertSend > 90000)
+ ) {
+ repoListToSendAlert.push(newRepoList[index].alias);
+ newRepoList[index].lastStatusAlertSend = date;
+ }
+ }
+ } catch (err) {
+ res.status(500).json({
+ status: 500,
+ message: "API error : can't check if a repo needs an email alert.",
+ });
+ return;
+ }
+
+ //PART 3 : Save the new repoList
+ try {
+ //Stringify the repoList to write it into the json file.
+ newRepoList = JSON.stringify(newRepoList);
+ //Write the new json
+ await fs.writeFile(jsonDirectory + '/repo.json', newRepoList, (err) => {
+ if (err) console.log(err);
+ });
+ } catch (err) {
+ res.status(500).json({
+ status: 500,
+ message: "API error : can't write the new repoList.",
+ });
+ return;
+ }
+ //PART 4 : Send the alerts
+ if (repoListToSendAlert.length > 0) {
+ // Read user informations
+ try {
+ //Read the email of the user
+ usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
+ //Parse the usersList
+ usersList = JSON.parse(usersList);
+ } catch (err) {
+ res.status(500).json({
+ status: 500,
+ message: "API error : can't read user information.",
+ });
+ return;
+ }
+ ////EMAIL
+ // If the user has enabled email alerts
+ if (usersList[0].emailAlert) {
+ //Send mail
+ //Create the SMTP Transporter
+ const transporter = nodemailerSMTP();
+ //Mail options
+ const mailData = emailAlertStatus(
+ usersList[0].email,
+ usersList[0].username,
+ repoListToSendAlert
+ );
+ transporter.sendMail(mailData, function (err, info) {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(info);
+ }
+ });
+ }
+ ////APPRISE
+ // If the user has enabled Apprise alerts
+ if (usersList[0].appriseAlert) {
+ let appriseServicesURLs = '';
+ for (let service of usersList[0].appriseServices) {
+ appriseServicesURLs = appriseServicesURLs + service + ' ';
+ }
+ //Mode : package
+ if (usersList[0].appriseMode === 'package') {
+ try {
+ //Send notification via local package.
+ await exec(
+ `apprise -v -b '🔴 Some repositories on BorgWarehouse need attention !\nList of down repositories :\n ${repoListToSendAlert}' ${appriseServicesURLs}`
+ );
+ } catch (err) {
+ console.log(err.stderr);
+ res.status(500).json({
+ message: 'Error : ' + err.stderr,
+ });
+ return;
+ }
+
+ //Mode : stateless
+ } else if (usersList[0].appriseMode === 'stateless') {
+ try {
+ await fetch(usersList[0].appriseStatelessURL + '/notify', {
+ method: 'POST',
+ headers: {
+ 'Content-type': 'application/json',
+ },
+ body: JSON.stringify({
+ urls: appriseServicesURLs,
+ body:
+ '🔴 Some repositories on BorgWarehouse need attention !\nList of down repositories :\n' +
+ repoListToSendAlert,
+ }),
+ });
+ } catch (err) {
+ console.log(err);
+ res.status(500).json({
+ message: 'Error : ' + err.message,
+ });
+ return;
+ }
+
+ //Mode : unknown
+ } else {
+ res.status(422).json({
+ message: 'No Apprise Mode selected or supported.',
+ });
+ }
+ }
+ }
+
+ //PART 5 : Sucess
+ res.status(200).json({
+ success: 'Status cron has been executed.',
+ });
+ return;
+ } else {
+ res.status(401).json({
+ status: 401,
+ message: 'Unauthorized',
+ });
+ return;
+ }
}
diff --git a/pages/api/cronjob/getStorageUsed.js b/pages/api/cronjob/getStorageUsed.js
index 16cf508..8bc9e07 100644
--- a/pages/api/cronjob/getStorageUsed.js
+++ b/pages/api/cronjob/getStorageUsed.js
@@ -8,89 +8,79 @@ const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
export default async function handler(req, res) {
- if (req.headers.authorization == null) {
- res.status(401).json({
- status: 401,
- message: 'Unauthorized',
+ if (req.headers.authorization == null) {
+ res.status(401).json({
+ status: 401,
+ message: 'Unauthorized',
+ });
+ return;
+ }
+
+ const CRONJOB_KEY = process.env.CRONJOB_KEY;
+ const ACTION_KEY = req.headers.authorization.split(' ')[1];
+
+ try {
+ if (req.method == 'POST' && ACTION_KEY === CRONJOB_KEY) {
+ //Check the repoList
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let repoList = await fs.readFile(jsonDirectory + '/repo.json', 'utf8');
+ //Parse the repoList
+ repoList = JSON.parse(repoList);
+ //If repoList is empty we stop here.
+ if (repoList.length === 0) {
+ res.status(200).json({
+ success: 'No repositories to analyse yet.',
});
return;
- }
+ }
- const CRONJOB_KEY = process.env.CRONJOB_KEY;
- const ACTION_KEY = req.headers.authorization.split(' ')[1];
-
- try {
- if (req.method == 'POST' && ACTION_KEY === CRONJOB_KEY) {
- //Check the repoList
- const jsonDirectory = path.join(process.cwd(), '/config');
- let repoList = await fs.readFile(
- jsonDirectory + '/repo.json',
- 'utf8'
- );
- //Parse the repoList
- repoList = JSON.parse(repoList);
- //If repoList is empty we stop here.
- if (repoList.length === 0) {
- res.status(200).json({
- success: 'No repositories to analyse yet.',
- });
- return;
- }
-
- ////Call the shell : getStorageUsed.sh
- //Find the absolute path of the shells directory
- const shellsDirectory = path.join(process.cwd(), '/helpers');
- //Exec the shell
- const { stdout, stderr } = await exec(
- `${shellsDirectory}/shells/getStorageUsed.sh`
- );
- if (stderr) {
- res.status(500).json({
- status: 500,
- message:
- 'Error on getting storage, contact the administrator.',
- });
- return;
- }
- //Parse the JSON output of getStorageUsed.sh to use it
- const storageUsed = JSON.parse(stdout);
-
- //Rebuild a newRepoList with the storageUsed value updated
- let newRepoList = repoList;
- for (let index in newRepoList) {
- const repoFiltered = storageUsed.filter(
- (x) => x.name === newRepoList[index].repositoryName
- );
- if (repoFiltered.length === 1) {
- newRepoList[index].storageUsed = repoFiltered[0].size;
- }
- }
-
- //Stringify the repoList to write it into the json file.
- newRepoList = JSON.stringify(newRepoList);
- //Write the new json
- await fs.writeFile(
- jsonDirectory + '/repo.json',
- newRepoList,
- (err) => {
- if (err) console.log(err);
- }
- );
-
- res.status(200).json({
- success: 'Storage cron has been executed.',
- });
- } else {
- res.status(401).json({
- status: 401,
- message: 'Unauthorized',
- });
- }
- } catch (err) {
- console.log(err);
+ ////Call the shell : getStorageUsed.sh
+ //Find the absolute path of the shells directory
+ const shellsDirectory = path.join(process.cwd(), '/helpers');
+ //Exec the shell
+ const { stdout, stderr } = await exec(`${shellsDirectory}/shells/getStorageUsed.sh`);
+ if (stderr) {
res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator.',
+ status: 500,
+ message: 'Error on getting storage, contact the administrator.',
});
+ return;
+ }
+ //Parse the JSON output of getStorageUsed.sh to use it
+ const storageUsed = JSON.parse(stdout);
+
+ //Rebuild a newRepoList with the storageUsed value updated
+ let newRepoList = repoList;
+ for (let index in newRepoList) {
+ const repoFiltered = storageUsed.filter(
+ (x) => x.name === newRepoList[index].repositoryName
+ );
+ if (repoFiltered.length === 1) {
+ newRepoList[index].storageUsed = repoFiltered[0].size;
+ }
+ }
+
+ //Stringify the repoList to write it into the json file.
+ newRepoList = JSON.stringify(newRepoList);
+ //Write the new json
+ await fs.writeFile(jsonDirectory + '/repo.json', newRepoList, (err) => {
+ if (err) console.log(err);
+ });
+
+ res.status(200).json({
+ success: 'Storage cron has been executed.',
+ });
+ } else {
+ res.status(401).json({
+ status: 401,
+ message: 'Unauthorized',
+ });
}
+ } catch (err) {
+ console.log(err);
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator.',
+ });
+ }
}
diff --git a/pages/api/repo/add.js b/pages/api/repo/add.js
index 6359920..8fabcae 100644
--- a/pages/api/repo/add.js
+++ b/pages/api/repo/add.js
@@ -7,124 +7,109 @@ const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
export default async function handler(req, res) {
- if (req.method == 'POST') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- const {
- alias,
- sshPublicKey,
- size,
- comment,
- alert,
- lanCommand,
- appendOnlyMode,
- } = req.body;
- //We check that we receive data for each variable. Only "comment" and "lanCommand" are optional in the form.
- if (
- !alias ||
- !sshPublicKey ||
- !size ||
- typeof appendOnlyMode !== 'boolean' ||
- (!alert && alert !== 0)
- ) {
- //If a variable is empty.
- res.status(422).json({
- message: 'Unexpected data',
- });
- //A return to make sure we don't go any further if data are incorrect.
- return;
- }
-
- try {
- //console.log('API call (PUT)');
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let repoList = await fs.readFile(
- jsonDirectory + '/repo.json',
- 'utf8'
- );
- //Parse the repoList
- repoList = JSON.parse(repoList);
-
- //Find the first biggest ID available to assign it, so the highest ID is already the last added.
- let newID = 0;
- for (let element in repoList) {
- if (newID <= repoList[element].id) {
- newID = repoList[element].id + 1;
- }
- }
- //Create the new repo object
- const newRepo = {
- id: newID,
- alias: alias,
- repositoryName: '',
- status: false,
- lastSave: 0,
- alert: alert,
- storageSize: Number(size),
- storageUsed: 0,
- sshPublicKey: sshPublicKey,
- comment: comment,
- displayDetails: true,
- lanCommand: lanCommand,
- appendOnlyMode: appendOnlyMode,
- };
-
- ////Call the shell : createRepo.sh
- //Find the absolute path of the shells directory
- const shellsDirectory = path.join(process.cwd(), '/helpers');
- //Exec the shell
- const { stdout } = await exec(
- `${shellsDirectory}/shells/createRepo.sh "${newRepo.sshPublicKey}" ${newRepo.storageSize} ${newRepo.appendOnlyMode}`
- );
-
- newRepo.repositoryName = stdout.trim();
-
- //Create the new repoList with the new repo
- let newRepoList = [newRepo, ...repoList];
-
- //History the new repoList
- await repoHistory(newRepoList);
-
- //Stringify the newRepoList to write it into the json file.
- newRepoList = JSON.stringify(newRepoList);
-
- //Write the new json
- await fs.writeFile(
- jsonDirectory + '/repo.json',
- newRepoList,
- (err) => {
- if (err) console.log(err);
- }
- );
- res.status(200).json({ message: 'Envoi API réussi' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: error.stdout,
- });
- }
- return;
- }
- } else {
- res.status(405).json({
- status: 405,
- message: 'Method Not Allowed ',
- });
+ if (req.method == 'POST') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ const { alias, sshPublicKey, size, comment, alert, lanCommand, appendOnlyMode } = req.body;
+ //We check that we receive data for each variable. Only "comment" and "lanCommand" are optional in the form.
+ if (
+ !alias ||
+ !sshPublicKey ||
+ !size ||
+ typeof appendOnlyMode !== 'boolean' ||
+ (!alert && alert !== 0)
+ ) {
+ //If a variable is empty.
+ res.status(422).json({
+ message: 'Unexpected data',
+ });
+ //A return to make sure we don't go any further if data are incorrect.
+ return;
+ }
+
+ try {
+ //console.log('API call (PUT)');
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let repoList = await fs.readFile(jsonDirectory + '/repo.json', 'utf8');
+ //Parse the repoList
+ repoList = JSON.parse(repoList);
+
+ //Find the first biggest ID available to assign it, so the highest ID is already the last added.
+ let newID = 0;
+ for (let element in repoList) {
+ if (newID <= repoList[element].id) {
+ newID = repoList[element].id + 1;
+ }
+ }
+ //Create the new repo object
+ const newRepo = {
+ id: newID,
+ alias: alias,
+ repositoryName: '',
+ status: false,
+ lastSave: 0,
+ alert: alert,
+ storageSize: Number(size),
+ storageUsed: 0,
+ sshPublicKey: sshPublicKey,
+ comment: comment,
+ displayDetails: true,
+ lanCommand: lanCommand,
+ appendOnlyMode: appendOnlyMode,
+ };
+
+ ////Call the shell : createRepo.sh
+ //Find the absolute path of the shells directory
+ const shellsDirectory = path.join(process.cwd(), '/helpers');
+ //Exec the shell
+ const { stdout } = await exec(
+ `${shellsDirectory}/shells/createRepo.sh "${newRepo.sshPublicKey}" ${newRepo.storageSize} ${newRepo.appendOnlyMode}`
+ );
+
+ newRepo.repositoryName = stdout.trim();
+
+ //Create the new repoList with the new repo
+ let newRepoList = [newRepo, ...repoList];
+
+ //History the new repoList
+ await repoHistory(newRepoList);
+
+ //Stringify the newRepoList to write it into the json file.
+ newRepoList = JSON.stringify(newRepoList);
+
+ //Write the new json
+ await fs.writeFile(jsonDirectory + '/repo.json', newRepoList, (err) => {
+ if (err) console.log(err);
+ });
+ res.status(200).json({ message: 'Envoi API réussi' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: error.stdout,
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({
+ status: 405,
+ message: 'Method Not Allowed ',
+ });
+ }
}
diff --git a/pages/api/repo/id/[slug]/delete.js b/pages/api/repo/id/[slug]/delete.js
index 7eef893..d294069 100644
--- a/pages/api/repo/id/[slug]/delete.js
+++ b/pages/api/repo/id/[slug]/delete.js
@@ -7,112 +7,103 @@ const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
export default async function handler(req, res) {
- if (req.method == 'DELETE') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
- //If deletion is disabled on the server, return error
- if (process.env.DISABLE_DELETE_REPO === 'true') {
- res.status(403).json({
- status: 403,
- message: 'Deletion is disabled on this server',
- });
- return;
- }
- //The data we expect to receive
- const { toDelete } = req.body;
- ////We check that we receive toDelete and it must be a bool.
- if (typeof toDelete != 'boolean' || toDelete === false) {
- //If a variable is empty.
- res.status(422).json({
- message: 'Unexpected data',
- });
- //A return to make sure we don't go any further if data are incorrect.
- return;
- }
-
- try {
- //console.log('API call (DELETE)');
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let repoList = await fs.readFile(
- jsonDirectory + '/repo.json',
- 'utf8'
- );
- //Parse the repoList
- repoList = JSON.parse(repoList);
-
- //Find the ID in the repoList and delete the repo.
- //NOTE : req.query.slug return a string, so parseInt to use with indexOf.
- const indexToDelete = repoList
- .map((repo) => repo.id)
- .indexOf(parseInt(req.query.slug));
-
- ////Call the shell : deleteRepo.sh
- //Find the absolute path of the shells directory
- const shellsDirectory = path.join(process.cwd(), '/helpers');
- //Exec the shell
- const { stdout, stderr } = await exec(
- `${shellsDirectory}/shells/deleteRepo.sh ${repoList[indexToDelete].repositoryName}`
- );
- if (stderr) {
- console.log('stderr:', stderr);
- res.status(500).json({
- status: 500,
- message: 'Error on delete, contact the administrator.',
- });
- return;
- }
-
- //Delete the repo in the repoList
- if (indexToDelete !== -1) {
- repoList.splice(indexToDelete, 1);
- } else {
- console.log('The index to delete does not existe (-1)');
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- return;
- }
- //History the repoList
- await repoHistory(repoList);
- //Stringify the repoList to write it into the json file.
- repoList = JSON.stringify(repoList);
- //Write the new json
- await fs.writeFile(
- jsonDirectory + '/repo.json',
- repoList,
- (err) => {
- if (err) console.log(err);
- }
- );
-
- res.status(200).json({ message: 'Envoi API réussi' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
- } else {
- res.status(405).json({
- status: 405,
- message: 'Method Not Allowed ',
- });
+ if (req.method == 'DELETE') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+ //If deletion is disabled on the server, return error
+ if (process.env.DISABLE_DELETE_REPO === 'true') {
+ res.status(403).json({
+ status: 403,
+ message: 'Deletion is disabled on this server',
+ });
+ return;
+ }
+ //The data we expect to receive
+ const { toDelete } = req.body;
+ ////We check that we receive toDelete and it must be a bool.
+ if (typeof toDelete != 'boolean' || toDelete === false) {
+ //If a variable is empty.
+ res.status(422).json({
+ message: 'Unexpected data',
+ });
+ //A return to make sure we don't go any further if data are incorrect.
+ return;
+ }
+
+ try {
+ //console.log('API call (DELETE)');
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let repoList = await fs.readFile(jsonDirectory + '/repo.json', 'utf8');
+ //Parse the repoList
+ repoList = JSON.parse(repoList);
+
+ //Find the ID in the repoList and delete the repo.
+ //NOTE : req.query.slug return a string, so parseInt to use with indexOf.
+ const indexToDelete = repoList.map((repo) => repo.id).indexOf(parseInt(req.query.slug));
+
+ ////Call the shell : deleteRepo.sh
+ //Find the absolute path of the shells directory
+ const shellsDirectory = path.join(process.cwd(), '/helpers');
+ //Exec the shell
+ const { stdout, stderr } = await exec(
+ `${shellsDirectory}/shells/deleteRepo.sh ${repoList[indexToDelete].repositoryName}`
+ );
+ if (stderr) {
+ console.log('stderr:', stderr);
+ res.status(500).json({
+ status: 500,
+ message: 'Error on delete, contact the administrator.',
+ });
+ return;
+ }
+
+ //Delete the repo in the repoList
+ if (indexToDelete !== -1) {
+ repoList.splice(indexToDelete, 1);
+ } else {
+ console.log('The index to delete does not existe (-1)');
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ return;
+ }
+ //History the repoList
+ await repoHistory(repoList);
+ //Stringify the repoList to write it into the json file.
+ repoList = JSON.stringify(repoList);
+ //Write the new json
+ await fs.writeFile(jsonDirectory + '/repo.json', repoList, (err) => {
+ if (err) console.log(err);
+ });
+
+ res.status(200).json({ message: 'Envoi API réussi' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({
+ status: 405,
+ message: 'Method Not Allowed ',
+ });
+ }
}
diff --git a/pages/api/repo/id/[slug]/edit.js b/pages/api/repo/id/[slug]/edit.js
index 9726356..67dcb54 100644
--- a/pages/api/repo/id/[slug]/edit.js
+++ b/pages/api/repo/id/[slug]/edit.js
@@ -7,112 +7,95 @@ const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
export default async function handler(req, res) {
- if (req.method == 'PUT') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- //The data we expect to receive
- const {
- alias,
- sshPublicKey,
- size,
- comment,
- alert,
- lanCommand,
- appendOnlyMode,
- } = req.body;
- //Only "comment" and "lanCommand" are optional in the form.
- if (
- !alias ||
- !sshPublicKey ||
- !size ||
- typeof appendOnlyMode !== 'boolean' ||
- (!alert && alert !== 0)
- ) {
- res.status(422).json({
- message: 'Unexpected data',
- });
- return;
- }
-
- try {
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- let repoList = await fs.readFile(
- jsonDirectory + '/repo.json',
- 'utf8'
- );
- //Parse the repoList
- repoList = JSON.parse(repoList);
-
- //Find the index of the repo in repoList
- //NOTE : req.query.slug return a string, so parseInt to use with indexOf.
- const repoIndex = repoList
- .map((repo) => repo.id)
- .indexOf(parseInt(req.query.slug));
-
- ////Call the shell : updateRepo.sh
- //Find the absolute path of the shells directory
- const shellsDirectory = path.join(process.cwd(), '/helpers');
- // //Exec the shell
- await exec(
- `${shellsDirectory}/shells/updateRepo.sh ${repoList[repoIndex].repositoryName} "${sshPublicKey}" ${size} ${appendOnlyMode}`
- );
-
- //Find the ID in the data and change the values transmitted by the form
- let newRepoList = repoList.map((repo) =>
- repo.id == req.query.slug
- ? {
- ...repo,
- alias: alias,
- sshPublicKey: sshPublicKey,
- storageSize: Number(size),
- comment: comment,
- alert: alert,
- lanCommand: lanCommand,
- appendOnlyMode: appendOnlyMode,
- }
- : repo
- );
- //History the new repoList
- await repoHistory(newRepoList);
- //Stringify the newRepoList to write it into the json file.
- newRepoList = JSON.stringify(newRepoList);
- //Write the new json
- await fs.writeFile(
- jsonDirectory + '/repo.json',
- newRepoList,
- (err) => {
- if (err) console.log(err);
- }
- );
-
- res.status(200).json({ message: 'Envoi API réussi' });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: error.stdout,
- });
- }
- return;
- }
- } else {
- res.status(405).json({
- status: 405,
- message: 'Method Not Allowed ',
- });
+ if (req.method == 'PUT') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ //The data we expect to receive
+ const { alias, sshPublicKey, size, comment, alert, lanCommand, appendOnlyMode } = req.body;
+ //Only "comment" and "lanCommand" are optional in the form.
+ if (
+ !alias ||
+ !sshPublicKey ||
+ !size ||
+ typeof appendOnlyMode !== 'boolean' ||
+ (!alert && alert !== 0)
+ ) {
+ res.status(422).json({
+ message: 'Unexpected data',
+ });
+ return;
+ }
+
+ try {
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ let repoList = await fs.readFile(jsonDirectory + '/repo.json', 'utf8');
+ //Parse the repoList
+ repoList = JSON.parse(repoList);
+
+ //Find the index of the repo in repoList
+ //NOTE : req.query.slug return a string, so parseInt to use with indexOf.
+ const repoIndex = repoList.map((repo) => repo.id).indexOf(parseInt(req.query.slug));
+
+ ////Call the shell : updateRepo.sh
+ //Find the absolute path of the shells directory
+ const shellsDirectory = path.join(process.cwd(), '/helpers');
+ // //Exec the shell
+ await exec(
+ `${shellsDirectory}/shells/updateRepo.sh ${repoList[repoIndex].repositoryName} "${sshPublicKey}" ${size} ${appendOnlyMode}`
+ );
+
+ //Find the ID in the data and change the values transmitted by the form
+ let newRepoList = repoList.map((repo) =>
+ repo.id == req.query.slug
+ ? {
+ ...repo,
+ alias: alias,
+ sshPublicKey: sshPublicKey,
+ storageSize: Number(size),
+ comment: comment,
+ alert: alert,
+ lanCommand: lanCommand,
+ appendOnlyMode: appendOnlyMode,
+ }
+ : repo
+ );
+ //History the new repoList
+ await repoHistory(newRepoList);
+ //Stringify the newRepoList to write it into the json file.
+ newRepoList = JSON.stringify(newRepoList);
+ //Write the new json
+ await fs.writeFile(jsonDirectory + '/repo.json', newRepoList, (err) => {
+ if (err) console.log(err);
+ });
+
+ res.status(200).json({ message: 'Envoi API réussi' });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: error.stdout,
+ });
+ }
+ return;
+ }
+ } else {
+ res.status(405).json({
+ status: 405,
+ message: 'Method Not Allowed ',
+ });
+ }
}
diff --git a/pages/api/repo/id/[slug]/index.js b/pages/api/repo/id/[slug]/index.js
index 7462858..309d2d7 100644
--- a/pages/api/repo/id/[slug]/index.js
+++ b/pages/api/repo/id/[slug]/index.js
@@ -4,57 +4,54 @@ import { authOptions } from '../../../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'GET') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- res.status(401).json({ message: 'You must be logged in.' });
- return;
- }
-
- try {
- //console.log('API call (GET)');
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- //Read the json data file data.json
- let repoList = await fs.readFile(
- jsonDirectory + '/repo.json',
- 'utf8'
- );
- //Parse the json data file who has been read
- repoList = JSON.parse(repoList);
- //Find the ID (req.query.slug) in RepoList and put the repo in a single object (repo).
- let repo;
- for (let element in repoList) {
- if (repoList[element].id == req.query.slug) {
- repo = repoList[element];
- }
- }
- //If no repo is found --> 404.
- if (!repo) {
- res.status(404).json({
- message: 'No repository with id #' + req.query.slug,
- });
- return;
- }
- // Send the response and return the repo object --> 200
- res.status(200).json({ repo });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator',
- });
- }
- return;
- }
+ if (req.method == 'GET') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).json({ message: 'You must be logged in.' });
+ return;
}
+
+ try {
+ //console.log('API call (GET)');
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ //Read the json data file data.json
+ let repoList = await fs.readFile(jsonDirectory + '/repo.json', 'utf8');
+ //Parse the json data file who has been read
+ repoList = JSON.parse(repoList);
+ //Find the ID (req.query.slug) in RepoList and put the repo in a single object (repo).
+ let repo;
+ for (let element in repoList) {
+ if (repoList[element].id == req.query.slug) {
+ repo = repoList[element];
+ }
+ }
+ //If no repo is found --> 404.
+ if (!repo) {
+ res.status(404).json({
+ message: 'No repository with id #' + req.query.slug,
+ });
+ return;
+ }
+ // Send the response and return the repo object --> 200
+ res.status(200).json({ repo });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator',
+ });
+ }
+ return;
+ }
+ }
}
diff --git a/pages/api/repo/index.js b/pages/api/repo/index.js
index 4d350c6..f5d6790 100644
--- a/pages/api/repo/index.js
+++ b/pages/api/repo/index.js
@@ -4,51 +4,45 @@ import { authOptions } from '../../../pages/api/auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
- if (req.method == 'GET') {
- //Verify that the user is logged in.
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- // res.status(401).json({ message: 'You must be logged in.' });
- res.status(401).end();
- return;
- }
-
- try {
- //console.log('API call (GET)');
- //Find the absolute path of the json directory
- const jsonDirectory = path.join(process.cwd(), '/config');
- //Check if the repo.json file exists and initialize it if not.
- if (!fs.existsSync(jsonDirectory + '/repo.json')) {
- fs.writeFileSync(
- jsonDirectory + '/repo.json',
- JSON.stringify([])
- );
- }
- //Read the file repo.json
- let repoList = await fs.promises.readFile(
- jsonDirectory + '/repo.json',
- 'utf8'
- );
- //Parse the JSON
- repoList = JSON.parse(repoList);
- //Send the response
- res.status(200).json({ repoList });
- } catch (error) {
- //Log for backend
- console.log(error);
- //Log for frontend
- if (error.code == 'ENOENT') {
- res.status(500).json({
- status: 500,
- message: 'No such file or directory',
- });
- } else {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator !',
- });
- }
- return;
- }
+ if (req.method == 'GET') {
+ //Verify that the user is logged in.
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ // res.status(401).json({ message: 'You must be logged in.' });
+ res.status(401).end();
+ return;
}
+
+ try {
+ //console.log('API call (GET)');
+ //Find the absolute path of the json directory
+ const jsonDirectory = path.join(process.cwd(), '/config');
+ //Check if the repo.json file exists and initialize it if not.
+ if (!fs.existsSync(jsonDirectory + '/repo.json')) {
+ fs.writeFileSync(jsonDirectory + '/repo.json', JSON.stringify([]));
+ }
+ //Read the file repo.json
+ let repoList = await fs.promises.readFile(jsonDirectory + '/repo.json', 'utf8');
+ //Parse the JSON
+ repoList = JSON.parse(repoList);
+ //Send the response
+ res.status(200).json({ repoList });
+ } catch (error) {
+ //Log for backend
+ console.log(error);
+ //Log for frontend
+ if (error.code == 'ENOENT') {
+ res.status(500).json({
+ status: 500,
+ message: 'No such file or directory',
+ });
+ } else {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator !',
+ });
+ }
+ return;
+ }
+ }
}
diff --git a/pages/api/version/index.js b/pages/api/version/index.js
index f2b4123..de51940 100644
--- a/pages/api/version/index.js
+++ b/pages/api/version/index.js
@@ -1,16 +1,16 @@
import packageInfo from '../../../package.json';
export default async function handler(req, res) {
- if (req.method === 'GET') {
- try {
- res.status(200).json({ version: packageInfo.version });
- return;
- } catch (error) {
- res.status(500).json({
- status: 500,
- message: 'API error, contact the administrator !',
- });
- return;
- }
+ if (req.method === 'GET') {
+ try {
+ res.status(200).json({ version: packageInfo.version });
+ return;
+ } catch (error) {
+ res.status(500).json({
+ status: 500,
+ message: 'API error, contact the administrator !',
+ });
+ return;
}
+ }
}
diff --git a/pages/index.js b/pages/index.js
index 95de8fe..b4db2c8 100644
--- a/pages/index.js
+++ b/pages/index.js
@@ -8,46 +8,42 @@ import Head from 'next/head';
import RepoList from '../Containers/RepoList/RepoList';
export default function Index() {
- const { status } = useSession();
+ const { status } = useSession();
- return (
+ return (
+ <>
+ {status === 'unauthenticated' || status === 'loading' ? null : (
<>
- {status === 'unauthenticated' || status === 'loading' ? null : (
- <>
-
- {/*
+ {/*
*/}
-
Repositories - BorgWarehouse
-
-
- >
- )}
+
Repositories - BorgWarehouse
+
+
>
- );
+ )}
+ >
+ );
}
export async function getServerSideProps(context) {
- //Var
- const session = await getServerSession(
- context.req,
- context.res,
- authOptions
- );
-
- if (!session) {
- return {
- redirect: {
- destination: '/login',
- permanent: false,
- },
- };
- }
+ //Var
+ const session = await getServerSession(context.req, context.res, authOptions);
+ if (!session) {
return {
- props: {},
+ redirect: {
+ destination: '/login',
+ permanent: false,
+ },
};
+ }
+
+ return {
+ props: {},
+ };
}
diff --git a/pages/login.js b/pages/login.js
index c96338e..f523c3c 100644
--- a/pages/login.js
+++ b/pages/login.js
@@ -11,182 +11,169 @@ import { getServerSession } from 'next-auth/next';
import Error from '../Components/UI/Error/Error';
export default function Login() {
- //Var
- const {
- register,
- handleSubmit,
- formState: { errors },
- reset,
- } = useForm();
- const router = useRouter();
+ //Var
+ const {
+ register,
+ handleSubmit,
+ formState: { errors },
+ reset,
+ } = useForm();
+ const router = useRouter();
- //State
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState();
+ //State
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState();
- //Functions
- const formSubmitHandler = async (data) => {
- setIsLoading(true);
- setError(null);
- const resultat = await signIn('credentials', {
- username: data.username,
- password: data.password,
- redirect: false,
- });
+ //Functions
+ const formSubmitHandler = async (data) => {
+ setIsLoading(true);
+ setError(null);
+ const resultat = await signIn('credentials', {
+ username: data.username,
+ password: data.password,
+ redirect: false,
+ });
- setIsLoading(false);
+ setIsLoading(false);
- if (resultat.error) {
- reset();
- setError(resultat.error);
- setTimeout(() => setError(), 4000);
- } else {
- router.replace('/');
- }
- };
+ if (resultat.error) {
+ reset();
+ setError(resultat.error);
+ setTimeout(() => setError(), 4000);
+ } else {
+ router.replace('/');
+ }
+ };
- return (
-
+
+
-
-
+ BorgWarehouse
+
+
+ Sign in to your account.
+
+ {error && }
+
-
-
- );
+ {errors.username.message}
+
+ )}
+
+
+
+ {errors.password && (
+
+ {errors.password.message}
+
+ )}
+
+
+
+ {isLoading ? (
+
+ ) : (
+ 'Sign in'
+ )}
+
+
+
+
+
+
+ );
}
export async function getServerSideProps(context) {
- //Var
- const session = await getServerSession(
- context.req,
- context.res,
- authOptions
- );
-
- //Here, if I am connected, I redirect to the home page.
- if (session) {
- return {
- redirect: {
- destination: '/',
- permanent: false,
- },
- };
- }
+ //Var
+ const session = await getServerSession(context.req, context.res, authOptions);
+ //Here, if I am connected, I redirect to the home page.
+ if (session) {
return {
- props: { session },
+ redirect: {
+ destination: '/',
+ permanent: false,
+ },
};
+ }
+
+ return {
+ props: { session },
+ };
}
diff --git a/pages/manage-repo/add.js b/pages/manage-repo/add.js
index 8e2576b..7288ab5 100644
--- a/pages/manage-repo/add.js
+++ b/pages/manage-repo/add.js
@@ -3,27 +3,23 @@ import { authOptions } from '../../pages/api/auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default function Add() {
- return
;
}
export async function getServerSideProps(context) {
- //Var
- const session = await getServerSession(
- context.req,
- context.res,
- authOptions
- );
-
- if (!session) {
- return {
- redirect: {
- destination: '/login',
- permanent: false,
- },
- };
- }
+ //Var
+ const session = await getServerSession(context.req, context.res, authOptions);
+ if (!session) {
return {
- props: {},
+ redirect: {
+ destination: '/login',
+ permanent: false,
+ },
};
+ }
+
+ return {
+ props: {},
+ };
}
diff --git a/pages/manage-repo/edit/[slug].js b/pages/manage-repo/edit/[slug].js
index 3a7496a..d878820 100644
--- a/pages/manage-repo/edit/[slug].js
+++ b/pages/manage-repo/edit/[slug].js
@@ -3,27 +3,23 @@ import { authOptions } from '../../../pages/api/auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default function Add() {
- return
;
}
export async function getServerSideProps(context) {
- //Var
- const session = await getServerSession(
- context.req,
- context.res,
- authOptions
- );
-
- if (!session) {
- return {
- redirect: {
- destination: '/login',
- permanent: false,
- },
- };
- }
+ //Var
+ const session = await getServerSession(context.req, context.res, authOptions);
+ if (!session) {
return {
- props: {},
+ redirect: {
+ destination: '/login',
+ permanent: false,
+ },
};
+ }
+
+ return {
+ props: {},
+ };
}
diff --git a/pages/monitoring/index.js b/pages/monitoring/index.js
index bd4225c..3832b87 100644
--- a/pages/monitoring/index.js
+++ b/pages/monitoring/index.js
@@ -6,63 +6,59 @@ import { getServerSession } from 'next-auth/next';
import StorageUsedChartBar from '../../Containers/Monitoring/StorageUsedChartBar/StorageUsedChartBar';
export default function Monitoring() {
- return (
- <>
-
-
+ >
+ );
}
export async function getServerSideProps(context) {
- //Var
- const session = await getServerSession(
- context.req,
- context.res,
- authOptions
- );
-
- if (!session) {
- return {
- redirect: {
- destination: '/login',
- permanent: false,
- },
- };
- }
+ //Var
+ const session = await getServerSession(context.req, context.res, authOptions);
+ if (!session) {
return {
- props: {},
+ redirect: {
+ destination: '/login',
+ permanent: false,
+ },
};
+ }
+
+ return {
+ props: {},
+ };
}
diff --git a/pages/setup-wizard/[slug].js b/pages/setup-wizard/[slug].js
index fbcb229..3d1691a 100644
--- a/pages/setup-wizard/[slug].js
+++ b/pages/setup-wizard/[slug].js
@@ -6,38 +6,34 @@ import { authOptions } from '../../pages/api/auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default function SetupWizardStep() {
- ////Var
- const router = useRouter();
- const step = router.query.slug;
+ ////Var
+ const router = useRouter();
+ const step = router.query.slug;
- return (
- <>
-
-
+ >
+ );
}
export async function getServerSideProps(context) {
- //Var
- const session = await getServerSession(
- context.req,
- context.res,
- authOptions
- );
-
- if (!session) {
- return {
- redirect: {
- destination: '/login',
- permanent: false,
- },
- };
- }
+ //Var
+ const session = await getServerSession(context.req, context.res, authOptions);
+ if (!session) {
return {
- props: {},
+ redirect: {
+ destination: '/login',
+ permanent: false,
+ },
};
+ }
+
+ return {
+ props: {},
+ };
}
diff --git a/styles/default.css b/styles/default.css
index a48897e..bcf464d 100644
--- a/styles/default.css
+++ b/styles/default.css
@@ -1,213 +1,212 @@
* {
- box-sizing: border-box;
+ box-sizing: border-box;
}
@font-face {
- font-family: 'Inter';
- src: url('/font/Inter/Inter-VariableFont_slnt,wght.ttf') format('truetype');
+ font-family: 'Inter';
+ src: url('/font/Inter/Inter-VariableFont_slnt,wght.ttf') format('truetype');
}
body {
- margin: 0;
- font-family: Inter, sans-serif;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- background-color: #fafafa;
+ margin: 0;
+ font-family: Inter, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ background-color: #fafafa;
}
/* Disable scrollbar for chrome */
::-webkit-scrollbar {
- display: none;
+ display: none;
}
code {
- font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
- monospace;
+ font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}
.defaultButton {
- border: 0;
- padding: 10px 15px;
- background-color: #6d4aff;
- color: white;
- border-radius: 4px;
- cursor: pointer;
- text-decoration: none;
- font-weight: bold;
- font-size: 1em;
+ border: 0;
+ padding: 10px 15px;
+ background-color: #6d4aff;
+ color: white;
+ border-radius: 4px;
+ cursor: pointer;
+ text-decoration: none;
+ font-weight: bold;
+ font-size: 1em;
}
.defaultButton:hover {
- border: 0;
- padding: 10px 15px;
- background-color: #4f31ce;
- color: white;
- border-radius: 4px;
- cursor: pointer;
- text-decoration: none;
- font-weight: bold;
- font-size: 1em;
+ border: 0;
+ padding: 10px 15px;
+ background-color: #4f31ce;
+ color: white;
+ border-radius: 4px;
+ cursor: pointer;
+ text-decoration: none;
+ font-weight: bold;
+ font-size: 1em;
}
.defaultButton:active {
- border: 0;
- padding: 10px 15px;
- background-color: #4f31ce;
- color: white;
- border-radius: 4px;
- cursor: pointer;
- text-decoration: none;
- font-weight: bold;
- font-size: 1em;
- transform: scale(0.9);
+ border: 0;
+ padding: 10px 15px;
+ background-color: #4f31ce;
+ color: white;
+ border-radius: 4px;
+ cursor: pointer;
+ text-decoration: none;
+ font-weight: bold;
+ font-size: 1em;
+ transform: scale(0.9);
}
.defaultButton:disabled {
- opacity: 0.3;
- cursor: not-allowed;
- pointer-events: none;
+ opacity: 0.3;
+ cursor: not-allowed;
+ pointer-events: none;
}
/* signIn */
.signInContainer {
- display: 'flex';
- flex-direction: 'column';
- justify-content: 'center';
- align-items: 'center';
- height: calc(100vh - 100px);
- animation: signInAnim 1s ease 0s 1 normal forwards;
+ display: 'flex';
+ flex-direction: 'column';
+ justify-content: 'center';
+ align-items: 'center';
+ height: calc(100vh - 100px);
+ animation: signInAnim 1s ease 0s 1 normal forwards;
}
@keyframes signInAnim {
- 0% {
- opacity: 0;
- transform: translateY(-250px);
- }
+ 0% {
+ opacity: 0;
+ transform: translateY(-250px);
+ }
- 100% {
- opacity: 1;
- transform: translateY(0);
- }
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ }
}
.signInInput {
- background: #262e49;
- background-color: #262e49;
- border: 1px solid #6d4aff21;
- font-size: 16px;
- height: auto;
- margin: 0;
- margin-bottom: 0px;
- outline: 0;
- padding: 15px;
- width: 100%;
- border-radius: 5px;
- color: #d6d6d6;
- box-shadow: 0 1px 0 rgba(0, 0, 0, 0.03) inset;
+ background: #262e49;
+ background-color: #262e49;
+ border: 1px solid #6d4aff21;
+ font-size: 16px;
+ height: auto;
+ margin: 0;
+ margin-bottom: 0px;
+ outline: 0;
+ padding: 15px;
+ width: 100%;
+ border-radius: 5px;
+ color: #d6d6d6;
+ box-shadow: 0 1px 0 rgba(0, 0, 0, 0.03) inset;
}
.signInInput:focus {
- outline: 1px solid #6d4aff;
- box-shadow: 0 0 10px 3px rgba(110, 74, 255, 0.605);
+ outline: 1px solid #6d4aff;
+ box-shadow: 0 0 10px 3px rgba(110, 74, 255, 0.605);
}
.signInInput.invalid {
- background: #f3c7c7;
- border: 1px solid #e45454;
- outline: 1px solid #ff4a4a;
+ background: #f3c7c7;
+ border: 1px solid #e45454;
+ outline: 1px solid #ff4a4a;
}
.signInInput.invalid:focus {
- background: #f3c7c7;
- border: 1px solid #e45454;
- outline: 1px solid #ff4a4a;
- box-shadow: 0 0 10px 3px rgba(255, 74, 74, 0.605);
+ background: #f3c7c7;
+ border: 1px solid #e45454;
+ outline: 1px solid #ff4a4a;
+ box-shadow: 0 0 10px 3px rgba(255, 74, 74, 0.605);
}
.signInButton {
- border: 0;
- padding: 10px 15px;
- background-color: #6d4aff;
- color: #dfdeee;
- margin: 5px;
- border-radius: 100px;
- cursor: pointer;
- text-decoration: none;
- font-size: 1em;
+ border: 0;
+ padding: 10px 15px;
+ background-color: #6d4aff;
+ color: #dfdeee;
+ margin: 5px;
+ border-radius: 100px;
+ cursor: pointer;
+ text-decoration: none;
+ font-size: 1em;
}
.signInButton:hover {
- border: 0;
- padding: 10px 15px;
- background-color: #4f31ce;
- color: #dfdeee;
- margin: 5px;
- border-radius: 100px;
- cursor: pointer;
- text-decoration: none;
- font-size: 1em;
+ border: 0;
+ padding: 10px 15px;
+ background-color: #4f31ce;
+ color: #dfdeee;
+ margin: 5px;
+ border-radius: 100px;
+ cursor: pointer;
+ text-decoration: none;
+ font-size: 1em;
}
.signInButton:active {
- border: 0;
- padding: 10px 15px;
- background-color: #4f31ce;
- color: #dfdeee;
- margin: 5px;
- border-radius: 100px;
- cursor: pointer;
- text-decoration: none;
- font-size: 1em;
- transform: scale(0.9);
+ border: 0;
+ padding: 10px 15px;
+ background-color: #4f31ce;
+ color: #dfdeee;
+ margin: 5px;
+ border-radius: 100px;
+ cursor: pointer;
+ text-decoration: none;
+ font-size: 1em;
+ transform: scale(0.9);
}
.signInButton:disabled {
- opacity: 0.3;
- cursor: not-allowed;
- pointer-events: none;
+ opacity: 0.3;
+ cursor: not-allowed;
+ pointer-events: none;
}
.heart {
- color: #6d4aff;
+ color: #6d4aff;
}
.heart::before {
- content: '\f004';
+ content: '\f004';
}
/* Radio group and radio button */
.radio-group {
- display: flex;
+ display: flex;
}
.radio-group input[type='radio']:checked + span::before {
- background-color: #6d4aff;
- box-shadow: inset white 0 0 0 2px;
+ background-color: #6d4aff;
+ box-shadow: inset white 0 0 0 2px;
}
.radio-group span::before {
- border: 2px solid #6d4aff;
- content: '';
- display: flex;
- height: 16px;
- width: 16px;
- margin: 0 5px;
- border-radius: 50%;
- box-sizing: border-box;
- transition: all ease 0.2s;
- box-shadow: inset white 0 0 0 10px;
+ border: 2px solid #6d4aff;
+ content: '';
+ display: flex;
+ height: 16px;
+ width: 16px;
+ margin: 0 5px;
+ border-radius: 50%;
+ box-sizing: border-box;
+ transition: all ease 0.2s;
+ box-shadow: inset white 0 0 0 10px;
}
.radio-group label {
- margin: 0 8px 0 0;
- cursor: pointer;
+ margin: 0 8px 0 0;
+ cursor: pointer;
}
.radio-group input[type='radio'] {
- opacity: 0;
- width: 0;
+ opacity: 0;
+ width: 0;
}
.radio-group span {
- display: flex;
- align-items: center;
+ display: flex;
+ align-items: center;
}