CEO updated

This commit is contained in:
andrei-mihnea-cerbu
2024-04-20 03:18:44 +03:00
parent 869305a491
commit 57c2c7ec55
81 changed files with 3517 additions and 1035 deletions
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<includedPredefinedLibrary name="Node.js Core" />
</component>
</project>
+1
View File
@@ -0,0 +1 @@
{}
+36
View File
@@ -0,0 +1,36 @@
const httpStatus = {
// Informational
CONTINUE: 100,
SWITCHING_PROTOCOLS: 101,
PROCESSING: 102,
// Success
OK: 200,
CREATED: 201,
ACCEPTED: 202,
NO_CONTENT: 204,
// Redirection
MOVED_PERMANENTLY: 301,
FOUND: 302,
SEE_OTHER: 303,
NOT_MODIFIED: 304,
TEMPORARY_REDIRECT: 307,
// Client Error
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
METHOD_NOT_ALLOWED: 405,
CONFLICT: 409,
GONE: 410,
UNSUPPORTED_MEDIA_TYPE: 415,
// Server Error
INTERNAL_SERVER_ERROR: 500,
NOT_IMPLEMENTED: 501,
SERVICE_UNAVAILABLE: 503
};
module.exports = { httpStatus };
+33
View File
@@ -0,0 +1,33 @@
const lockfile = require('proper-lockfile');
async function lockFile(filePath) {
try {
await lockfile.lock(filePath, {
realpath: false,
retries: {
retries: 10, // Number of retries
factor: 2, // The exponential factor
minTimeout: 1000, // The number of milliseconds before starting the first retry
maxTimeout: 5000, // The maximum number of milliseconds between two retries
randomize: true, // Randomizes the timeouts by multiplying with a factor between 1 to 2
}
});
console.log(`File locked: ${filePath}`);
} catch (error) {
console.error(`Error locking file ${filePath}: ${error.message}`);
throw error; // Propagate the error if unable to lock after retries
}
}
async function unlockFile(filePath) {
try {
await lockfile.unlock(filePath);
console.log(`File unlocked: ${filePath}`);
} catch (error) {
console.error(`Error unlocking file ${filePath}: ${error.message}`);
// Decide whether to throw the error or not, based on your error handling strategy
throw error;
}
}
module.exports = {lockFile, unlockFile}
+1
View File
@@ -0,0 +1 @@
/ϋ Ν=η9Ϋ υuόDζΧHαΫΐΎ[
+1
View File
@@ -0,0 +1 @@
睇アbアィ ・/釞@
+365
View File
@@ -0,0 +1,365 @@
const fsPromises = require('fs').promises; // Ensure you use the promise-based API
const fs = require('fs');
const path = require('path');
const { decryptFileInPlace, encryptFileInPlace, encryptFileWithKey, decryptFileWithKey} = require("../src/main/aes_encrypt");
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
async function decryptAndGetServerIP(filePath) {
try {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
await encryptFileInPlace(filePath)
await unlockFile(filePath);
return serverIP;
} catch (error) {
console.error('An error occurred:', error);
return null;
}
}
function extractFilePaths(directoryStructure) {
let paths = [];
const traverse = (dir, currentPath) => {
Object.keys(dir).forEach(key => {
if (key === 'files') {
dir[key].forEach(file => paths.push(path.join(currentPath, file)));
} else {
traverse(dir[key], path.join(currentPath, key));
}
});
};
traverse(directoryStructure, '');
return paths;
}
async function fetchFiles(ip, filePaths) {
let results = {};
for (const filePath of filePaths) {
const url = `http://${ip}:3000/file_path`;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ filePath })
});
if (!response.ok) throw new Error(`HTTP status ${response.status}`);
const arrayBuffer = await response.arrayBuffer(); // Fetch the response as an ArrayBuffer
results[filePath] = Buffer.from(arrayBuffer);
} catch (error) {
console.error(`Error fetching ${filePath}:`, error);
results[filePath] = null;
}
}
return results;
}
async function removeDirectory(directoryPath) {
try {
// Check if the directory exists
const stats = await fsPromises.stat(directoryPath);
if (!stats.isDirectory()) {
console.log('The specified path is not a directory.');
return;
}
// Read all the contents of the directory
const files = await fsPromises.readdir(directoryPath);
// Loop through each file/directory and delete them
for (const file of files) {
const currentPath = path.join(directoryPath, file);
const currentStats = await fsPromises.stat(currentPath);
if (currentStats.isDirectory()) {
// Recursive call for directories
await removeDirectory(currentPath);
} else {
await lockFile(currentPath);
await unlockFile(currentPath);
await fsPromises.unlink(currentPath);
}
}
// Finally, delete the directory itself
await fsPromises.rmdir(directoryPath);
//console.log(`Directory removed: ${directoryPath}`);
} catch (error) {
console.error(`Error removing directory: ${error.message}`);
}
}
async function decryptUserSystemConfig() {
const configPath = path.join(__dirname, '..', 'usersInSystem.json');
await lockFile(configPath);
await decryptFileInPlace(configPath);
}
async function encryptUserSystemConfig(){
const configPath = path.join(__dirname, '..', 'usersInSystem.json');
await encryptFileInPlace(configPath);
await unlockFile(configPath);
}
async function processBackup() {
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
const backupConfigPath = path.join(__dirname, '..', 'backupSchemes.json');
const baseBackupDirPath = path.join(__dirname, '..', 'backup_directories');
if(!fs.existsSync(backupConfigPath) || !fs.existsSync(usersConfigPath)){
console.log('Can\'t start backup system: necessary files missing!');
return;
}
await decryptUserSystemConfig();
try {
// Read and parse the users configuration
const usersData = await fsPromises.readFile(usersConfigPath, 'utf8');
const usersConfig = JSON.parse(usersData);
// Read and parse the backup configuration
const backupData = await fsPromises.readFile(backupConfigPath, 'utf8');
const jsonData = JSON.parse(backupData);
for (const key in jsonData) {
const userBackupDir = path.join(baseBackupDirPath, key);
await removeDirectory(userBackupDir);
const node = jsonData[key];
const directoryStructure = JSON.parse(node.directoryStructure);
const filePaths = extractFilePaths(directoryStructure);
const files = await fetchFiles(node.ip, filePaths);
await fsPromises.mkdir(userBackupDir, { recursive: true });
// Find the encryption key for the user's department
let encryptionKey = '';
for (const dept in usersConfig) {
if (usersConfig[dept].users.includes(key)) {
encryptionKey = usersConfig[dept].key;
break;
}
}
for (const file in files) {
if (files[file]) {
const fullPath = path.join(userBackupDir, file);
await fsPromises.mkdir(path.dirname(fullPath), { recursive: true });
await fsPromises.writeFile(fullPath, files[file]); // Write the binary data
// Encrypt the file in place after writing it
if (encryptionKey) {
await encryptFileWithKey(fullPath, encryptionKey);
}
}
}
}
} catch (error) {
console.error('Failed to read or process the JSON file:', error);
}
await encryptUserSystemConfig();
}
async function getAllFilePaths(dirPath) {
let filePaths = [];
async function recurse(currentPath) {
const entries = await fsPromises.readdir(currentPath, { withFileTypes: true });
// Create promises for each entry and process them in parallel
const entryPromises = entries.map(async (entry) => {
const resolvedPath = path.join(currentPath, entry.name);
if (entry.isDirectory()) {
// If it's a directory, recurse into it
await recurse(resolvedPath);
} else {
// If it's a file, add it to the file paths array
filePaths.push(resolvedPath);
}
});
// Wait for all promises to complete
await Promise.all(entryPromises);
}
await recurse(dirPath);
return filePaths;
}
async function decryptBackupFilesToDirectory(destinationDir) {
await decryptUserSystemConfig();
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
if(!fs.existsSync(usersConfigPath)){
return false;
}
const usersConfig = JSON.parse(await fsPromises.readFile(usersConfigPath, 'utf8'));
const sourceDir = path.join(__dirname, '..', 'backup_directories');
await removeDirectory(destinationDir);
try {
for (const department in usersConfig) {
const { key, users } = usersConfig[department];
for (const userId of users) {
const userDir = path.join(sourceDir, userId);
try {
const files = await getAllFilePaths(userDir);
for (const filePath of files) {
const stats = await fsPromises.stat(filePath);
if (stats.isFile()) {
const relativePath = path.relative(userDir, filePath);
// Construct the destination file path
const destinationFilePath = path.join(destinationDir, userId, relativePath);
await fsPromises.mkdir(path.dirname(destinationFilePath), { recursive: true });
await lockFile(filePath);
// Decrypt the file in its original location
await decryptFileWithKey(filePath, key);
// Copy the decrypted file to the destination directory
await fsPromises.copyFile(filePath, destinationFilePath);
console.log(`Decrypted file copied to: ${destinationFilePath}`);
// Re-encrypt the file in its original location (optional)
await encryptFileWithKey(filePath, key);
await unlockFile(filePath);
}
}
} catch (error) {
console.error(`Error processing files for user ${userId}: ${error.message}`);
await encryptUserSystemConfig();
return false;
}
}
}
} catch (error) {
console.error(`Error processing decryption: ${error.message}`);
await encryptUserSystemConfig();
return false;
}
await encryptUserSystemConfig();
return true;
}
async function decryptDepartmentFilesToDirectory() {
const dirDepartmentPath = path.join(__dirname, '..', 'dirDepartment.json');
const loginDataPath = path.join(__dirname, '..', 'loginData.json');
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
const sourceDir = path.join(__dirname, '..', 'backup_directories');
if (!fs.existsSync(usersConfigPath) || !fs.existsSync(loginDataPath) || !fs.existsSync(dirDepartmentPath)) {
console.error("Missing one or more essential configuration files.");
return false;
}
await lockFile(loginDataPath);
await lockFile(usersConfigPath);
await decryptFileInPlace(loginDataPath);
await decryptFileInPlace(usersConfigPath);
const { path: destinationDir } = JSON.parse(await fsPromises.readFile(dirDepartmentPath, 'utf8'));
const { department } = JSON.parse(await fsPromises.readFile(loginDataPath, 'utf8'));
const usersConfig = JSON.parse(await fsPromises.readFile(usersConfigPath, 'utf8'));
// Check if department exists in users configuration
if (!usersConfig[department]) {
console.error(`No configuration found for department: ${department}`);
return false;
}
const { key, users } = usersConfig[department];
await encryptFileInPlace(loginDataPath);
await encryptFileInPlace(usersConfigPath);
await unlockFile(loginDataPath);
await unlockFile(usersConfigPath);
await removeDirectory(destinationDir);
for (const userId of users) {
const userDir = path.join(sourceDir, userId);
try {
const files = await getAllFilePaths(userDir);
console.log(`Processing files for user ${userId}: ${files}`);
for (const filePath of files) {
const stats = await fsPromises.stat(filePath);
if (stats.isFile()) {
const relativePath = path.relative(userDir, filePath);
// Construct the destination file path
const destinationFilePath = path.join(destinationDir, userId, relativePath);
await fsPromises.mkdir(path.dirname(destinationFilePath), { recursive: true });
// Decrypt the file in its original location
await decryptFileWithKey(filePath, key);
// Copy the decrypted file to the destination directory
await fsPromises.copyFile(filePath, destinationFilePath);
console.log(`Decrypted file copied to: ${destinationFilePath}`);
// Re-encrypt the file in its original location (optional)
await encryptFileWithKey(filePath, key);
}
}
} catch (error) {
console.error(`Error processing files for user ${userId}: ${error.message}`);
return false;
}
}
console.log("All files processed successfully.");
return true;
}
let serverIp = null;
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
const timeoutInterval = 7 * 60 * 1000 //minutes * seconds * miliseconds
setInterval(async () => {
await decryptDepartmentFilesToDirectory();
}, timeoutInterval);
console.log('backup.js process started!');
process.on('SIGINT', async () => {
console.log('Shutdown signal received in \'backup.js\'. Cleaning up...');
try {
console.log('Performing cleanup tasks...');
console.log('Cleanup completed successfully.');
} catch (error) {
console.error('An error occurred during cleanup:', error);
} finally {
console.log('Process terminated');
process.exit(0);
}
});
process.on('message', async (message) => {
if (message.type === 'startBackup') {
console.log('BackupProcess: Received command to start backup.');
await processBackup()
}
if(message.type === 'decryptBackup'){
console.log(`BackupProcess: Received command to decrypt backup to ${message.decryptDestPath}`);
console.log(message.decryptDestPath);
await decryptBackupFilesToDirectory(message.decryptDestPath);
}
});
+187
View File
@@ -0,0 +1,187 @@
const express = require('express');
const fs = require('fs');
const multer = require('multer');
const fsExtra = require('fs-extra');
const path = require('path');
const Joi = require('joi');
const { httpStatus } = require('../helpers/http_status');
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
const app = express();
app.use(express.json());
app.use('/share_file', express.raw({ type: 'application/octet-stream', limit: 'Infinity' }));
const server = require('http').createServer(app);
const connections = [];
// Store active connections to close them on shutdown
server.on('connection', (conn) => {
connections.push(conn);
conn.on('close', () => {
connections.splice(connections.indexOf(conn), 1);
});
});
const filePathSchema = Joi.object({
filePath: Joi.string().required()
});
async function getBaseDirectory() {
const filePath = path.join(__dirname, '..', 'dirBackup.json');
try {
const data = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(data);
return jsonData.path;
} catch (error) {
console.error('Error reading the base directory:', error);
throw error;
}
}
app.post('/file_path', async (req, res) => {
const { error, value } = filePathSchema.validate(req.body);
if (error) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Invalid input',
data: error.details
});
}
try {
const basePath = await getBaseDirectory();
let { filePath } = value;
const baseDirName = path.basename(basePath);
if (filePath.startsWith(baseDirName + path.sep)) {
filePath = filePath.slice(baseDirName.length + 1);
}
const fullPath = path.resolve(basePath, filePath);
fs.stat(fullPath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
return res.status(httpStatus.NOT_FOUND).json({
message: 'File not found'
});
}
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error accessing the file'
});
}
if (!stats.isFile()) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Path is not a file'
});
}
// Stream the file as binary data
res.writeHead(httpStatus.OK, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${path.basename(fullPath)}"`
});
const fileStream = fs.createReadStream(fullPath);
fileStream.pipe(res);
});
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error processing request'
});
}
});
async function addFilePathToJson(filePath) {
const jsonFilePath = path.join(__dirname, '..', 'filesReceived.json');
try {
let data = { receivedFiles: [] };
if (await fsExtra.pathExists(jsonFilePath)) {
await lockFile(jsonFilePath);
data = await fsExtra.readJson(jsonFilePath);
}else{
await lockFile(jsonFilePath);
}
data.receivedFiles.push(filePath);
await fsExtra.writeJson(jsonFilePath, data, { spaces: 2 });
await unlockFile(jsonFilePath);
console.log('File path added successfully.');
} catch (error) {
console.error('Error updating JSON file:', error);
throw error; // Rethrow the error for further handling if necessary
}
}
const shareFileSchema = Joi.object({
idUser: Joi.string().required(),
nameOfFile: Joi.string().required(),
sizeOfFile: Joi.number().required()
});
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const { error, value } = shareFileSchema.validate(req.body);
if (error) {
cb(error, undefined);
return;
}
const baseDir = path.join(__dirname, '..', 'uploads', value.idUser); // Temp storage location
fsExtra.ensureDirSync(baseDir);
cb(null, baseDir);
},
filename: function (req, file, cb) {
cb(null, req.body.nameOfFile); // Using directly assuming it has been validated already
}
});
const upload = multer({ storage: storage }).single('file');
app.post('/upload', (req, res) => {
upload(req, res, async (err) => {
if (err instanceof multer.MulterError) {
res.status(httpStatus.INTERNAL_SERVER_ERROR).send(`Multer error: ${err.message}`);
return;
} else if (err) {
res.status(httpStatus.BAD_REQUEST).send(`Validation error: ${err.message}`);
return;
}
try {
const { idUser, nameOfFile } = req.body;
const dirConfig = await fsExtra.readJson(path.join(__dirname, '..', 'dirShare.json'));
const baseDir = dirConfig.path;
const finalPath = path.join(baseDir, idUser, nameOfFile);
await fsExtra.move(req.file.path, finalPath, { overwrite: true });
await addFilePathToJson(finalPath);
res.status(httpStatus.OK).json({message: 'Upload successful.'})
} catch (error) {
console.error('Failed to move file:', error);
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({message: 'Server error while moving the file.'});
}
});
});
console.log('external_endpoints.json started.');
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
process.on('SIGINT', () => {
console.log('SIGINT signal received. Shutting down gracefully.');
server.close(() => {
console.log('Server closed.');
// Ensure all connections are closed
connections.forEach(conn => conn.end());
setTimeout(() => connections.forEach(conn => conn.destroy()), 5000);
process.exit(0);
});
});
+234
View File
@@ -0,0 +1,234 @@
const fsPromises = require('fs').promises;
const fs = require('fs');
const path = require('path');
const ip = require('ip');
const {encryptFileInPlace, decryptFileInPlace} = require('../src/main/aes_encrypt');
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
async function fetchBackupSchemes(serverIp) {
// Fetching backup schemes from the server
const depResponse = await fetch(`http://${serverIp}/backup_schemes`, {
method: 'GET',
headers: {'x-api-key': 'uc_api'}
});
const backupSchemesJson = await depResponse.json();
const backupSchemes = backupSchemesJson['data'];
// Specify the path where the backup schemes will be saved
const destPath = path.join(__dirname, '..', 'backupSchemes.json');
// Write the fetched backup schemes to the specified file
try {
await lockFile(destPath);
await fsPromises.writeFile(destPath, JSON.stringify(backupSchemes, null, 2)); // Use null, 2 for pretty formatting
await unlockFile(destPath);
console.log('Backup schemes saved successfully to', destPath);
} catch (error) {
console.error('Failed to save backup schemes:', error);
}
}
async function fetchUsersAndDepartments(serverIp) {
try {
console.log('se asteapta depart');
// Fetch departments
const depResponse = await fetch(`http://${serverIp}/users/departments`, {
method: 'GET',
headers: {'x-api-key': 'uc_api'}
});
const departmentsJson = await depResponse.json();
const departments = departmentsJson['data'];
console.log('se asteapta users')
// Fetch users
const userResponse = await fetch(`http://${serverIp}/users`, {
method: 'GET',
headers: {'x-api-key': 'uc_api'}
});
const usersJson = await userResponse.json();
const users = usersJson['data'];
// Combine the JSON data
const combinedData = Object.values(departments).reduce((acc, {name, key}) => {
acc[name] = {
key,
users: users.filter(user => user.department === name).map(user => user.id)
};
return acc;
}, {});
// Write combined data to a file
const filePath = path.join(__dirname, '..', 'usersInSystem.json');
if(!fs.existsSync(filePath)){
await fsPromises.writeFile(filePath, '');
}
await lockFile(filePath);
await fsPromises.writeFile(filePath, JSON.stringify(combinedData, null, 2), 'utf8');
await encryptFileInPlace(filePath);
await unlockFile(filePath);
console.log('Data has been encrypted and saved.');
} catch (error) {
console.error('Failed to fetch or process data:', error);
}
}
async function decryptAndGetServerIP(filePath) {
try {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fsPromises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
await encryptFileInPlace(filePath)
await unlockFile(filePath);
return serverIP;
} catch (error) {
console.error('An error occurred:', error);
return null;
}
}
async function getDirectoryStructure(dirPath) {
const baseName = path.basename(dirPath);
const entries = await fsPromises.readdir(dirPath, {withFileTypes: true});
const result = {};
result[baseName] = {files: []};
let totalSize = 0;
for (let entry of entries) {
const entryPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
// Recursively get structure for subdirectories
const {structure, size: subSize} = await getDirectoryStructure(entryPath);
result[baseName][entry.name] = structure[Object.keys(structure)[0]]; // Object.keys to fetch the first key name
totalSize += subSize;
} else {
// Add file name to the 'files' array and calculate total size
const stats = await fsPromises.stat(entryPath);
result[baseName].files.push(entry.name);
totalSize += stats.size;
}
}
return {structure: result, size: totalSize};
}
async function createBackupScheme(serverIp, structure, size) {
let filePath = path.join(__dirname, '..', 'loginData.json');
await lockFile(filePath);
await decryptFileInPlace(filePath);
const userContent = await fsPromises.readFile(filePath, 'utf8');
const userJson = JSON.parse(userContent);
await encryptFileInPlace(filePath)
await unlockFile(filePath);
// Find the IP address of the machine
const machineIP = ip.address();
// Prepare the data to be sent
const dataToSend = {
id: userJson.id,
ip: machineIP,
directoryStructure: JSON.stringify(structure),
totalSize: size
};
const response = await fetch(`http://${serverIp}/backup_schemes`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
},
body: JSON.stringify(dataToSend)
});
if (response.ok) {
console.log("Backup dir structure submitted.")
} else {
const data = await response.json()
console.log(data.message);
}
}
async function watchDirectoryChanges(serverIp) {
async function readBackupConfig(filePath) {
await lockFile(filePath);
const fileContent = await fsPromises.readFile(filePath, 'utf8');
await unlockFile(filePath);
return JSON.parse(fileContent);
}
async function updateBackupConfig(filePath, structure, size) {
const data = {
path: filePath,
structure: structure,
size: size
};
await lockFile(filePath);
await fsPromises.writeFile(path.join(__dirname, '..', 'dirBackup.json'), JSON.stringify(data, null, 2));
await unlockFile(filePath);
}
const configPath = path.join(__dirname, '..', 'dirBackup.json');
if(!fs.existsSync(configPath)){
console.log('backupDir file doesn\'t exists');
return;
}
const backupConfig = await readBackupConfig(configPath);
const storedStructure = backupConfig.structure;
const {structure: currentStructure, size: currentSize} = await getDirectoryStructure(backupConfig.path);
if (JSON.stringify(storedStructure) !== JSON.stringify(currentStructure)) {
console.log("Directory structure has changed. Updating backup...");
await createBackupScheme(serverIp, currentStructure, currentSize);
await updateBackupConfig(backupConfig.path, currentStructure, currentSize);
console.log('FetcherProcess: start backup.');
process.send({type: 'startBackup'});
} else {
console.log("No changes detected in the directory structure.");
}
}
let serverIp = null
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
const timeoutInterval = 6 * 60 * 1000 //minutes * seconds * miliseconds
setInterval(() => {
fetchUsersAndDepartments(serverIp);
}, timeoutInterval);
setInterval(() => {
watchDirectoryChanges(serverIp);
}, timeoutInterval);
setInterval(() => {
fetchBackupSchemes(serverIp);
}, timeoutInterval);
console.log("fetcher.js process started.");
process.on('SIGINT', async () => {
console.log('Shutdown signal received in \'fetcher.js\'. Cleaning up...');
try {
console.log('Performing cleanup tasks...');
console.log('Cleanup completed successfully.');
} catch (error) {
console.error('An error occurred during cleanup:', error);
} finally {
console.log('Process terminated');
process.exit(0);
}
});
+90
View File
@@ -0,0 +1,90 @@
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const FormData = require('form-data');
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
const {decryptFileInPlace, encryptFileInPlace} = require("../src/main/aes_encrypt");
async function decryptAndGetServerIP(filePath) {
try {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
await encryptFileInPlace(filePath)
await unlockFile(filePath);
return serverIP;
} catch (error) {
console.error('An error occurred:', error);
return null;
}
}
async function extractId() {
try {
// Path to the JSON file
const jsonFilePath = path.join(__dirname, '..', 'loginData.json');
// Read and parse the JSON file
const jsonData = await fs.promises.readFile(jsonFilePath, 'utf-8');
const { id } = JSON.parse(jsonData);
return id;
} catch (error) {
console.error('Failed to read file or parse data:', error);
throw error;
}
}
async function uploadFile(filePath, serverIp) {
try {
const idUser = await extractId(); // Fetch ID from JSON
const nameOfFile = path.basename(filePath); // Extract the file name from the path
// Ensure the file exists and get its size
if (!fs.existsSync(filePath)) {
console.error("File does not exist: " + filePath);
process.exit(1);
}
const fileSizeInBytes = fs.statSync(filePath).size;
const form = new FormData();
form.append('idUser', idUser);
form.append('nameOfFile', nameOfFile);
form.append('sizeOfFile', fileSizeInBytes);
form.append('file', fs.createReadStream(filePath));
const response = await axios.post(`http://${serverIp}/upload`, form, {
headers: {
...form.getHeaders(),
},
});
console.log('File uploaded successfully:', response.data);
process.exit(0); // Exit with status 0 (success)
} catch (error) {
console.error('Error uploading file:', error.message);
process.exit(1); // Exit with status 1 (error)
}
}
// Command-line argument for file path
if (process.argv.length < 3) {
console.log('Usage: node <script> <filePath>');
process.exit(1);
}
const filePath = process.argv[2]; // The third command-line argument is the file path
let serverIp = null
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
uploadFile(filePath, serverIp).catch(err => {
console.error(err);
process.exit(1); // Ensure to exit with status 1 in case of promise rejection
});
Binary file not shown.
+346 -13
View File
@@ -9,10 +9,17 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"axios": "^1.6.8",
"bootstrap": "^5.3.3",
"electron": "^29.1.5",
"express": "^4.19.2",
"form-data": "^4.0.0",
"fs-extra": "^11.2.0",
"ip": "^2.0.1",
"joi": "^17.12.3",
"multer": "^1.4.5-lts.1",
"nodemon": "^3.1.0",
"proper-lockfile": "^4.1.2",
"toastify-js": "^1.12.0"
},
"devDependencies": {
@@ -39,6 +46,48 @@
"global-agent": "^3.0.0"
}
},
"node_modules/@electron/get/node_modules/fs-extra": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
"integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
},
"engines": {
"node": ">=6 <7 || >=8"
}
},
"node_modules/@electron/get/node_modules/jsonfile": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/@electron/get/node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
"engines": {
"node": ">= 4.0.0"
}
},
"node_modules/@hapi/hoek": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz",
"integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ=="
},
"node_modules/@hapi/topo": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@hapi/topo/-/topo-5.1.0.tgz",
"integrity": "sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==",
"dependencies": {
"@hapi/hoek": "^9.0.0"
}
},
"node_modules/@popperjs/core": {
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
@@ -49,6 +98,24 @@
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@sideway/address": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/@sideway/address/-/address-4.1.5.tgz",
"integrity": "sha512-IqO/DUQHUkPeixNQ8n0JA6102hT9CmaljNTPmQ1u8MEhBo/R4Q8eKLN/vGZxuebwOroDB4cbpjheD4+/sKFK4Q==",
"dependencies": {
"@hapi/hoek": "^9.0.0"
}
},
"node_modules/@sideway/formula": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@sideway/formula/-/formula-3.0.1.tgz",
"integrity": "sha512-/poHZJJVjx3L+zVD6g9KgHfYnb443oi7wLu/XKojDviHy6HOEOA6z1Trk5aR1dGcmPenJEgb2sK2I80LeS3MIg=="
},
"node_modules/@sideway/pinpoint": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@sideway/pinpoint/-/pinpoint-2.0.0.tgz",
"integrity": "sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ=="
},
"node_modules/@sindresorhus/is": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",
@@ -164,11 +231,31 @@
"node": ">= 8"
}
},
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -273,6 +360,22 @@
"node": "*"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -410,11 +513,36 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="
},
"node_modules/concat-stream": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
"integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
"engines": [
"node >= 0.8"
],
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^2.2.2",
"typedarray": "^0.0.6"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
@@ -447,6 +575,11 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ=="
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
},
"node_modules/debug": {
"version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
@@ -529,6 +662,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -788,6 +929,38 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
},
"node_modules/follow-redirects": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -805,16 +978,16 @@
}
},
"node_modules/fs-extra": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
"integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz",
"integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=6 <7 || >=8"
"node": ">=14.14"
}
},
"node_modules/fsevents": {
@@ -1085,6 +1258,11 @@
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"node_modules/ip": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/ip/-/ip-2.0.1.tgz",
"integrity": "sha512-lJUL9imLTNi1ZfXT+DU6rBBdbiKGBuay9B6xGSPVjUeQwaH1RIGqef8RZkUtHioLmSNpPR5M4HVKJGm1j8FWVQ=="
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@@ -1131,6 +1309,23 @@
"node": ">=0.12.0"
}
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="
},
"node_modules/joi": {
"version": "17.12.3",
"resolved": "https://registry.npmjs.org/joi/-/joi-17.12.3.tgz",
"integrity": "sha512-2RRziagf555owrm9IRVtdKynOBeITiDpuZqIpgwqXShPncPKNiRQoiGsl/T8SQdq+8ugRzH2LqY67irr2y/d+g==",
"dependencies": {
"@hapi/hoek": "^9.3.0",
"@hapi/topo": "^5.1.0",
"@sideway/address": "^4.1.5",
"@sideway/formula": "^3.0.1",
"@sideway/pinpoint": "^2.0.0"
}
},
"node_modules/json-buffer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
@@ -1143,9 +1338,12 @@
"optional": true
},
"node_modules/jsonfile": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
@@ -1278,11 +1476,47 @@
"node": "*"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/multer": {
"version": "1.4.5-lts.1",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz",
"integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.0.0",
"concat-stream": "^1.5.2",
"mkdirp": "^0.5.4",
"object-assign": "^4.1.1",
"type-is": "^1.6.4",
"xtend": "^4.0.0"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@@ -1365,6 +1599,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": {
"version": "1.13.1",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz",
@@ -1447,6 +1689,11 @@
"node": ">=6"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
},
"node_modules/progress": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
@@ -1455,6 +1702,16 @@
"node": ">=0.4.0"
}
},
"node_modules/proper-lockfile": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
"integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
"dependencies": {
"graceful-fs": "^4.2.4",
"retry": "^0.12.0",
"signal-exit": "^3.0.2"
}
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -1467,6 +1724,11 @@
"node": ">= 0.10"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
},
"node_modules/pstree.remy": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
@@ -1528,6 +1790,25 @@
"node": ">= 0.8"
}
},
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/readable-stream/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -1570,6 +1851,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/retry": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
"integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
"engines": {
"node": ">= 4"
}
},
"node_modules/roarr": {
"version": "2.15.4",
"resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",
@@ -1742,6 +2031,11 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/signal-exit": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="
},
"node_modules/simple-update-notifier": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
@@ -1781,6 +2075,27 @@
"node": ">= 0.8"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/string_decoder/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/sumchecker": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
@@ -1862,6 +2177,11 @@
"node": ">= 0.6"
}
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="
},
"node_modules/undefsafe": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",
@@ -1873,11 +2193,11 @@
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="
},
"node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
"engines": {
"node": ">= 4.0.0"
"node": ">= 10.0.0"
}
},
"node_modules/unixify": {
@@ -1912,6 +2232,11 @@
"node": ">= 0.8"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -1948,6 +2273,14 @@
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"engines": {
"node": ">=0.4"
}
},
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+7
View File
@@ -11,10 +11,17 @@
"author": "Cerbu Andrei - Mihnea",
"license": "ISC",
"dependencies": {
"axios": "^1.6.8",
"bootstrap": "^5.3.3",
"electron": "^29.1.5",
"express": "^4.19.2",
"form-data": "^4.0.0",
"fs-extra": "^11.2.0",
"ip": "^2.0.1",
"joi": "^17.12.3",
"multer": "^1.4.5-lts.1",
"nodemon": "^3.1.0",
"proper-lockfile": "^4.1.2",
"toastify-js": "^1.12.0"
},
"devDependencies": {
BIN
View File
Binary file not shown.
+115
View File
@@ -0,0 +1,115 @@
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
async function readKeyFromFile(filePath) {
try {
await fs.promises.access(filePath, fs.constants.F_OK);
return fs.promises.readFile(filePath); // Use asynchronous readFile
} catch (error) {
console.error('Error reading key file:', error);
return null;
}
}
// Paths to the key files remain the same
const IV_FILE_PATH = path.join(__dirname, '..', '..', 'iv.key');
const SECRET_KEY_FILE_PATH = path.join(__dirname, '..', '..', 'secret.key');
async function encryptFileInPlace(filePath) {
// Await the resolution of these promises
const IV = await readKeyFromFile(IV_FILE_PATH);
const SECRET_KEY = await readKeyFromFile(SECRET_KEY_FILE_PATH);
if (!IV || !SECRET_KEY) {
throw new Error('Failed to load IV or Secret Key');
}
const tempEncryptedFilePath = filePath + '.enc'; // Temporary encrypted file
return new Promise((resolve, reject) => {
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(SECRET_KEY), IV);
const input = fs.createReadStream(filePath);
const output = fs.createWriteStream(tempEncryptedFilePath);
input.pipe(cipher).pipe(output);
output.on('finish', () => {
fs.rename(tempEncryptedFilePath, filePath, (err) => {
if (err) reject(err);
else resolve('File encrypted successfully and replaced original.');
});
});
output.on('error', reject);
});
}
async function decryptFileInPlace(filePath) {
// Await the resolution of these promises
const IV = await readKeyFromFile(IV_FILE_PATH);
const SECRET_KEY = await readKeyFromFile(SECRET_KEY_FILE_PATH);
if (!IV || !SECRET_KEY) {
throw new Error('Failed to load IV or Secret Key');
}
const tempDecryptedFilePath = filePath + '.dec'; // Temporary decrypted file
return new Promise((resolve, reject) => {
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(SECRET_KEY), IV);
const input = fs.createReadStream(filePath);
const output = fs.createWriteStream(tempDecryptedFilePath);
input.pipe(decipher).pipe(output);
output.on('finish', () => {
fs.rename(tempDecryptedFilePath, filePath, (err) => {
if (err) reject(err);
else resolve('File decrypted successfully and replaced original.');
});
});
output.on('error', reject);
});
}
function cryptForKey(content, key, decrypt = false) {
const algorithm = 'aes-256-ctr';
const secretKey = crypto.createHash('sha256').update(String(key)).digest('base64').substr(0, 32);
let cipher;
if (decrypt) {
cipher = crypto.createDecipheriv(algorithm, secretKey, Buffer.alloc(16, 0)); // Using a zeroed IV for CTR
} else {
cipher = crypto.createCipheriv(algorithm, secretKey, Buffer.alloc(16, 0));
}
return Buffer.concat([cipher.update(content), cipher.final()]);
}
// Encrypts a file in place with a given key
async function encryptFileWithKey(filePath, key) {
try {
const fileContent = await fs.promises.readFile(filePath);
const encryptedContent = cryptForKey(fileContent, key, false);
await fs.promises.writeFile(filePath, encryptedContent);
console.log(`File encrypted successfully: ${filePath}`);
} catch (error) {
console.error(`Error encrypting file: ${error.message}`);
}
}
async function decryptFileWithKey(filePath, key) {
try {
const fileContent = await fs.promises.readFile(filePath);
const decryptedContent = cryptForKey(fileContent, key, true);
await fs.promises.writeFile(filePath, decryptedContent);
console.log(`File decrypted successfully: ${filePath}`);
} catch (error) {
console.error(`Error decrypting file: ${error.message}`);
}
}
module.exports = {
encryptFileInPlace,
decryptFileInPlace,
encryptFileWithKey,
decryptFileWithKey,
}
+206 -32
View File
@@ -1,13 +1,60 @@
const { app, BrowserWindow, screen, ipcMain, dialog } = require('electron');
const {app, BrowserWindow, screen, ipcMain, dialog} = require('electron');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const {fork} = require('child_process');
const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt');
const {lockFile, unlockFile} = require("../../helpers/lock_mechanism");
//const {decryptUserFilesToDirectory} = require("../../jobs/backup");
const isMac = process.platform === 'darwin';
let html_page = undefined;
let mainWindow = undefined;
let alertWindow = undefined;
const createMainWindow = ((title, width, height) => {
let fetcherProcess = null;
let backupProcess = null;
let externalEndpointsProcess = null;
let sendFileProcess = null;
const create_initial_keys = () => {
const SECRET_KEY = crypto.randomBytes(32);
const IV = crypto.randomBytes(16);
const secretKeyPath = path.join(__dirname, '..', '..', 'secret.key');
const ivPath = path.join(__dirname, '..', '..', 'iv.key');
fs.writeFileSync(secretKeyPath, SECRET_KEY);
console.log(`Secret Key saved to ${secretKeyPath}`);
fs.writeFileSync(ivPath, IV);
console.log(`IV saved to ${ivPath}`);
}
const delete_external_files = () => {
const ipConfigPath = path.join(__dirname, '..', '..', 'ipConfig.json');
const loginDataPath = path.join(__dirname, '..', '..', 'loginData.json');
fs.unlink(ipConfigPath, (err) => {
if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted successfully: ' + 'ipConfig.json');
});
fs.unlink(loginDataPath, (err) => {
if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted successfully: ' + 'loginData.json');
});
}
const createMainWindow = (async (title, width, height) => {
mainWindow = new BrowserWindow({
title: title,
width: width,
@@ -19,9 +66,25 @@ const createMainWindow = ((title, width, height) => {
}
});
html_page = 'login.html';
try {
await fs.promises.access(path.join(__dirname, '..', '..', 'secret.key'), fs.constants.F_OK);
await fs.promises.access(path.join(__dirname, '..', '..', 'iv.key'), fs.constants.F_OK);
} catch (err) {
create_initial_keys();
delete_external_files();
}
html_page = 'ip_config.html';
try {
await fs.promises.access(path.join(__dirname, '..', '..', 'ipConfig.json'));
html_page = 'login.html';
} catch (err) {
html_page = 'ip_submit.html';
}
//mainWindow.setMenu(null);
mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', 'login.html'))
mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', html_page))
.then(() => {
console.log('Main window loaded!')
})
@@ -57,8 +120,8 @@ function showAlert(message) {
if (alertWindow === undefined) {
const title = 'Alert';
const mainScreen = screen.getPrimaryDisplay();
const { width, height } = mainScreen.size;
createAlertWindow(title, width/4, height/4);
const {width, height} = mainScreen.size;
createAlertWindow(title, width / 4, height / 4);
}
alertWindow.webContents.once('dom-ready', () => {
@@ -69,18 +132,34 @@ function showAlert(message) {
app.whenReady().then(() => {
const title = "Application";
const mainScreen = screen.getPrimaryDisplay();
const { width, height } = mainScreen.size;
const {width, height} = mainScreen.size;
createMainWindow(title, width / 1.5, height / 1.5);
app.on('activate', () => {
if(BrowserWindow.getAllWindows().length === 0){
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow(title, width, height);
}
});
});
app.on('before-quit', () => {
if (backupProcess !== null) {
backupProcess.kill();
}
if (externalEndpointsProcess !== null) {
externalEndpointsProcess.kill();
}
if (fetcherProcess !== null) {
fetcherProcess.kill();
}
if (sendFileProcess !== null) {
sendFileProcess.kill();
}
});
app.on('window-all-closed', () => {
if(!isMac){
if (!isMac) {
app.quit();
}
});
@@ -88,53 +167,52 @@ app.on('window-all-closed', () => {
ipcMain.handle('write-file', async (event, fileName, content) => {
try {
let filePath = path.join(__dirname, '..', '..', fileName);
await lockFile(filePath);
await fs.promises.writeFile(filePath, content);
await encryptFileInPlace(filePath);
await unlockFile(filePath)
console.log(`File successfully written to ${filePath}`);
return { success: true };
return {success: true};
} catch (error) {
console.error('Failed to write file:', error);
return { success: false, error: error.message };
return {success: false, error: error.message};
}
});
ipcMain.handle('delete-file', async (event, fileName) => {
try {
let filePath = path.join(__dirname, '..', '..', fileName);
console.log(filePath);
await fs.promises.unlink(filePath);
console.log(`File ${filePath} successfully deleted`);
return { success: true };
return {success: true};
} catch (error) {
console.error('Failed to delete file:', error);
return { success: false, error: error.message };
return {success: false, error: error.message};
}
});
ipcMain.handle('read-file', async (event, fileName) => {
try {
let filePath = path.join(__dirname, '..', '..', fileName);
await lockFile(filePath);
await decryptFileInPlace(filePath);
const content = await fs.promises.readFile(filePath, 'utf-8');
return { success: true, content };
await encryptFileInPlace(filePath);
await unlockFile(filePath);
return {success: true, content};
} catch (error) {
console.error('Error reading file:', error);
return { success: false, error: error.message };
return {success: false, error: error.message};
}
});
ipcMain.handle('change-content', async (event, nextPage) => {
try {
html_page = nextPage;
mainWindow.webContents.executeJavaScript(`
document.body.classList.add('fade-out');
`);
await new Promise(resolve => setTimeout(resolve, 1000));
await mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', nextPage));
mainWindow.webContents.executeJavaScript(`
document.body.classList.add('fade-in');
`);
return true;
} catch (error) {
console.error('Error changing content:', error);
@@ -142,7 +220,24 @@ ipcMain.handle('change-content', async (event, nextPage) => {
}
});
ipcMain.handle('open-backup-dir-dialog', async (event) => {
ipcMain.handle('open-dir-dialog', async (event) => {
try {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
});
if (result.canceled || result.filePaths.length === 0) {
return {canceled: true}
}
return result.filePaths[0];
} catch (error) {
console.error('Error opening file dialog:', error);
return null;
}
})
ipcMain.handle('open-json-dir-config', async (event, fileName) => {
try {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
@@ -154,16 +249,15 @@ ipcMain.handle('open-backup-dir-dialog', async (event) => {
const dirPath = result.filePaths[0];
await fs.promises.writeFile(
path.join(__dirname, '..', '..', 'dirBackup.json'),
path.join(__dirname, '..', '..', fileName),
JSON.stringify({
path: dirPath,
structure: {}
path: dirPath
}, null, 2));
return true;
} catch (error) {
console.error('Error opening file dialog:', error);
return { error: error.message };
return {error: error.message};
}
});
@@ -187,7 +281,7 @@ ipcMain.handle('check-file-exists', async (event, fileName) => {
}
});
ipcMain.handle('show-alert', async (event, message) =>{
ipcMain.handle('show-alert', async (event, message) => {
showAlert(message);
});
@@ -197,3 +291,83 @@ ipcMain.on('close-alert-window', () => {
alertWindow = undefined;
}
});
//External processes
ipcMain.handle('start-main-processes', async (event, args) => {
if (!backupProcess) {
backupProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'backup.js'), args, { silent: false });
backupProcess.on('exit', () => {
backupProcess = null;
});
backupProcess.on('error', (err) => {
console.log('Backup process error:', err);
});
}
if (!fetcherProcess) {
fetcherProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'fetcher.js'), args, { silent: false });
fetcherProcess.on('exit', () => {
fetcherProcess = null;
});
fetcherProcess.on('error', (err) => {
console.log('Fetcher process error:', err);
});
fetcherProcess.on('message', (message) => {
if (message.type === 'startBackup') {
backupProcess.send({
type: 'startBackup'
});
}
});
}
if (!externalEndpointsProcess) {
externalEndpointsProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'external_endpoints.js'), args, { silent: false });
externalEndpointsProcess.on('exit', () => {
externalEndpointsProcess = null;
});
externalEndpointsProcess.on('error', (err) => {
console.log('External endpoints process error:', err);
});
}
return true; // Indicate that the operation has started
});
ipcMain.handle('start-send-file-process', async (event, args) => {
if (sendFileProcess === null) {
sendFileProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'send_file.js'), args, {silent: false});
sendFileProcess.on('exit', () => {
sendFileProcess = null;
});
}
return true; // Indicate that the operation has started
});
ipcMain.handle('kill-before-logout', async(event) =>{
if (backupProcess !== null) {
backupProcess.kill('SIGINT');
}
if (externalEndpointsProcess !== null) {
externalEndpointsProcess.kill('SIGINT');
}
if (fetcherProcess !== null) {
fetcherProcess.kill('SIGINT');
}
if (sendFileProcess !== null) {
sendFileProcess.kill('SIGINT');
}
})
ipcMain.handle('decrypt-backup-files', async(event, destPath) => {
console.log('ai intrat in handle')
if(backupProcess != null){
console.log('esti in process');
backupProcess.send({
type: 'decryptBackup',
decryptDestPath: destPath
});
}
})
+8 -3
View File
@@ -1,4 +1,4 @@
const { contextBridge, ipcRenderer } = require('electron');
const {contextBridge, ipcRenderer} = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
writeFile: (fileName, content) => ipcRenderer.invoke('write-file', fileName, content),
@@ -7,7 +7,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
changeContent: (nextPage) => ipcRenderer.invoke('change-content', nextPage),
showAlert: (message) => ipcRenderer.invoke('show-alert', message),
closeAlertWindow: () => ipcRenderer.send('close-alert-window'),
openBackupDirDialog: () => ipcRenderer.invoke('open-backup-dir-dialog'),
openJsonDirConfigDialog: (fileName) => ipcRenderer.invoke('open-json-dir-config', fileName),
openDirDialog: () => ipcRenderer.invoke('open-dir-dialog'),
openFileDialog: () => ipcRenderer.invoke('open-file-dialog'),
checkFileExists: (fileName) => ipcRenderer.invoke('check-file-exists', fileName)
checkFileExists: (fileName) => ipcRenderer.invoke('check-file-exists', fileName),
startMainProcesses: async (args) => ipcRenderer.invoke('start-main-processes', args),
killBeforeLogout: async() => ipcRenderer.invoke('kill-before-logout'),
decryptFiles: async(destPath) => ipcRenderer.invoke('decrypt-backup-files', destPath)
});
@@ -15,47 +15,47 @@ body, html {
}
.container {
opacity: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
min-height: 100vh;
text-align: center;
}
.header{
color: #1B1A55;
font-size: 4vh;
text-transform: uppercase;
line-height: 2.5rem;
margin-bottom: 10rem;
}
.signup-form {
.ip-form {
background-color: #535C91;
opacity: 71;
padding: 13vh 3vh 5vh;
padding: 9vh 3vh 5vh;
border-radius: 1rem;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.9);
width: 25%;
}
.signup-form-title{
margin-bottom: 5vh;
.ip-form-title {
margin: 0 0 5vh 0;
text-align: center;
}
.signup-form-title h2 {
.ip-form-title h2 {
color: #FFFFFF;
font-size: 5vh;
margin: 0;
padding: 0;
text-align: center;
font-size: 5vh;
}
.signup-form hr{
.ip-form hr {
width: 40%;
}
.ip-form-content {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
input {
text-align: center;
color: white;
@@ -68,7 +68,22 @@ input {
border-radius: 10px;
}
.signup-form-footer{
button {
font-weight: bold;
width: 35%;
font-size: 1rem;
padding: 10px;
border: none;
border-radius: 5px;
margin-top: 1rem;
cursor: pointer;
}
button:hover {
filter: brightness(85%);
}
.ip-form-footer {
margin-top: 3vh;
display: flex;
flex-wrap: wrap;
@@ -77,26 +92,6 @@ input {
justify-content: space-evenly;
}
button {
font-weight: bold;
width: 35%;
font-size: 1rem;
padding: 10px;
border: none;
border-radius: 5px;
margin-top: 5px;
cursor: pointer;
}
button:hover{
filter: brightness(85%);
}
button[name="login"] {
background-color: #2196F3;
color: white;
}
button[name="submit"] {
background-color: #F44336;
color: white;
+3
View File
@@ -15,6 +15,7 @@ body, html {
}
.overlay {
display: none;
position: fixed;
width: 100%;
@@ -85,6 +86,8 @@ input {
}
.container {
opacity: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
@@ -15,6 +15,8 @@ body, html {
}
.container {
opacity: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
+2
View File
@@ -15,6 +15,8 @@ body, html {
}
.container {
opacity: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
+2
View File
@@ -15,6 +15,8 @@ body, html {
}
.container {
opacity: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
@@ -15,6 +15,8 @@ body, html {
}
.container {
opacity: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
+2
View File
@@ -15,6 +15,8 @@ body, html {
}
.container {
opacity: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
@@ -1,32 +0,0 @@
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-family: "Roboto", sans-serif;
font-weight: 500;
font-style: normal;
background-image: url('../assets/background.png');
background-size: cover;
background-repeat: no-repeat;
}
.container {
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
min-height: 100vh;
text-align: center; /* Center the text for all child elements */
}
.header{
color: #1B1A55;
font-size: 4vh;
text-transform: uppercase;
line-height: 2.5rem;
margin-bottom: 10rem;
}
-127
View File
@@ -1,127 +0,0 @@
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-family: "Roboto", sans-serif;
font-weight: 500;
font-style: normal;
background-image: url('../assets/background.png');
background-size: cover;
background-repeat: no-repeat;
}
.container {
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
min-height: 100vh;
text-align: center;
}
.header{
color: #1B1A55;
font-size: 4vh;
text-transform: uppercase;
line-height: 2.5rem;
margin-bottom: 10rem;
}
.signup-form {
background-color: #535C91;
opacity: 71;
padding: 8vh 3vh 5vh;
border-radius: 1rem;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.9);
width: 25%;
}
.signup-form-title{
margin-bottom: 5vh;
}
.signup-form-title h2 {
color: #FFFFFF;
margin: 0;
padding: 0;
text-align: center;
font-size: 5vh;
}
.signup-form hr{
width: 65%;
}
input{
margin: 0 0 1rem 0;
}
.signup-form-content{
display: flex;
margin: 1rem 2rem 2rem 3rem;
flex-direction: column;
align-items: start;
height: 20vh; /* Fixed height */
width: 80%; /* Full width */
overflow: auto; /* Enable scrolling */
font-size: 1.2rem;
color: white;
font-weight: bold;
}
.signup-form-content::-webkit-scrollbar {
width: 10px; /* Reduced width of the scrollbar by 2px */
}
.signup-form-content::-webkit-scrollbar-track {
background: #1B1A55; /* Updated track color */
}
.signup-form-content::-webkit-scrollbar-thumb {
background: #535C91; /* Updated handle color */
border: 2px solid #1B1A55; /* Adding a border to effectively reduce the thumb size */
}
.signup-form-content::-webkit-scrollbar-thumb:hover {
background: #555; /* Updated handle color on hover */
}
.signup-form-footer{
margin-top: 5vh;
display: flex;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-between;
align-items: center;
}
button {
font-weight: bold;
width: 30%;
font-size: 1rem;
padding: 10px;
border: none;
border-radius: 5px;
margin-top: 5px;
cursor: pointer;
}
button:hover{
filter: brightness(85%);
}
button[name="submit"] {
background-color: #F44336;
color: white;
}
button[name="back"] {
background-color: #23BDEE;
color: white;
}
@@ -9,13 +9,20 @@
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async function () {
const destPath = await window.electronAPI.openDirDialog();
await window.electronAPI.decryptFiles(destPath);
fadeOut('main_menu.html');
});
</script>
<title>Setup Completion</title>
<title>Sending file</title>
</head>
<body onload="fadeIn()">
<div class="container">
<div class="header">
<h1>SENDING THE FILE!</h1>
<h1>DECRYPTING BACKUP!</h1>
<h2>PlEASE WAIT</h2>
<img alt="Description of GIF" src="../assets/loading.gif">
+32
View File
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<link href="../assets/hard-disk.ico" rel="icon" type="image/x-icon">
<link href="../../../../CEO/src/renderer/css/ip_submit.css" rel="stylesheet">
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/ip_submit.js"></script>
<script src="../js/transition.js"></script>
<title>IP Submit</title>
</head>
<body onload="fadeIn()">
<div class="container">
<form class="ip-form" id="ipForm">
<div class="ip-form-title">
<h2>IP Config</h2>
<hr>
</div>
<div class="ip-form-content">
<input id="ipInput" name="ip" placeholder="192.168.x.x : Port" type="text">
</div>
<div class="ip-form-footer">
<button id="submit" name="submit" type="submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
+4 -2
View File
@@ -4,12 +4,15 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/login.js"></script>
<script src="../js/transition.js"></script>
<title>Login</title>
</head>
<body>
<body onload="fadeIn()">
<div class="container">
<div class="header">
<h1>DO WE KNOW</h1>
@@ -25,7 +28,6 @@
<input type="password" name="password" placeholder="Password">
</div>
<div class="login-form-footer">
<button id="signin" type="submit" name="signin">Sign in</button>
<button id="submit" type="submit" name="submit">Submit</button>
</div>
</form>
+11 -5
View File
@@ -4,15 +4,17 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/main_menu.css">
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/main_menu.js"></script>
<script src="../js/transition.js"></script>
<title>Main Page</title>
</head>
<body>
<body onload="fadeIn()">
<div class="container">
<div class="left_block">
<div class="left_block_top">
@@ -26,15 +28,19 @@
<div class="left_block_content">
<div class="left_block_buttons">
<button id="backup" name="menu_button">Set backup directory</button>
<button id="share_dir" name="menu_button">Set share directory</button>
</div>
<div class="left_block_buttons">
<button id="manage_department" name="menu_button">Manage work department</button>
</div>
<div class="left_block_buttons">
<button id="change_info" name="menu_button">Change your info</button>
<button id="share_file" name="menu_button">Share a file</button>
<button id="manage_users" name="menu_button">Manage users</button>
</div>
<div class="left_block_buttons">
<button id="share_file" name="menu_button">Share a file</button>
<button id="decrypt" name="menu_button">Decrypt files</button>
<button id="manage_users" name="menu_button">Manage users</button>
</div>
</div>
<div class="left_block_footer">
+5 -11
View File
@@ -9,12 +9,13 @@
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/manage_departments.js"></script>
<script src="../js/transition.js"></script>
<title>Manage Departments</title>
</head>
<body>
<body onload="fadeIn()">
<div class="container">
<form action="/signup" method="post" class="left_block">
<form class="left_block">
<div class="left_block_top">
<h1>CREATE NEW DEPARTMENT</h1>
<hr>
@@ -27,21 +28,14 @@
<button type="submit" name="create">Create</button>
</div>
</form>
<form action="/signup" method="post" class="right_block">
<form class="right_block">
<div class="security_level_form_title">
<h1>SECURITY</h1>
<h1>LEVELS</h1>
<hr>
</div>
<ul id="security_level_form_content">
<li draggable="true">Department 1</li>
<li draggable="true">Department 2</li>
<li draggable="true">Department 3</li>
<li draggable="true">Department 4</li>
<li draggable="true">Department 4</li>
<li draggable="true">Department 4</li>
<li draggable="true">Department 4</li>
<!-- Add more departments as needed -->
</ul>
<div>
+14 -21
View File
@@ -9,31 +9,24 @@
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/manage_users.js"></script>
<script src="../js/transition.js"></script>
<title>Manage Users</title>
</head>
<body>
<body onload="fadeIn()">
<div class="container">
<div class="signup-form">
<form action="/signup" method="post">
<div class="signup-form-title">
<h2>Users</h2>
<hr>
</div>
<div class="signup-form-content">
<label><input type="radio" name="dept" value="accounting">User1</label>
<label><input type="radio" name="dept" value="developer">User2</label>
<label><input type="radio" name="dept" value="designer">User3</label>
<label><input type="radio" name="dept" value="accounting">User1</label>
<label><input type="radio" name="dept" value="developer">User2</label>
<label><input type="radio" name="dept" value="designer">User3</label>
</div>
<div class="signup-form-footer">
<button type="button" name="back">Back</button>
<button type="submit" name="delete">Delete</button>
</div>
</form>
</div>
<form class="signup-form">
<div class="signup-form-title">
<h2>Users</h2>
<hr>
</div>
<div class="signup-form-content">
</div>
<div class="signup-form-footer">
<button type="button" name="back">Back</button>
<button type="submit" name="delete">Delete</button>
</div>
</form>
</div>
</body>
</html>
+2 -1
View File
@@ -9,10 +9,11 @@
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/profile.js"></script>
<script src="../js/transition.js"></script>
<title>Profile</title>
</head>
<body>
<body onload="fadeIn()">
<div class="container">
<form id="profileForm" class="profile-form">
<div class="profile-form-title">
@@ -2,17 +2,63 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<title>Setup Completion</title>
<link rel="stylesheet" href="../css/sending_file_confirmation.css">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<link href="../assets/hard-disk.ico" rel="icon" type="image/x-icon">
<link href="../css/sending_file_confirmation.css" rel="stylesheet">
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script>
<script>
import * as fs from "fs";
document.addEventListener("DOMContentLoaded", async function () {
async function performUploads() {
try {
const uploadData = JSON.parse(await window.electronAPI.readFile('usersDestTemp.json'));
const uploadPromises = uploadData.users.map(async (user) => {
const formData = new FormData();
formData.append('file', fs.readFileSync(uploadData.filePath));
formData.append('idUser', user.userId);
formData.append('nameOfFile', user.fileName);
const url = `http://${user.destIp}:${user.destPort}/upload`;
const uploadResponse = await fetch(url, {
method: 'POST',
body: formData
});
if (!uploadResponse.ok) {
throw new Error(`HTTP error during file upload to ${user.userId}: status ${uploadResponse.status}`);
}
return { userId: user.userId, success: true, message: `Upload successful for user ${user.userId}` };
});
const results = await Promise.all(uploadPromises);
results.forEach(result => {
console.log(result.message);
});
console.log('All files processed. Check the console for detailed results.');
} catch (error) {
console.error('An error occurred during uploads:', error);
}
}
await performUploads();
fadeOut('main_menu.html');
});
</script>
<title>Sending file</title>
</head>
<body>
<body onload="fadeIn()">
<div class="container">
<div class="header">
<h1>SENDING THE FILE!</h1>
<h2>PlEASE WAIT</h2>
<img src="../assets/loading.gif" alt="Description of GIF">
<img alt="Description of GIF" src="../assets/loading.gif">
</div>
</div>
+2 -1
View File
@@ -9,9 +9,10 @@
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/share_file.js"></script>
<script src="../js/transition.js"></script>
<title>Share File</title>
</head>
<body>
<body onload="fadeIn()">
<div class="container">
<div class="left_block">
<div class="left_block_top">
@@ -1,21 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/sign_up_confirmation.css">
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/sign_up_confirmation.js"></script>
<title>Setup Completion</title>
</head>
<body>
<div class="container">
<div class="header">
<h1>ALL THE SETUP IS DONE!</h1>
<h2>LETS PROCEED TO THE</h2>
<h2>LOGIN PAGE</h2>
</div>
</div>
</body>
</html>
@@ -1,37 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/sign_up_department.css">
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/sign_up_departments.js"></script>
<title>Department Selection</title>
</head>
<body>
<div class="container">
<div class="header">
<h1>TELL ME MORE</h1>
<h1>ABOUT</h1>
<h1>YOUR WORK</h1>
</div>
<form id="signupForm" class="signup-form">
<div class="signup-form-title">
<h2>Choose your department</h2>
<hr>
</div>
<div class="signup-form-content">
<!-- add the list query for departments-->
</div>
<div class="signup-form-footer">
<button id="back" type="button" name="back">Back</button>
<button id="submit" type="submit" name="submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
@@ -1,33 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/transition.css">
<link rel="stylesheet" href="../css/sing_up_profile.css">
<script src="../js/sign_up_profile.js"></script>
<title>Signup</title>
</head>
<body>
<div class="container">
<div class="header">
<h1>LET US MEET</h1>
<h1>EACH OTHER</h1>
</div>
<form id="signupForm" class="signup-form">
<div class="signup-form-title">
<h2>Sign Up</h2>
<hr>
</div>
<div>
<input type="email" name="email" placeholder="Email">
<input type="text" name="name" placeholder="Username">
<input type="password" name="password" placeholder="Password">
</div>
<div class="signup-form-footer">
<button id="login" type="button" name="login">Login</button>
<button id="continue" type="submit" name="submit">Continue</button>
</div>
</form>
</div>
+33
View File
@@ -0,0 +1,33 @@
document.addEventListener('DOMContentLoaded', async function () {
const submitButton = document.getElementById('submit');
const ipInput = document.getElementById('ipInput');
submitButton.addEventListener('click', async function (e) {
e.preventDefault();
try {
const ipAddress = ipInput.value.trim();
if (!ipAddress) {
throw new Error('Please enter an IP address.');
}
fetch(`http://${ipAddress}/heartbeat`)
.then(async response => {
if (!response.ok) {
throw new Error('Test failed. Check ip and server.');
}
await window.electronAPI.writeFile('ipConfig.json', JSON.stringify({ip: ipAddress}));
fadeOut('login.html');
})
.catch(error => {
console.error('Error:', error.message);
throw new Error(error.message);
});
} catch (error) {
console.error('Error:', error.message);
await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
}
});
});
+78 -76
View File
@@ -1,89 +1,91 @@
document.addEventListener('DOMContentLoaded', async function () {
const signinButton = document.getElementById('signin');
const submitButton = document.getElementById('submit');
await window.electronAPI.readFile('loginData.json')
.then(async result => {
const loginData = JSON.parse(result.content);
const { email, password } = loginData;
const signupDataExists = await window.electronAPI.checkFileExists('signupData.json');
if (signupDataExists) {
await window.electronAPI.deleteFile('signupData.json');
}
const response = await fetch('http://localhost:5000/users/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
},
body: JSON.stringify({
email: email,
password: password
})
let ip = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
const fileExists = await window.electronAPI.checkFileExists('loginData.json');
if (fileExists) {
await window.electronAPI.readFile('loginData.json')
.then(async result => {
const loginData = JSON.parse(result.content);
console.log(loginData);
const {email, password} = loginData;
await fetch(`http://${ip}/ceo/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
},
body: JSON.stringify({
email: email,
password: password
})
}).then(async response => {
if (response.ok) {
await window.electronAPI.killBeforeLogout();
await window.electronAPI.startMainProcesses();
fadeOut('main_menu.html');
} else {
await window.electronAPI.deleteFile('loginData.json');
}
}).catch(error => {
console.error(error);
});
})
.catch(async error => {
console.error('Can\'t read loginData');
await window.electronAPI.deleteFile('loginData.json');
});
if(response.ok) {
window.electronAPI.changeContent('main_menu.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
}
}).catch(async error => {
console.error('Can\'t read loginData');
await window.electronAPI.deleteFile('loginData.json')
});
signinButton.addEventListener('click', function (e) {
window.electronAPI.changeContent('sign_up_profile.html')
.then(() => console.log('Content changed successfully'))
.catch(error => console.error('Error changing content:', error));
});
}
submitButton.addEventListener('click', async function (e) {
try {
e.preventDefault();
console.log('Submit button clicked');
e.preventDefault();
console.log('Submit button clicked');
const form = document.getElementById('loginForm');
const formData = new FormData(form);
const form = document.getElementById('loginForm');
const formData = new FormData(form);
const email = formData.get('email');
const password = formData.get('password');
const email = formData.get('email');
const password = formData.get('password');
if (!email || !password) {
throw new Error('Both email and password are required.');
await fetch(`http://${ip}/ceo/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
},
body: JSON.stringify({
email: email,
password: password
})
}).then(async response => {
if (!response.ok) {
const data = await response.json();
throw new Error(data.message);
}
const response = await fetch('http://localhost:5000/users/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
},
body: JSON.stringify({
email: email,
password: password
})
});
switch (response.status) {
case 401:
throw new Error('Invalid credentials!');
case 500:
throw new Error('Internal server error. Try again later!');
}
const responseBody = await response.json();
const result = await window.electronAPI.writeFile('loginData.json', JSON.stringify(responseBody.message, null, 2));
if (!result.success) {
throw new Error('Error writing to file. Please try again later.');
}
window.electronAPI.changeContent('main_menu.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
} catch (error) {
await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
}
return response.json();
}).then(async data => {
console.log(data);
await window.electronAPI.writeFile('loginData.json', JSON.stringify(data.data, null, 2));
await window.electronAPI.startMainProcesses();
fadeOut('main_menu.html');
})
.catch(async error => {
await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
})
});
});
});
+73 -34
View File
@@ -1,5 +1,9 @@
document.addEventListener('DOMContentLoaded', async function () {
await insertUsername();
const backupButton = document.getElementById('backup');
const shareButton = document.getElementById('share_dir');
const manageDepartmentButton = document.getElementById('manage_department');
const manageUsersButton = document.getElementById('manage_users');
const changeInfoButton = document.getElementById('change_info');
@@ -7,66 +11,70 @@ document.addEventListener('DOMContentLoaded', async function () {
const decryptButton = document.getElementById('decrypt');
const logoutButton = document.getElementById('logout');
await insertUsername();
checkDirBackupFileExists()
.then(() => console.log('verificare facuta'));
.then(() => console.log('verificare backupDir facuta'));
manageUsersButton.addEventListener('click', async function(){
window.electronAPI.changeContent('manage_users.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
});
manageDepartmentButton.addEventListener('click', async function(){
window.electronAPI.changeContent('manage_departments.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
});
checkShareDirFileExists()
.then(() => console.log('verificare ShareDir facuta'));
backupButton.addEventListener('click', function () {
console.log('Set backup directory button clicked!');
window.electronAPI.openBackupDirDialog()
window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
.then(() => console.log('Back-up directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
});
shareButton.addEventListener('click', function () {
console.log('Set backup directory button clicked!');
window.electronAPI.openJsonDirConfigDialog('dirShare.json')
.then(() => console.log('Back-up directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
});
manageUsersButton.addEventListener('click', async function(){
fadeOut('manage_users.html');
});
changeInfoButton.addEventListener('click', function () {
console.log('Change your info button clicked!');
fadeOut('profile.html');
});
window.electronAPI.changeContent('profile.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
decryptButton.addEventListener('click', function () {
fadeOut('decrypting_backup.html');
});
changeInfoButton.addEventListener('click', function () {
console.log('Change your info button clicked!');
fadeOut('profile.html');
});
shareFileButton.addEventListener('click', function () {
console.log('Share a file button clicked!');
window.electronAPI.changeContent('share_file.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
fadeOut('share_file.html');
});
manageDepartmentButton.addEventListener('click', function() {
fadeOut('manage_departments.html');
})
logoutButton.addEventListener('click', async function () {
console.log('Logout button clicked!');
await window.electronAPI.killBeforeLogout();
await window.electronAPI.deleteFile('loginData.json');
window.electronAPI.changeContent('login.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
fadeOut('login.html');
});
decryptButton.addEventListener('click', async function (){
});
async function decryptFiles(){
}
async function checkDirBackupFileExists() {
try {
// Make an IPC call to check file existence
@@ -78,7 +86,7 @@ document.addEventListener('DOMContentLoaded', async function () {
button.id = 'backup_alert';
button.name = 'alert';
button.textContent = 'Set your backup directory!';
button.addEventListener('click', handleButtonClick);
button.addEventListener('click', handleBackupButtonPressed);
notificationsDiv.appendChild(button);
}
} catch (error) {
@@ -86,10 +94,28 @@ document.addEventListener('DOMContentLoaded', async function () {
}
}
async function handleButtonClick() {
async function checkShareDirFileExists() {
try {
const fileExists = await window.electronAPI.checkFileExists('dirShare.json');
if (!fileExists) {
const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button');
button.id = 'share_file_alert';
button.name = 'alert';
button.textContent = 'Set your share directory!';
button.addEventListener('click', handleShareButtonPressed);
notificationsDiv.appendChild(button);
}
} catch (error) {
console.error('Error checking file existence:', error);
}
}
async function handleBackupButtonPressed() {
console.log('Button clicked!');
await window.electronAPI.openBackupDirDialog()
await window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
.then(() => console.log('Back-up directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
@@ -99,6 +125,19 @@ document.addEventListener('DOMContentLoaded', async function () {
button.remove();
}
async function handleShareButtonPressed() {
console.log('Button clicked!');
await window.electronAPI.openJsonDirConfigDialog('dirShare.json')
.then(() => console.log('Share directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
const button = document.getElementById('backup_alert');
button.remove();
}
async function insertUsername() {
try {
const userData = await window.electronAPI.readFile('loginData.json');
+163 -57
View File
@@ -1,69 +1,175 @@
document.addEventListener('DOMContentLoaded', function() {
const list = document.getElementById('security_level_form_content');
let draggedItem = null;
document.addEventListener('DOMContentLoaded', async function () {
let ip = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
for (const item of list.querySelectorAll('li')) {
item.setAttribute('draggable', true);
const result = await window.electronAPI.readFile('loginData.json');
const loginData = JSON.parse(result.content);
const password = loginData.password;
item.addEventListener('dragstart', function(e) {
draggedItem = this;
setTimeout(() => this.classList.add('hide'), 0);
});
const backButton = document.querySelector('button[name="back"]');
const createButton = document.querySelector('button[name="create"]');
const submitButton = document.querySelector('button[name="submit"]');
item.addEventListener('dragend', function(e) {
setTimeout(() => this.classList.remove('hide'), 0);
});
backButton.addEventListener('click', function () {
fadeOut('main_menu.html');
console.log('Back button clicked');
});
item.addEventListener('dragover', function(e) {
e.preventDefault();
});
createButton.addEventListener('click', async function (e) {
e.preventDefault();
const departmentName = document.querySelector('input[name="text"]').value;
if (!departmentName) {
await window.electronAPI.showAlert('Department name is required.')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
return; // Exit if no name is provided
}
console.log(`Creating department: ${departmentName}`);
item.addEventListener('dragenter', function(e) {
e.preventDefault();
this.classList.add('over');
});
const url = `http://${ip}/ceo/departments`;
const headers = {
'Content-Type': 'application/json',
'x-api-key': 'uc_api',
'ceo_password': password
};
console.log(headers);
console.log(password);
const body = JSON.stringify({ name: departmentName });
item.addEventListener('dragleave', function(e) {
this.classList.remove('over');
});
try {
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: body
});
item.addEventListener('drop', function(e) {
e.preventDefault();
this.classList.remove('over');
if (this !== draggedItem) {
const items = Array.from(list.querySelectorAll('li'));
const draggedIndex = items.indexOf(draggedItem);
const droppedIndex = items.indexOf(this);
if (draggedIndex < droppedIndex) {
this.after(draggedItem);
} else {
this.before(draggedItem);
}
if (response.ok) {
const data = await response.json();
await window.electronAPI.showAlert(data.message);
document.querySelector('input[name="text"]').value = '';
fadeOut('manage_departments.html');
} else {
console.log("eroare");
const errorData = await response.json();
await window.electronAPI.showAlert(errorData.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
}
});
}
});
} catch (error) {
console.log("error");
await window.electronAPI.showAlert(error)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
}
});
function saveOrder() {
const listItems = document.querySelectorAll('#security_level_form_content li');
const order = Array.from(listItems).map(item => item.textContent.trim());
localStorage.setItem('listOrder', JSON.stringify(order));
}
submitButton.addEventListener('click', function () {
// Handle the "Submit" button functionality here
console.log('Submit button clicked');
saveOrder();
});
function loadOrder() {
const storedOrder = JSON.parse(localStorage.getItem('listOrder'));
if (storedOrder) {
document.addEventListener('DOMContentLoaded', function () {
const list = document.getElementById('security_level_form_content');
list.innerHTML = '';
storedOrder.forEach(itemText => {
const li = document.createElement('li');
li.textContent = itemText;
li.setAttribute('draggable', true);
list.appendChild(li);
});
}
}
let draggedItem = null;
// Call loadOrder to initialize the list with the saved order
loadOrder();
for (const item of list.querySelectorAll('li')) {
item.setAttribute('draggable', true);
item.addEventListener('dragstart', function (e) {
draggedItem = this;
setTimeout(() => this.classList.add('hide'), 0);
});
item.addEventListener('dragend', function (e) {
setTimeout(() => this.classList.remove('hide'), 0);
});
item.addEventListener('dragover', function (e) {
e.preventDefault();
});
item.addEventListener('dragenter', function (e) {
e.preventDefault();
this.classList.add('over');
});
item.addEventListener('dragleave', function (e) {
this.classList.remove('over');
});
item.addEventListener('drop', function (e) {
e.preventDefault();
this.classList.remove('over');
if (this !== draggedItem) {
const items = Array.from(list.querySelectorAll('li'));
const draggedIndex = items.indexOf(draggedItem);
const droppedIndex = items.indexOf(this);
if (draggedIndex < droppedIndex) {
this.after(draggedItem);
} else {
this.before(draggedItem);
}
}
});
}
});
function saveOrder() {
const listItems = document.querySelectorAll('#security_level_form_content li');
const order = Array.from(listItems).map(item => item.textContent.trim());
}
async function loadOrder() {
const url = `http://${ip}/users/departments`; // Replace {serverip} with the actual IP address of the server
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
}
});
if (response.ok) {
let departments = await response.json();
const list = document.getElementById('security_level_form_content');
list.innerHTML = ''; // Clear existing items
departments = departments.data;
// Check if there's a stored order in localStorage and reorder the departments array accordingly
const storedOrder = JSON.parse(localStorage.getItem('listOrder'));
if (storedOrder) {
storedOrder.forEach(itemKey => {
if (departments[itemKey]) {
appendDepartmentToList(departments[itemKey], list);
}
});
} else {
Object.keys(departments).forEach(key => {
appendDepartmentToList(departments[key], list);});
}
} else {
console.error('Failed to fetch departments:', response.status);
}
} catch (error) {
console.error('Error making the request:', error);
}
}
function appendDepartmentToList(department, list) {
const li = document.createElement('li');
li.textContent = department.name;
li.id = `department-${department.key}`; // Use a unique ID if possible, here it's prefixed with 'department-'
li.setAttribute('draggable', true);
list.appendChild(li);
}
await loadOrder();
});
+94
View File
@@ -0,0 +1,94 @@
document.addEventListener('DOMContentLoaded', async function() {
let ip = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
const result = await window.electronAPI.readFile('loginData.json');
const loginData = JSON.parse(result.content);
const password = loginData.password;
const ceoId = loginData.id;
const loadUsers = (async () => {
const url = `http://${ip}/users`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'x-api-key': 'uc_api'
}
});
if (response.ok) {
let users = await response.json();
users = users.data;
const formContent = document.querySelector('.signup-form-content');
formContent.innerHTML = '';
users.forEach(user => {
if(user.id !== ceoId) {
const label = document.createElement('label');
const radioInput = document.createElement('input');
radioInput.type = 'radio';
radioInput.name = 'dept';
radioInput.value = user.id; // Set user ID as value
label.appendChild(radioInput);
label.appendChild(document.createTextNode(user.name)); // User's name for display
formContent.appendChild(label);
}
});
} else {
console.error('Failed to fetch users:', response.status);
}
} catch (error) {
console.error('Error making the request:', error);
}
});
await loadUsers();
const deleteButton = document.querySelector('button[name="delete"]');
deleteButton.addEventListener('click', async function(event) {
event.preventDefault(); // Prevent the default form submission
const selectedUser = document.querySelector('input[type="radio"][name="dept"]:checked');
if (!selectedUser) {
await window.electronAPI.showAlert('Please select a user to delete.')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
return;
}
const userId = selectedUser.value;
const deleteUrl = `http://${ip}/ceo/users/${userId}`;
try {
const response = await fetch(deleteUrl, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api',
'ceo_password': password
}
});
const data = await response.json();
await window.electronAPI.showAlert(data.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
fadeOut('manage_users.html');
} catch (error) {
await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
}
});
const backButton = document.querySelector('button[name="back"]');
backButton.addEventListener('click', function() {
fadeOut('main_menu.html');
console.log('Back button clicked');
});
});
+42 -50
View File
@@ -1,65 +1,59 @@
document.addEventListener('DOMContentLoaded', async function () {
try {
const result = await window.electronAPI.readFile('loginData.json');
const loginData = JSON.parse(result.content);
// Set values for the inputs
const emailInput = document.querySelector('input[name="email"]');
const usernameInput = document.querySelector('input[name="username"]');
let ip = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
emailInput.value = loginData.email;
usernameInput.value = loginData.name;
const result = await window.electronAPI.readFile('loginData.json');
const loginData = JSON.parse(result.content);
} catch (error) {
console.error('Error reading login data:', error);
}
const emailInput = document.querySelector('input[name="email"]');
const usernameInput = document.querySelector('input[name="username"]');
emailInput.value = loginData.email;
usernameInput.value = loginData.name;
const password = loginData.password;
const backButton = document.querySelector('button[name="login"]');
const submitButton = document.querySelector('button[name="submit"]');
// Add event listeners for the back and submit buttons
backButton.addEventListener('click', function () {
console.log('Back button clicked!');
window.electronAPI.changeContent('main_menu.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
fadeOut('main_menu.html')
});
submitButton.addEventListener('click', async function (e) {
try {
e.preventDefault();
console.log('Submit button clicked!');
e.preventDefault();
console.log('Submit button clicked!');
const emailInput = document.querySelector('input[name="email"]');
const usernameInput = document.querySelector('input[name="username"]');
const emailInput = document.querySelector('input[name="email"]');
const usernameInput = document.querySelector('input[name="username"]');
const result = await window.electronAPI.readFile('loginData.json');
const loginData = JSON.parse(result.content);
const result = await window.electronAPI.readFile('loginData.json');
const loginData = JSON.parse(result.content);
const {id, department} = loginData;
const email = emailInput.value;
const name = usernameInput.value;
const {id, department} = loginData;
const email = emailInput.value;
const name = usernameInput.value;
const response = await fetch(`http://localhost:5000/users/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
},
body: JSON.stringify({
name: name,
email: email,
})
});
switch (response.status) {
case 400:
throw new Error('Email format invalid!')
case 409:
throw new Error('Email already in system!')
case 500:
throw new Error('Internal server error. Try again later!')
await fetch(`http://${ip}/ceo`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api',
'ceo_password': password
},
body: JSON.stringify({
name: name,
email: email,
})
}).then(async result => {
const data = await result.json();
if (!result.ok) {
throw new Error(data.message);
}
await window.electronAPI.writeFile('loginData.json', JSON.stringify({
@@ -70,13 +64,11 @@ document.addEventListener('DOMContentLoaded', async function () {
department: department
}));
window.electronAPI.changeContent('main_menu.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
}catch(error) {
fadeOut('main_menu.html');
}).catch(async error => {
await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
}
})
});
});
+48 -23
View File
@@ -1,5 +1,11 @@
document.addEventListener("DOMContentLoaded", function() {
document.addEventListener("DOMContentLoaded", async function () {
let pathToFile = '';
let serverIp = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
function updateFileName() {
const fileNameElement = document.getElementById('fileName');
@@ -10,7 +16,6 @@ document.addEventListener("DOMContentLoaded", function() {
}
}
// Call the function to update file name on DOMContentLoaded
updateFileName();
async function fetchUsersAndCreateCheckboxes() {
@@ -19,7 +24,7 @@ document.addEventListener("DOMContentLoaded", function() {
const {id} = loginData;
fetch('http://localhost:5000/users', {
fetch(`http://${serverIp}/users`, {
method: 'GET',
headers: {
'x-api-key': 'uc_api'
@@ -60,45 +65,65 @@ document.addEventListener("DOMContentLoaded", function() {
document.getElementById('backButton').addEventListener('click', async function () {
console.log('Back button clicked');
try {
await window.electronAPI.changeContent('main_menu.html');
console.log('Content changed successfully');
} catch (error) {
console.error('Error changing content:', error);
}
fadeOut('main_menu.html');
});
document.getElementById('submitButton').addEventListener('click', async function (event) {
event.preventDefault();
console.log('Submit button clicked');
if (pathToFile === '' || pathToFile.length === 0) {
const fileInput = document.getElementById('fileInput');
if (!fileInput.files.length) {
await window.electronAPI.showAlert('File not chosen!')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
return
.catch(error => console.error('Error showing alert:', error));
return;
}
const form = document.getElementById('userDestForm');
const checkboxes = form.querySelectorAll('input[name="users"]');
const selectedUserIds = [];
const selectedUserIds = Array.from(checkboxes)
.filter(checkbox => checkbox.checked)
.map(checkbox => checkbox.value);
checkboxes.forEach(checkbox => {
if (checkbox.checked) {
selectedUserIds.push(checkbox.value);
}
});
if(selectedUserIds === []){
if (!selectedUserIds.length) {
await window.electronAPI.showAlert('No user selected!')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
.catch(error => console.error('Error showing alert:', error));
return;
}
//TODO: logic to send files
const uploadData = {
filePath: fileInput.files[0].path,
users: []
};
for (const userId of selectedUserIds) {
try {
const ipResponse = await fetch(`http://${serverIp}/backup_schemes/${userId}`);
if (!ipResponse.ok) {
throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`);
}
const { data: destIp } = await ipResponse.json();
uploadData.users.push({
userId,
destIp,
destPort: 3000, // Static destination port
fileName: fileInput.files[0].name
});
} catch (error) {
console.error('Error fetching user data:', error);
}
}
window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData))
.then(() => {
console.log('File saved successfully');
fadeOut('sending_file_confirmation.html');
})
.catch(error => console.error('Failed to save file:', error));
});
fetchUsersAndCreateCheckboxes().then(() => console.log('Page rendered'))
});
@@ -1,7 +0,0 @@
document.addEventListener('DOMContentLoaded', async function() {
await new Promise(resolve => setTimeout(resolve, 2000));
window.electronAPI.changeContent('login.html')
.then(() => console.log('Content changed successfully'))
.catch(error => console.error('Error changing content:', error));
});
@@ -1,93 +0,0 @@
document.addEventListener('DOMContentLoaded', async function() {
try {
// Make API call to fetch department data
const response = await fetch('http://localhost:5000/departments', {
method: 'GET',
headers: {
'x-api-key': 'uc_api'
}
});
const res = await response.json();
const data = res['data'];
const formContent = document.querySelector('.signup-form-content');
data.forEach(department => {
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.id}">${department.name}`;
formContent.appendChild(label);
});
} catch (error) {
await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
}
document.getElementById('back').addEventListener('click', async function() {
try {
await window.electronAPI.changeContent('sign_up_profile.html');
console.log('Content changed successfully');
} catch (error) {
console.error('Error changing content:', error);
}
});
// Handler for the continue button
document.getElementById('submit').addEventListener('click', async function(e) {
e.preventDefault();
const selectedDept = document.querySelector('input[name="dept"]:checked').value;
try {
if (!selectedDept) {
throw new Error('No department had been selected!.');
}
let result = await window.electronAPI.readFile('signupData.json');
if (!result.success) {
throw new Error('Error reading the file. Please try again later.');
}
const data = JSON.parse(result.content);
const email = data.email;
const name = data.name;
const password = data.password;
result = await window.electronAPI.deleteFile('signupData.json');
if (!result.success) {
throw new Error('Error deleting the file. Please try again later.');
}
await fetch('http://localhost:5000/users/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
},
body: JSON.stringify({
name: name,
email: email,
password: password,
department: selectedDept,
})
}).then(async response => {
if(!response.ok){
await window.electronAPI.showAlert("Internal server error. Try again later!")
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
}
window.electronAPI.changeContent('sign_up_confirmation.html')
.then(() => console.log('Content changed successfully'))
.catch(error => console.error('Error changing content:', error));
}).catch(error => {
console.error(error);
});
} catch (error) {
await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
}
});
});
-81
View File
@@ -1,81 +0,0 @@
document.addEventListener('DOMContentLoaded', function () {
const cancelButton = document.getElementById('login');
const continueButton = document.getElementById('continue');
cancelButton.addEventListener('click', function () {
console.log(`'Login' button clicked!`);
window.electronAPI.changeContent('login.html')
.then(() => console.log('Content changed successfully'))
.catch(error => console.error('Error changing content:', error));
});
continueButton.addEventListener('click', async function (e) {
try {
e.preventDefault();
console.log('Continue button clicked');
const form = document.getElementById('signupForm');
const formData = new FormData(form);
const email = formData.get('email');
const name = formData.get('name');
const password = formData.get('password');
if (!email || !name || !password) {
throw new Error('All fields are required.');
}
if(password.length < 8){
throw new Error('Password must have minimum length 8!');
}
let statusFetch = 200;
await fetch('http://localhost:5000/users/validate_email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'uc_api'
},
body: JSON.stringify({
email: email
})
}).then(async response => {
const responseData = await response.json();
statusFetch = response.status;
console.error(responseData.message);
})
.catch(error => {
console.log(error);
})
switch(statusFetch){
case 500:
throw new Error('Internal server error! Try again later');
case 400:
throw new Error('Not a valid email!');
case 409:
throw new Error('Email already exists in system!');
}
const formDataJSON = {};
formData.forEach((value, key) => {
formDataJSON[key] = value;
});
const result = await window.electronAPI.writeFile('signupData.json', JSON.stringify(formDataJSON));
if (!result.success) {
throw new Error('Error writing to file. Please try again later.');
}
window.electronAPI.changeContent('sign_up_departments.html')
.then(() => console.log('Content changed successfully'))
.catch(error => console.error('Error changing content:', error));
}
catch (error) {
await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));;
}
});
});
+16
View File
@@ -0,0 +1,16 @@
function fadeIn() {
document.querySelector('.container').classList.remove('fade-out');
document.querySelector('.container').classList.add('fade-in');
}
function fadeOut(destination) {
const container = document.querySelector('.container');
container.classList.remove('fade-in');
container.classList.add('fade-out');
container.addEventListener('animationend', async () => {
await window.electronAPI.changeContent(destination)
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
});
}
Binary file not shown.
+1 -7
View File
@@ -1,7 +1 @@
{
"4659e71f-9bb4-4902-97d8-097efa138333": {
"ip": "192.168.0.195",
"directoryStructure": "{\"to_backup\":{\"files\":[\"fisier_random.txt\"],\"alte fis\":{\"files\":[\"alt fisier.txt\",\"fisier now.txt\",\"New Microsoft Excel Worksheet.xlsx\"]}}}",
"totalSize": 6197
}
}
{}
+3 -2
View File
@@ -1,6 +1,7 @@
{
"id": "335ae110091d3bc5fbc90d5e3786890e",
"id": "7c0ef9d5-23ed-47a6-bfb4-fdcfce436904",
"name": "CEO",
"email": "ceo@yourfirm.com",
"password": "335ae110091d3bc5fbc90d5e3786890e"
"password": "b85cfc54e8dda76e72d7bde7b10ce30a",
"department": "CEO"
}
+4 -4
View File
@@ -1,10 +1,10 @@
{
"1": {
"name": "HR",
"key": "65388e02b16e1cc530502492384ebd29ee6cda57840235d714d59dd460ae148a"
"name": "CEO",
"key": "6f444243063271cc1ea3ccb3621dfebc352fd40e2f58eb6c97b26b7e34fde7a1"
},
"2": {
"name": "Contabili",
"key": "572854d54c42f03ddcbb2beeae574dc4fcd33b251670d4983be49c4242c2d88a"
"name": "HR",
"key": "2c480e5e3fdaca10d4d838b1b16fb44ce0f57238cb4343a839e065f8d6e41dc7"
}
}
+2 -2
View File
@@ -1,9 +1,9 @@
[
{
"id": "4659e71f-9bb4-4902-97d8-097efa138333",
"id": "59c712d9-e6dd-438f-aec9-31ca2ae750e6",
"name": "Andrei Cerbu",
"email": "a@c.com",
"password": "5447045dc3cfaafdb49b365e31dad41eb88616b0b1449930e55fd3a70bd8cee4",
"department": "Contabili"
"department": "HR"
}
]
+13 -2
View File
@@ -26,15 +26,26 @@ router.get('/reset_server', validateBody, (req, res) => {
const ceoDB = req.app.get('ceoDB');
usersDB.writeFile([]);
departmentsDB.writeFile([]);
departmentsDB.writeFile({});
backupSchemesDB.writeFile({});
ceoDB.writeFile({
id: uuidv4(),
name: "CEO",
email: "ceo@yourfirm.com",
password: crypto.randomBytes(16).toString('hex')
password: crypto.randomBytes(16).toString('hex'),
department: "CEO"
});
const ceoDepartment = {
name: "CEO",
key: crypto.randomBytes(32).toString('hex')
}
const departmentsJson = departmentsDB.readFile();
departmentsJson[1] = ceoDepartment;
departmentsDB.writeFile(departmentsJson);
res.status(httpStatus.OK).json({ message: "Resetting the server..." });
});
+12
View File
@@ -44,6 +44,18 @@ router.get('/', validateBody, (req, res) => {
});
});
router.get('/:userId', (req, res) => {
const userId = req.params.userId;
const backupSchemesDB = req.app.get('backupSchemesDB');
let backupSchemesJson = backupSchemesDB.readFile();
const ip = backupSchemesJson[userId].ip;
if (ip) {
res.status(httpStatus.OK).json({message: "IP found", data: ip});
} else {
res.status(httpStatus.NOT_FOUND).send({message: "IP not found"});
}
});
router.use((req, res) => {
return res.status(httpStatus.NOT_FOUND).json({message: "Endpoint not found"});
})
+12 -7
View File
@@ -59,7 +59,7 @@ router.post('/login', validateBody, (req, res) => {
return res.status(httpStatus.UNAUTHORIZED).json({message: 'Invalid credentials.'});
}
return res.status(httpStatus.Ok).json({message: 'Logged in.'});
return res.status(httpStatus.OK).json({message: 'Logged in.', data: ceoDB.readFile()});
});
router.post('/set_security_levels', validateBody, (req, res) => {
@@ -99,13 +99,16 @@ router.delete('/users/:id', validateBody, (req, res) => {
const usersDB = req.app.get('usersDB');
const { id } = req.params;
const userIndex = usersDB.findIndexByKeyValueInArray('id', id);
if(userIndex === -1){
let usersJson = usersDB.readFile();
const userIndex = usersJson.findIndex(user => user.id === id);
if (userIndex === -1) {
return res.status(httpStatus.NOT_FOUND).json({message: 'User not found in system.'});
}
let usersJson = usersDB.readFile;
usersJson.splice(userIndex, 1);
usersDB.writeFile(usersJson);
return res.status(httpStatus.OK).json({ message: 'User deleted successfully.' });
@@ -114,6 +117,7 @@ router.delete('/users/:id', validateBody, (req, res) => {
router.post('/departments', validateBody, (req, res) => {
const departmentsDB = req.app.get('departmentsDB');
const { name } = req.body;
console.log(name);
let jsonDepartments = departmentsDB.readFile();
const nameExists = Object.values(jsonDepartments).some(department => department.name === name);
@@ -164,17 +168,18 @@ router.delete('/departments/:name', validateBody, (req, res) => {
router.put('/', validateBody, (req, res) => {
const ceoDB = req.app.get('ceoDB');
const { name, email } = req.body;
const {id} = ceoDB.readFile()
const {id, department} = ceoDB.readFile()
const newCeo = {
id: id,
name: name,
email: email,
password: crypto.randomBytes(16).toString('hex')
password: crypto.randomBytes(16).toString('hex'),
department: department
}
ceoDB.writeFile(newCeo);
return res.status(httpStatus.OK).json({message: 'Information modified.'});
return res.status(httpStatus.OK).json({message: 'Information modified.', data: newCeo});
});
router.get('/get_decrypt_keys', (req, res) => {
+1 -1
View File
@@ -2,6 +2,6 @@
"4659e71f-9bb4-4902-97d8-097efa138333": {
"ip": "192.168.0.195",
"directoryStructure": "{\"to_backup\":{\"files\":[\"fisier_random.txt\"],\"alte fis\":{\"files\":[\"alt fisier.txt\",\"fisier now.txt\",\"New Microsoft Excel Worksheet.xlsx\"]}}}",
"totalSize": 6197
"totalSize": 8482
}
}
+1 -1
View File
@@ -14,5 +14,5 @@
}
}
},
"size": 6197
"size": 8482
}
+3
View File
@@ -0,0 +1,3 @@
{
"path": "C:\\Users\\Andrei Cerbu\\Documents\\department_shared_files"
}
+3
View File
@@ -0,0 +1,3 @@
{
"path": "C:\\Users\\Andrei Cerbu\\Documents\\share_directory"
}
+172 -24
View File
@@ -1,8 +1,27 @@
const fs = require('fs').promises; // Ensure you use the promise-based API
const fsPromises = require('fs').promises; // Ensure you use the promise-based API
const fs = require('fs');
const path = require('path');
const { decryptFileInPlace, encryptFileInPlace, encryptFileWithKey, decryptFileWithKey} = require("../src/main/aes_encrypt");
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
async function decryptAndGetServerIP(filePath) {
try {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
await encryptFileInPlace(filePath)
await unlockFile(filePath);
return serverIP;
} catch (error) {
console.error('An error occurred:', error);
return null;
}
}
function extractFilePaths(directoryStructure) {
let paths = [];
const traverse = (dir, currentPath) => {
@@ -48,31 +67,32 @@ async function fetchFiles(ip, filePaths) {
async function removeDirectory(directoryPath) {
try {
// Check if the directory exists
const stats = await fs.stat(directoryPath);
const stats = await fsPromises.stat(directoryPath);
if (!stats.isDirectory()) {
console.log('The specified path is not a directory.');
return;
}
// Read all the contents of the directory
const files = await fs.readdir(directoryPath);
const files = await fsPromises.readdir(directoryPath);
// Loop through each file/directory and delete them
for (const file of files) {
const currentPath = path.join(directoryPath, file);
const currentStats = await fs.stat(currentPath);
const currentStats = await fsPromises.stat(currentPath);
if (currentStats.isDirectory()) {
// Recursive call for directories
await removeDirectory(currentPath);
} else {
// Delete file
await fs.unlink(currentPath);
await lockFile(currentPath);
await unlockFile(currentPath);
await fsPromises.unlink(currentPath);
}
}
// Finally, delete the directory itself
await fs.rmdir(directoryPath);
await fsPromises.rmdir(directoryPath);
//console.log(`Directory removed: ${directoryPath}`);
} catch (error) {
console.error(`Error removing directory: ${error.message}`);
@@ -87,23 +107,28 @@ async function decryptUserSystemConfig() {
async function encryptUserSystemConfig(){
const configPath = path.join(__dirname, '..', 'usersInSystem.json');
await unlockFile(configPath);
await encryptFileInPlace(configPath);
await unlockFile(configPath);
}
async function processBackup() {
await decryptUserSystemConfig();
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
const backupConfigPath = path.join(__dirname, '..', 'backupSchemes.json');
const baseBackupDirPath = path.join(__dirname, '..', 'backup_directories');
if(!fs.existsSync(backupConfigPath) || !fs.existsSync(usersConfigPath)){
console.log('Can\'t start backup system: necessary files missing!');
return;
}
await decryptUserSystemConfig();
try {
// Read and parse the users configuration
const usersData = await fs.readFile(usersConfigPath, 'utf8');
const usersData = await fsPromises.readFile(usersConfigPath, 'utf8');
const usersConfig = JSON.parse(usersData);
// Read and parse the backup configuration
const backupData = await fs.readFile(backupConfigPath, 'utf8');
const backupData = await fsPromises.readFile(backupConfigPath, 'utf8');
const jsonData = JSON.parse(backupData);
for (const key in jsonData) {
@@ -115,7 +140,7 @@ async function processBackup() {
const filePaths = extractFilePaths(directoryStructure);
const files = await fetchFiles(node.ip, filePaths);
await fs.mkdir(userBackupDir, { recursive: true });
await fsPromises.mkdir(userBackupDir, { recursive: true });
// Find the encryption key for the user's department
let encryptionKey = '';
@@ -129,8 +154,8 @@ async function processBackup() {
for (const file in files) {
if (files[file]) {
const fullPath = path.join(userBackupDir, file);
await fs.mkdir(path.dirname(fullPath), { recursive: true });
await fs.writeFile(fullPath, files[file]); // Write the binary data
await fsPromises.mkdir(path.dirname(fullPath), { recursive: true });
await fsPromises.writeFile(fullPath, files[file]); // Write the binary data
// Encrypt the file in place after writing it
if (encryptionKey) {
@@ -149,7 +174,7 @@ async function processBackup() {
async function getAllFilePaths(dirPath) {
let filePaths = [];
async function recurse(currentPath) {
const entries = await fs.readdir(currentPath, { withFileTypes: true });
const entries = await fsPromises.readdir(currentPath, { withFileTypes: true });
// Create promises for each entry and process them in parallel
const entryPromises = entries.map(async (entry) => {
const resolvedPath = path.join(currentPath, entry.name);
@@ -168,12 +193,19 @@ async function getAllFilePaths(dirPath) {
return filePaths;
}
async function decryptUserFilesToDirectory(destinationDir) {
await decryptUserSystemConfig(); // Ensure user config is decrypted
async function decryptBackupFilesToDirectory(destinationDir) {
await decryptUserSystemConfig();
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
const usersConfig = JSON.parse(await fs.readFile(usersConfigPath, 'utf8'));
if(!fs.existsSync(usersConfigPath)){
return false;
}
const usersConfig = JSON.parse(await fsPromises.readFile(usersConfigPath, 'utf8'));
const sourceDir = path.join(__dirname, '..', 'backup_directories');
await removeDirectory(destinationDir);
try {
for (const department in usersConfig) {
const { key, users } = usersConfig[department];
@@ -182,36 +214,152 @@ async function decryptUserFilesToDirectory(destinationDir) {
try {
const files = await getAllFilePaths(userDir);
for (const filePath of files) {
const stats = await fs.stat(filePath);
const stats = await fsPromises.stat(filePath);
if (stats.isFile()) {
// Extract the part of the file path after the userId
const relativePath = path.relative(userDir, filePath);
// Construct the destination file path
const destinationFilePath = path.join(destinationDir, userId, relativePath);
await fs.mkdir(path.dirname(destinationFilePath), { recursive: true });
await fsPromises.mkdir(path.dirname(destinationFilePath), { recursive: true });
await lockFile(filePath);
// Decrypt the file in its original location
await decryptFileWithKey(filePath, key);
// Copy the decrypted file to the destination directory
await fs.copyFile(filePath, destinationFilePath);
await fsPromises.copyFile(filePath, destinationFilePath);
console.log(`Decrypted file copied to: ${destinationFilePath}`);
// Re-encrypt the file in its original location (optional)
await encryptFileWithKey(filePath, key);
await unlockFile(filePath);
}
}
} catch (error) {
console.error(`Error processing files for user ${userId}: ${error.message}`);
await encryptUserSystemConfig();
return false;
}
}
}
} catch (error) {
console.error(`Error processing decryption: ${error.message}`);
await encryptUserSystemConfig();
return false;
}
await encryptUserSystemConfig();
return true;
}
async function decryptDepartmentFilesToDirectory() {
const dirDepartmentPath = path.join(__dirname, '..', 'dirDepartment.json');
const loginDataPath = path.join(__dirname, '..', 'loginData.json');
const usersConfigPath = path.join(__dirname, '..', 'usersInSystem.json');
const sourceDir = path.join(__dirname, '..', 'backup_directories');
processBackup();
decryptUserFilesToDirectory("C:\\Users\\Andrei Cerbu\\Documents\\decrypted");
if (!fs.existsSync(usersConfigPath) || !fs.existsSync(loginDataPath) || !fs.existsSync(dirDepartmentPath)) {
console.error("Missing one or more essential configuration files.");
return false;
}
await lockFile(loginDataPath);
await lockFile(usersConfigPath);
await decryptFileInPlace(loginDataPath);
await decryptFileInPlace(usersConfigPath);
const { path: destinationDir } = JSON.parse(await fsPromises.readFile(dirDepartmentPath, 'utf8'));
const { department } = JSON.parse(await fsPromises.readFile(loginDataPath, 'utf8'));
const usersConfig = JSON.parse(await fsPromises.readFile(usersConfigPath, 'utf8'));
// Check if department exists in users configuration
if (!usersConfig[department]) {
console.error(`No configuration found for department: ${department}`);
return false;
}
const { key, users } = usersConfig[department];
await encryptFileInPlace(loginDataPath);
await encryptFileInPlace(usersConfigPath);
await unlockFile(loginDataPath);
await unlockFile(usersConfigPath);
await removeDirectory(destinationDir);
for (const userId of users) {
const userDir = path.join(sourceDir, userId);
try {
const files = await getAllFilePaths(userDir);
console.log(`Processing files for user ${userId}: ${files}`);
for (const filePath of files) {
const stats = await fsPromises.stat(filePath);
if (stats.isFile()) {
const relativePath = path.relative(userDir, filePath);
// Construct the destination file path
const destinationFilePath = path.join(destinationDir, userId, relativePath);
await fsPromises.mkdir(path.dirname(destinationFilePath), { recursive: true });
// Decrypt the file in its original location
await decryptFileWithKey(filePath, key);
// Copy the decrypted file to the destination directory
await fsPromises.copyFile(filePath, destinationFilePath);
console.log(`Decrypted file copied to: ${destinationFilePath}`);
// Re-encrypt the file in its original location (optional)
await encryptFileWithKey(filePath, key);
}
}
} catch (error) {
console.error(`Error processing files for user ${userId}: ${error.message}`);
return false;
}
}
console.log("All files processed successfully.");
return true;
}
let serverIp = null;
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
const timeoutInterval = 7 * 60 * 1000 //minutes * seconds * miliseconds
setInterval(async () => {
await decryptDepartmentFilesToDirectory();
}, timeoutInterval);
console.log('backup.js process started!');
process.on('SIGINT', async () => {
console.log('Shutdown signal received in \'backup.js\'. Cleaning up...');
try {
console.log('Performing cleanup tasks...');
console.log('Cleanup completed successfully.');
} catch (error) {
console.error('An error occurred during cleanup:', error);
} finally {
console.log('Process terminated');
process.exit(0);
}
});
process.on('message', async (message) => {
if (message.type === 'startBackup') {
console.log('BackupProcess: Received command to start backup.');
await processBackup()
}
if(message.type === 'decryptBackup'){
console.log(`BackupProcess: Received command to decrypt backup to ${message.decryptDestPath}`);
console.log(message.decryptDestPath);
await decryptBackupFilesToDirectory(message.decryptDestPath);
}
});
-79
View File
@@ -1,79 +0,0 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const Joi = require('joi');
const fetch = require('node-fetch');
const { httpStatus } = require('../helpers/http_status');
const app = express();
app.use(express.json());
const filePathSchema = Joi.object({
filePath: Joi.string().required()
});
async function getBaseDirectory() {
const filePath = path.join(__dirname, '..', 'dirBackup.json');
try {
const data = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(data);
return jsonData.path;
} catch (error) {
console.error('Error reading the base directory:', error);
throw error;
}
}
app.post('/file_path', async (req, res) => {
const { error, value } = filePathSchema.validate(req.body);
if (error) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Invalid input',
data: error.details
});
}
try {
const basePath = await getBaseDirectory();
let { filePath } = value;
const baseDirName = path.basename(basePath);
if (filePath.startsWith(baseDirName + path.sep)) {
filePath = filePath.slice(baseDirName.length + 1);
}
const fullPath = path.resolve(basePath, filePath);
fs.stat(fullPath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
return res.status(httpStatus.NOT_FOUND).json({
message: 'File not found'
});
}
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error accessing the file'
});
}
if (!stats.isFile()) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Path is not a file'
});
}
// Stream the file as binary data
res.writeHead(httpStatus.OK, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${path.basename(fullPath)}"`
});
const fileStream = fs.createReadStream(fullPath);
fileStream.pipe(res);
});
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error processing request'
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
+187
View File
@@ -0,0 +1,187 @@
const express = require('express');
const fs = require('fs');
const multer = require('multer');
const fsExtra = require('fs-extra');
const path = require('path');
const Joi = require('joi');
const { httpStatus } = require('../helpers/http_status');
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
const app = express();
app.use(express.json());
app.use('/share_file', express.raw({ type: 'application/octet-stream', limit: 'Infinity' }));
const server = require('http').createServer(app);
const connections = [];
// Store active connections to close them on shutdown
server.on('connection', (conn) => {
connections.push(conn);
conn.on('close', () => {
connections.splice(connections.indexOf(conn), 1);
});
});
const filePathSchema = Joi.object({
filePath: Joi.string().required()
});
async function getBaseDirectory() {
const filePath = path.join(__dirname, '..', 'dirBackup.json');
try {
const data = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(data);
return jsonData.path;
} catch (error) {
console.error('Error reading the base directory:', error);
throw error;
}
}
app.post('/file_path', async (req, res) => {
const { error, value } = filePathSchema.validate(req.body);
if (error) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Invalid input',
data: error.details
});
}
try {
const basePath = await getBaseDirectory();
let { filePath } = value;
const baseDirName = path.basename(basePath);
if (filePath.startsWith(baseDirName + path.sep)) {
filePath = filePath.slice(baseDirName.length + 1);
}
const fullPath = path.resolve(basePath, filePath);
fs.stat(fullPath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
return res.status(httpStatus.NOT_FOUND).json({
message: 'File not found'
});
}
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error accessing the file'
});
}
if (!stats.isFile()) {
return res.status(httpStatus.BAD_REQUEST).json({
message: 'Path is not a file'
});
}
// Stream the file as binary data
res.writeHead(httpStatus.OK, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${path.basename(fullPath)}"`
});
const fileStream = fs.createReadStream(fullPath);
fileStream.pipe(res);
});
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
message: 'Error processing request'
});
}
});
async function addFilePathToJson(filePath) {
const jsonFilePath = path.join(__dirname, '..', 'filesReceived.json');
try {
let data = { receivedFiles: [] };
if (await fsExtra.pathExists(jsonFilePath)) {
await lockFile(jsonFilePath);
data = await fsExtra.readJson(jsonFilePath);
}else{
await lockFile(jsonFilePath);
}
data.receivedFiles.push(filePath);
await fsExtra.writeJson(jsonFilePath, data, { spaces: 2 });
await unlockFile(jsonFilePath);
console.log('File path added successfully.');
} catch (error) {
console.error('Error updating JSON file:', error);
throw error; // Rethrow the error for further handling if necessary
}
}
const shareFileSchema = Joi.object({
idUser: Joi.string().required(),
nameOfFile: Joi.string().required(),
sizeOfFile: Joi.number().required()
});
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const { error, value } = shareFileSchema.validate(req.body);
if (error) {
cb(error, undefined);
return;
}
const baseDir = path.join(__dirname, '..', 'uploads', value.idUser); // Temp storage location
fsExtra.ensureDirSync(baseDir);
cb(null, baseDir);
},
filename: function (req, file, cb) {
cb(null, req.body.nameOfFile); // Using directly assuming it has been validated already
}
});
const upload = multer({ storage: storage }).single('file');
app.post('/upload', (req, res) => {
upload(req, res, async (err) => {
if (err instanceof multer.MulterError) {
res.status(httpStatus.INTERNAL_SERVER_ERROR).send(`Multer error: ${err.message}`);
return;
} else if (err) {
res.status(httpStatus.BAD_REQUEST).send(`Validation error: ${err.message}`);
return;
}
try {
const { idUser, nameOfFile } = req.body;
const dirConfig = await fsExtra.readJson(path.join(__dirname, '..', 'dirShare.json'));
const baseDir = dirConfig.path;
const finalPath = path.join(baseDir, idUser, nameOfFile);
await fsExtra.move(req.file.path, finalPath, { overwrite: true });
await addFilePathToJson(finalPath);
res.status(httpStatus.OK).json({message: 'Upload successful.'})
} catch (error) {
console.error('Failed to move file:', error);
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({message: 'Server error while moving the file.'});
}
});
});
console.log('external_endpoints.json started.');
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
process.on('SIGINT', () => {
console.log('SIGINT signal received. Shutting down gracefully.');
server.close(() => {
console.log('Server closed.');
// Ensure all connections are closed
connections.forEach(conn => conn.end());
setTimeout(() => connections.forEach(conn => conn.destroy()), 5000);
process.exit(0);
});
});
+43 -18
View File
@@ -1,4 +1,5 @@
const fs = require('fs').promises;
const fsPromises = require('fs').promises;
const fs = require('fs');
const path = require('path');
const ip = require('ip');
const {encryptFileInPlace, decryptFileInPlace} = require('../src/main/aes_encrypt');
@@ -19,7 +20,7 @@ async function fetchBackupSchemes(serverIp) {
// Write the fetched backup schemes to the specified file
try {
await lockFile(destPath);
await fs.writeFile(destPath, JSON.stringify(backupSchemes, null, 2)); // Use null, 2 for pretty formatting
await fsPromises.writeFile(destPath, JSON.stringify(backupSchemes, null, 2)); // Use null, 2 for pretty formatting
await unlockFile(destPath);
console.log('Backup schemes saved successfully to', destPath);
} catch (error) {
@@ -29,14 +30,17 @@ async function fetchBackupSchemes(serverIp) {
async function fetchUsersAndDepartments(serverIp) {
try {
console.log('se asteapta depart');
// Fetch departments
const depResponse = await fetch(`http://${serverIp}/users/departments`, {
method: 'GET',
headers: {'x-api-key': 'uc_api'}
});
const departmentsJson = await depResponse.json();
const departments = departmentsJson['data'];
console.log('se asteapta users')
// Fetch users
const userResponse = await fetch(`http://${serverIp}/users`, {
method: 'GET',
@@ -56,8 +60,11 @@ async function fetchUsersAndDepartments(serverIp) {
// Write combined data to a file
const filePath = path.join(__dirname, '..', 'usersInSystem.json');
if(!fs.existsSync(filePath)){
await fsPromises.writeFile(filePath, '');
}
await lockFile(filePath);
await fs.writeFile(filePath, JSON.stringify(combinedData, null, 2), 'utf8');
await fsPromises.writeFile(filePath, JSON.stringify(combinedData, null, 2), 'utf8');
await encryptFileInPlace(filePath);
await unlockFile(filePath);
@@ -72,7 +79,7 @@ async function decryptAndGetServerIP(filePath) {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fs.readFile(filePath, 'utf8');
const fileContent = await fsPromises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
@@ -87,7 +94,7 @@ async function decryptAndGetServerIP(filePath) {
async function getDirectoryStructure(dirPath) {
const baseName = path.basename(dirPath);
const entries = await fs.readdir(dirPath, {withFileTypes: true});
const entries = await fsPromises.readdir(dirPath, {withFileTypes: true});
const result = {};
result[baseName] = {files: []};
let totalSize = 0;
@@ -101,7 +108,7 @@ async function getDirectoryStructure(dirPath) {
totalSize += subSize;
} else {
// Add file name to the 'files' array and calculate total size
const stats = await fs.stat(entryPath);
const stats = await fsPromises.stat(entryPath);
result[baseName].files.push(entry.name);
totalSize += stats.size;
}
@@ -114,7 +121,7 @@ async function createBackupScheme(serverIp, structure, size) {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const userContent = await fs.readFile(filePath, 'utf8');
const userContent = await fsPromises.readFile(filePath, 'utf8');
const userJson = JSON.parse(userContent);
await encryptFileInPlace(filePath)
@@ -151,7 +158,7 @@ async function createBackupScheme(serverIp, structure, size) {
async function watchDirectoryChanges(serverIp) {
async function readBackupConfig(filePath) {
await lockFile(filePath);
const fileContent = await fs.readFile(filePath, 'utf8');
const fileContent = await fsPromises.readFile(filePath, 'utf8');
await unlockFile(filePath);
return JSON.parse(fileContent);
}
@@ -163,11 +170,15 @@ async function watchDirectoryChanges(serverIp) {
size: size
};
await lockFile(filePath);
await fs.writeFile(path.join(__dirname, '..', 'dirBackup.json'), JSON.stringify(data, null, 2));
await fsPromises.writeFile(path.join(__dirname, '..', 'dirBackup.json'), JSON.stringify(data, null, 2));
await unlockFile(filePath);
}
const configPath = path.join(__dirname, '..', 'dirBackup.json');
if(!fs.existsSync(configPath)){
console.log('backupDir file doesn\'t exists');
return;
}
const backupConfig = await readBackupConfig(configPath);
const storedStructure = backupConfig.structure;
@@ -178,32 +189,46 @@ async function watchDirectoryChanges(serverIp) {
await createBackupScheme(serverIp, currentStructure, currentSize);
await updateBackupConfig(backupConfig.path, currentStructure, currentSize);
console.log('FetcherProcess: start backup.');
process.send({type: 'startBackup'});
} else {
console.log("No changes detected in the directory structure.");
}
}
process.on('SIGINT', () => {
console.log('Process terminated');
process.exit(0);
});
let serverIp = null
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
const timeoutInterval = 6 * 60 * 1000 //minutes * seconds * miliseconds
setInterval(() => {
fetchUsersAndDepartments(serverIp);
}, 5000);
}, timeoutInterval);
setInterval(() => {
watchDirectoryChanges(serverIp);
}, 5000);
}, timeoutInterval);
setInterval(() => {
fetchBackupSchemes(serverIp);
}, 5000);
}, timeoutInterval);
console.log("Service running. Press CTRL+C to stop.");
console.log("fetcher.js process started.");
process.on('SIGINT', async () => {
console.log('Shutdown signal received in \'fetcher.js\'. Cleaning up...');
try {
console.log('Performing cleanup tasks...');
console.log('Cleanup completed successfully.');
} catch (error) {
console.error('An error occurred during cleanup:', error);
} finally {
console.log('Process terminated');
process.exit(0);
}
});
+90
View File
@@ -0,0 +1,90 @@
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const FormData = require('form-data');
const {lockFile, unlockFile} = require("../helpers/lock_mechanism");
const {decryptFileInPlace, encryptFileInPlace} = require("../src/main/aes_encrypt");
async function decryptAndGetServerIP(filePath) {
try {
await lockFile(filePath);
await decryptFileInPlace(filePath);
const fileContent = await fs.promises.readFile(filePath, 'utf8');
const jsonData = JSON.parse(fileContent);
const serverIP = jsonData.ip;
await encryptFileInPlace(filePath)
await unlockFile(filePath);
return serverIP;
} catch (error) {
console.error('An error occurred:', error);
return null;
}
}
async function extractId() {
try {
// Path to the JSON file
const jsonFilePath = path.join(__dirname, '..', 'loginData.json');
// Read and parse the JSON file
const jsonData = await fs.promises.readFile(jsonFilePath, 'utf-8');
const { id } = JSON.parse(jsonData);
return id;
} catch (error) {
console.error('Failed to read file or parse data:', error);
throw error;
}
}
async function uploadFile(filePath, serverIp) {
try {
const idUser = await extractId(); // Fetch ID from JSON
const nameOfFile = path.basename(filePath); // Extract the file name from the path
// Ensure the file exists and get its size
if (!fs.existsSync(filePath)) {
console.error("File does not exist: " + filePath);
process.exit(1);
}
const fileSizeInBytes = fs.statSync(filePath).size;
const form = new FormData();
form.append('idUser', idUser);
form.append('nameOfFile', nameOfFile);
form.append('sizeOfFile', fileSizeInBytes);
form.append('file', fs.createReadStream(filePath));
const response = await axios.post(`http://${serverIp}/upload`, form, {
headers: {
...form.getHeaders(),
},
});
console.log('File uploaded successfully:', response.data);
process.exit(0); // Exit with status 0 (success)
} catch (error) {
console.error('Error uploading file:', error.message);
process.exit(1); // Exit with status 1 (error)
}
}
// Command-line argument for file path
if (process.argv.length < 3) {
console.log('Usage: node <script> <filePath>');
process.exit(1);
}
const filePath = process.argv[2]; // The third command-line argument is the file path
let serverIp = null
decryptAndGetServerIP(path.join(__dirname, '..', 'ipConfig.json')).then(ip => {
serverIp = ip;
});
uploadFile(filePath, serverIp).catch(err => {
console.error(err);
process.exit(1); // Ensure to exit with status 1 in case of promise rejection
});
+1 -2
View File
@@ -1,2 +1 @@
göáÏ.­ôÜïlÜ.r¡Ê4
bºÒ©Þs+L5]ì>Gß»FmtLƒa.ðÎ0*ð ÿ§(EíÊ-¬aÒA¯dÌKÖú ìIJ~À§1.OLÕ È]E´~9äÔ_fBsUlhÆG(|Nóè|Ô'ÏÃ]7%nì0 nê¥Õíke4ôBªÐdDþsZ
!ִ©׀.:¦ !r©}QXֿ¯@Ki*¨»עu[9Jצ/¥¨ׁdל-סC$n¥¼¦jW4"¡wו¾{ֱ^·\־טJֱײ פ˜ ־³RAךQTc4שE'I®עvעlַ7E־;ֱ9jה3ִ±אֻˆֲַ UU©1קל
+264 -13
View File
@@ -9,13 +9,17 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"axios": "^1.6.8",
"body-parser": "^1.20.2",
"bootstrap": "^5.3.3",
"cors": "^2.8.5",
"electron": "^29.1.5",
"express": "^4.19.2",
"form-data": "^4.0.0",
"fs-extra": "^11.2.0",
"ip": "^2.0.1",
"joi": "^17.12.3",
"multer": "^1.4.5-lts.1",
"node-fetch": "^3.3.2",
"nodemon": "^3.1.0",
"proper-lockfile": "^4.1.2",
@@ -45,6 +49,35 @@
"global-agent": "^3.0.0"
}
},
"node_modules/@electron/get/node_modules/fs-extra": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
"integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
},
"engines": {
"node": ">=6 <7 || >=8"
}
},
"node_modules/@electron/get/node_modules/jsonfile": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/@electron/get/node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
"engines": {
"node": ">= 4.0.0"
}
},
"node_modules/@hapi/hoek": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz",
@@ -201,11 +234,31 @@
"node": ">= 8"
}
},
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -310,6 +363,22 @@
"node": "*"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -447,11 +516,36 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="
},
"node_modules/concat-stream": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
"integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
"engines": [
"node >= 0.8"
],
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^2.2.2",
"typedarray": "^0.0.6"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
@@ -484,6 +578,11 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ=="
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
},
"node_modules/cors": {
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
@@ -586,6 +685,14 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -867,6 +974,38 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
},
"node_modules/follow-redirects": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
@@ -895,16 +1034,16 @@
}
},
"node_modules/fs-extra": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
"integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz",
"integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=6 <7 || >=8"
"node": ">=14.14"
}
},
"node_modules/fsevents": {
@@ -1226,6 +1365,11 @@
"node": ">=0.12.0"
}
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="
},
"node_modules/joi": {
"version": "17.12.3",
"resolved": "https://registry.npmjs.org/joi/-/joi-17.12.3.tgz",
@@ -1250,9 +1394,12 @@
"optional": true
},
"node_modules/jsonfile": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
@@ -1385,11 +1532,47 @@
"node": "*"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/multer": {
"version": "1.4.5-lts.1",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz",
"integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.0.0",
"concat-stream": "^1.5.2",
"mkdirp": "^0.5.4",
"object-assign": "^4.1.1",
"type-is": "^1.6.4",
"xtend": "^4.0.0"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@@ -1597,6 +1780,11 @@
"node": ">=6"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
},
"node_modules/progress": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
@@ -1627,6 +1815,11 @@
"node": ">= 0.10"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
},
"node_modules/pstree.remy": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
@@ -1688,6 +1881,25 @@
"node": ">= 0.8"
}
},
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/readable-stream/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -1954,6 +2166,27 @@
"node": ">= 0.8"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/string_decoder/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/sumchecker": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
@@ -2035,6 +2268,11 @@
"node": ">= 0.6"
}
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="
},
"node_modules/undefsafe": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",
@@ -2046,11 +2284,11 @@
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="
},
"node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
"engines": {
"node": ">= 4.0.0"
"node": ">= 10.0.0"
}
},
"node_modules/unixify": {
@@ -2085,6 +2323,11 @@
"node": ">= 0.8"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@@ -2129,6 +2372,14 @@
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"engines": {
"node": ">=0.4"
}
},
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+4
View File
@@ -11,13 +11,17 @@
"author": "Cerbu Andrei - Mihnea",
"license": "ISC",
"dependencies": {
"axios": "^1.6.8",
"body-parser": "^1.20.2",
"bootstrap": "^5.3.3",
"cors": "^2.8.5",
"electron": "^29.1.5",
"express": "^4.19.2",
"form-data": "^4.0.0",
"fs-extra": "^11.2.0",
"ip": "^2.0.1",
"joi": "^17.12.3",
"multer": "^1.4.5-lts.1",
"node-fetch": "^3.3.2",
"nodemon": "^3.1.0",
"proper-lockfile": "^4.1.2",
+102 -12
View File
@@ -6,15 +6,17 @@ const {fork} = require('child_process');
const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt');
const {lockFile, unlockFile} = require("../../helpers/lock_mechanism");
//const {decryptUserFilesToDirectory} = require("../../jobs/backup");
const isMac = process.platform === 'darwin';
let html_page = undefined;
let mainWindow = undefined;
let alertWindow = undefined;
let backupProcess = null;
let receiverProcess = null;
let fetcherProcess = null;
let backupProcess = null;
let externalEndpointsProcess = null;
let sendFileProcess = null;
const create_initial_keys = () => {
const SECRET_KEY = crypto.randomBytes(32);
@@ -144,12 +146,16 @@ app.on('before-quit', () => {
if (backupProcess !== null) {
backupProcess.kill();
}
if (receiverProcess !== null) {
receiverProcess.kill();
if (externalEndpointsProcess !== null) {
externalEndpointsProcess.kill();
}
if (fetcherProcess !== null) {
fetcherProcess.kill();
}
if (sendFileProcess !== null) {
sendFileProcess.kill();
}
});
app.on('window-all-closed', () => {
@@ -214,7 +220,24 @@ ipcMain.handle('change-content', async (event, nextPage) => {
}
});
ipcMain.handle('open-backup-dir-dialog', async (event) => {
ipcMain.handle('open-dir-dialog', async (event) => {
try {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
});
if (result.canceled || result.filePaths.length === 0) {
return {canceled: true}
}
return result.filePaths[0];
} catch (error) {
console.error('Error opening file dialog:', error);
return null;
}
})
ipcMain.handle('open-json-dir-config', async (event, fileName) => {
try {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
@@ -226,10 +249,9 @@ ipcMain.handle('open-backup-dir-dialog', async (event) => {
const dirPath = result.filePaths[0];
await fs.promises.writeFile(
path.join(__dirname, '..', '..', 'dirBackup.json'),
path.join(__dirname, '..', '..', fileName),
JSON.stringify({
path: dirPath,
structure: {}
path: dirPath
}, null, 2));
return true;
@@ -271,13 +293,81 @@ ipcMain.on('close-alert-window', () => {
});
//External processes
ipcMain.handle('start-fetcher', async (event, args) => {
if (fetcherProcess === null) {
fetcherProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'fetcher.js'), args, {silent: false});
ipcMain.handle('start-main-processes', async (event, args) => {
if (!backupProcess) {
backupProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'backup.js'), args, { silent: false });
backupProcess.on('exit', () => {
backupProcess = null;
});
backupProcess.on('error', (err) => {
console.log('Backup process error:', err);
});
}
if (!fetcherProcess) {
fetcherProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'fetcher.js'), args, { silent: false });
fetcherProcess.on('exit', () => {
fetcherProcess = null;
// Optionally, notify the renderer process that the fetcher has finished
});
fetcherProcess.on('error', (err) => {
console.log('Fetcher process error:', err);
});
fetcherProcess.on('message', (message) => {
if (message.type === 'startBackup') {
backupProcess.send({
type: 'startBackup'
});
}
});
}
if (!externalEndpointsProcess) {
externalEndpointsProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'external_endpoints.js'), args, { silent: false });
externalEndpointsProcess.on('exit', () => {
externalEndpointsProcess = null;
});
externalEndpointsProcess.on('error', (err) => {
console.log('External endpoints process error:', err);
});
}
return true; // Indicate that the operation has started
});
ipcMain.handle('start-send-file-process', async (event, args) => {
if (sendFileProcess === null) {
sendFileProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'send_file.js'), args, {silent: false});
sendFileProcess.on('exit', () => {
sendFileProcess = null;
});
}
return true; // Indicate that the operation has started
});
ipcMain.handle('kill-before-logout', async(event) =>{
if (backupProcess !== null) {
backupProcess.kill('SIGINT');
}
if (externalEndpointsProcess !== null) {
externalEndpointsProcess.kill('SIGINT');
}
if (fetcherProcess !== null) {
fetcherProcess.kill('SIGINT');
}
if (sendFileProcess !== null) {
sendFileProcess.kill('SIGINT');
}
})
ipcMain.handle('decrypt-backup-files', async(event, destPath) => {
console.log('ai intrat in handle')
if(backupProcess != null){
console.log('esti in process');
backupProcess.send({
type: 'decryptBackup',
decryptDestPath: destPath
});
}
})
+5 -6
View File
@@ -7,13 +7,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
changeContent: (nextPage) => ipcRenderer.invoke('change-content', nextPage),
showAlert: (message) => ipcRenderer.invoke('show-alert', message),
closeAlertWindow: () => ipcRenderer.send('close-alert-window'),
openBackupDirDialog: () => ipcRenderer.invoke('open-backup-dir-dialog'),
openJsonDirConfigDialog: (fileName) => ipcRenderer.invoke('open-json-dir-config', fileName),
openDirDialog: () => ipcRenderer.invoke('open-dir-dialog'),
openFileDialog: () => ipcRenderer.invoke('open-file-dialog'),
checkFileExists: (fileName) => ipcRenderer.invoke('check-file-exists', fileName),
startFetcher: async (args) => ipcRenderer.invoke('start-fetcher', args),
startBackup: async (args) => ipcRenderer.invoke('start-backup', args),
startDecryptFiles: async (args) => ipcRenderer.invoke('start-decrypt-files', args),
startSendFiles: async (args) => ipcRenderer.invoke('start-send_files', args),
startReceiver: async (args) => ipcRenderer.invoke('start-receiver', args)
startMainProcesses: async (args) => ipcRenderer.invoke('start-main-processes', args),
killBeforeLogout: async() => ipcRenderer.invoke('kill-before-logout'),
decryptFiles: async(destPath) => ipcRenderer.invoke('decrypt-backup-files', destPath)
});
@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<link href="../assets/hard-disk.ico" rel="icon" type="image/x-icon">
<link href="../css/sending_file_confirmation.css" rel="stylesheet">
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async function () {
const destPath = await window.electronAPI.openDirDialog();
await window.electronAPI.decryptFiles(destPath);
fadeOut('main_menu.html');
});
</script>
<title>Sending file</title>
</head>
<body onload="fadeIn()">
<div class="container">
<div class="header">
<h1>DECRYPTING BACKUP!</h1>
<h2>PlEASE WAIT</h2>
<img alt="Description of GIF" src="../assets/loading.gif">
</div>
</div>
</body>
</html>
+1 -1
View File
@@ -5,7 +5,7 @@
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<link href="../assets/hard-disk.ico" rel="icon" type="image/x-icon">
<link href="../css/ip_submit.css" rel="stylesheet">
<link href="../../../../CEO/src/renderer/css/ip_submit.css" rel="stylesheet">
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/ip_submit.js"></script>
+3 -2
View File
@@ -38,13 +38,14 @@
<div class="left_block_content">
<div class="left_block_buttons">
<button id="backup" name="menu_button">Set backup directory</button>
<button id="change_department" name="menu_button">Change work department</button>
<button id="share_dir" name="menu_button">Set share directory</button>
</div>
<div class="left_block_buttons">
<button id="change_info" name="menu_button">Change your info</button>
<button id="share_file" name="menu_button">Share a file</button>
<button id="change_department" name="menu_button">Change work department</button>
</div>
<div class="left_block_buttons">
<button id="share_file" name="menu_button">Share a file</button>
<button id="decrypt" name="menu_button">Decrypt files</button>
</div>
</div>
@@ -9,8 +9,49 @@
<link href="../css/transition.css" rel="stylesheet">
<script src="../js/transition.js"></script>
<script>
import * as fs from "fs";
<title>Setup Completion</title>
document.addEventListener("DOMContentLoaded", async function () {
async function performUploads() {
try {
const uploadData = JSON.parse(await window.electronAPI.readFile('usersDestTemp.json'));
const uploadPromises = uploadData.users.map(async (user) => {
const formData = new FormData();
formData.append('file', fs.readFileSync(uploadData.filePath));
formData.append('idUser', user.userId);
formData.append('nameOfFile', user.fileName);
const url = `http://${user.destIp}:${user.destPort}/upload`;
const uploadResponse = await fetch(url, {
method: 'POST',
body: formData
});
if (!uploadResponse.ok) {
throw new Error(`HTTP error during file upload to ${user.userId}: status ${uploadResponse.status}`);
}
return { userId: user.userId, success: true, message: `Upload successful for user ${user.userId}` };
});
const results = await Promise.all(uploadPromises);
results.forEach(result => {
console.log(result.message);
});
console.log('All files processed. Check the console for detailed results.');
} catch (error) {
console.error('An error occurred during uploads:', error);
}
}
await performUploads();
fadeOut('main_menu.html');
});
</script>
<title>Sending file</title>
</head>
<body onload="fadeIn()">
<div class="container">
+5 -3
View File
@@ -17,9 +17,11 @@ document.addEventListener('DOMContentLoaded', async function () {
const formContent = document.querySelector('.department-form-content');
Object.entries(data).forEach(([key, department]) => {
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label);
if(department.name !== 'CEO'){
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label);
}
});
}).catch(async error => {
await window.electronAPI.showAlert(error.message)
+3 -4
View File
@@ -34,6 +34,8 @@ document.addEventListener('DOMContentLoaded', async function () {
})
}).then(async response => {
if (response.ok) {
await window.electronAPI.killBeforeLogout();
await window.electronAPI.startMainProcesses();
fadeOut('main_menu.html');
} else {
await window.electronAPI.deleteFile('loginData.json');
@@ -84,6 +86,7 @@ document.addEventListener('DOMContentLoaded', async function () {
}).then(async data => {
data.data.password = password
await window.electronAPI.writeFile('loginData.json', JSON.stringify(data.data, null, 2));
await window.electronAPI.startMainProcesses();
fadeOut('main_menu.html');
})
.catch(async error => {
@@ -92,8 +95,4 @@ document.addEventListener('DOMContentLoaded', async function () {
.catch(error => console.error('Error showing alert:', error));
})
});
function delayWithTimeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
});
+96 -17
View File
@@ -1,5 +1,8 @@
document.addEventListener('DOMContentLoaded', async function () {
await insertUsername();
const backupButton = document.getElementById('backup');
const shareButton = document.getElementById('share_dir');
const changeDepartmentButton = document.getElementById('change_department');
const changeInfoButton = document.getElementById('change_info');
const shareFileButton = document.getElementById('share_file');
@@ -19,21 +22,12 @@ document.addEventListener('DOMContentLoaded', async function () {
let triggerSource = '';
function handleOverlayOpen(buttonId) {
overlay.style.display = 'block';
triggerSource = buttonId; // Remember the button that triggered the overlay
console.log(`${buttonId} button clicked!`);
}
changeDepartmentButton.addEventListener('click', function () {
handleOverlayOpen('change_department');
});
decryptButton.addEventListener('click', function () {
handleOverlayOpen('decrypt');
});
ceoBackButton.addEventListener('click', function () {
overlay.style.display = 'none';
});
@@ -59,7 +53,8 @@ document.addEventListener('DOMContentLoaded', async function () {
if (triggerSource === 'change_department') {
fadeOut('change_department.html');
} else if (triggerSource === 'decrypt') {
fadeOut('decrypting_files.html');
console.log('astept decryptarea')
fadeOut('decrypting_backup.html');
}
})
@@ -68,13 +63,28 @@ document.addEventListener('DOMContentLoaded', async function () {
});
checkDirBackupFileExists()
.then(() => console.log('verificare facuta'));
await insertUsername();
.then(() => console.log('verificare backupDir facuta'));
checkShareDirFileExists()
.then(() => console.log('verificare ShareDir facuta'));
checkDepartmentDirFileExists()
.then(() => {console.log('verificare departmentDir facuta')})
backupButton.addEventListener('click', function () {
console.log('Set backup directory button clicked!');
window.electronAPI.openBackupDirDialog()
window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
.then(() => console.log('Back-up directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
});
shareButton.addEventListener('click', function () {
console.log('Set backup directory button clicked!');
window.electronAPI.openJsonDirConfigDialog('dirShare.json')
.then(() => console.log('Back-up directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
@@ -86,6 +96,14 @@ document.addEventListener('DOMContentLoaded', async function () {
fadeOut('profile.html');
});
changeDepartmentButton.addEventListener('click', function () {
handleOverlayOpen('change_department');
});
decryptButton.addEventListener('click', function () {
handleOverlayOpen('decrypt');
});
shareFileButton.addEventListener('click', function () {
console.log('Share a file button clicked!');
fadeOut('share_file.html');
@@ -93,7 +111,7 @@ document.addEventListener('DOMContentLoaded', async function () {
logoutButton.addEventListener('click', async function () {
console.log('Logout button clicked!');
await window.electronAPI.killBeforeLogout();
await window.electronAPI.deleteFile('loginData.json');
fadeOut('login.html');
});
@@ -109,7 +127,7 @@ document.addEventListener('DOMContentLoaded', async function () {
button.id = 'backup_alert';
button.name = 'alert';
button.textContent = 'Set your backup directory!';
button.addEventListener('click', handleButtonClick);
button.addEventListener('click', handleBackupButtonPressed);
notificationsDiv.appendChild(button);
}
} catch (error) {
@@ -117,11 +135,46 @@ document.addEventListener('DOMContentLoaded', async function () {
}
}
async function checkShareDirFileExists() {
try {
const fileExists = await window.electronAPI.checkFileExists('dirShare.json');
async function handleButtonClick() {
if (!fileExists) {
const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button');
button.id = 'share_file_alert';
button.name = 'alert';
button.textContent = 'Set your share directory!';
button.addEventListener('click', handleShareButtonPressed);
notificationsDiv.appendChild(button);
}
} catch (error) {
console.error('Error checking file existence:', error);
}
}
async function checkDepartmentDirFileExists() {
try {
const fileExists = await window.electronAPI.checkFileExists('dirDepartment.json');
if (!fileExists) {
const notificationsDiv = document.getElementById('notifications');
const button = document.createElement('button');
button.id = 'department_alert';
button.name = 'alert';
button.textContent = 'Set your department directory!';
button.addEventListener('click', handleDepartmentButtonPressed);
notificationsDiv.appendChild(button);
}
} catch (error) {
console.error('Error checking file existence:', error);
}
}
async function handleBackupButtonPressed() {
console.log('Button clicked!');
await window.electronAPI.openBackupDirDialog()
await window.electronAPI.openJsonDirConfigDialog('dirBackup.json')
.then(() => console.log('Back-up directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
@@ -131,6 +184,32 @@ document.addEventListener('DOMContentLoaded', async function () {
button.remove();
}
async function handleShareButtonPressed() {
console.log('Button clicked!');
await window.electronAPI.openJsonDirConfigDialog('dirShare.json')
.then(() => console.log('Share directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
const button = document.getElementById('backup_alert');
button.remove();
}
async function handleDepartmentButtonPressed() {
console.log('Button clicked!');
await window.electronAPI.openJsonDirConfigDialog('dirDepartment.json')
.then(() => console.log('Department directory set'))
.catch(async error => await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)));
const button = document.getElementById('backup_alert');
button.remove();
}
async function insertUsername() {
try {
const userData = await window.electronAPI.readFile('loginData.json');
+1 -4
View File
@@ -23,10 +23,7 @@ document.addEventListener('DOMContentLoaded', async function () {
backButton.addEventListener('click', function () {
console.log('Back button clicked!');
window.electronAPI.changeContent('main_menu.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
fadeOut('main_menu.html')
});
submitButton.addEventListener('click', async function (e) {
+47 -15
View File
@@ -1,5 +1,11 @@
document.addEventListener("DOMContentLoaded", function () {
document.addEventListener("DOMContentLoaded", async function () {
let pathToFile = '';
let serverIp = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
serverIp = jsonData.ip;
})
function updateFileName() {
const fileNameElement = document.getElementById('fileName');
@@ -18,7 +24,7 @@ document.addEventListener("DOMContentLoaded", function () {
const {id} = loginData;
fetch('http://localhost:5000/users', {
fetch(`http://${serverIp}/users`, {
method: 'GET',
headers: {
'x-api-key': 'uc_api'
@@ -66,32 +72,58 @@ document.addEventListener("DOMContentLoaded", function () {
event.preventDefault();
console.log('Submit button clicked');
if (pathToFile === '' || pathToFile.length === 0) {
const fileInput = document.getElementById('fileInput');
if (!fileInput.files.length) {
await window.electronAPI.showAlert('File not chosen!')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
return
.catch(error => console.error('Error showing alert:', error));
return;
}
const form = document.getElementById('userDestForm');
const checkboxes = form.querySelectorAll('input[name="users"]');
const selectedUserIds = [];
const selectedUserIds = Array.from(checkboxes)
.filter(checkbox => checkbox.checked)
.map(checkbox => checkbox.value);
checkboxes.forEach(checkbox => {
if (checkbox.checked) {
selectedUserIds.push(checkbox.value);
}
});
if (selectedUserIds === []) {
if (!selectedUserIds.length) {
await window.electronAPI.showAlert('No user selected!')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));
.catch(error => console.error('Error showing alert:', error));
return;
}
//TODO: logic to send files
const uploadData = {
filePath: fileInput.files[0].path,
users: []
};
for (const userId of selectedUserIds) {
try {
const ipResponse = await fetch(`http://${serverIp}/backup_schemes/${userId}`);
if (!ipResponse.ok) {
throw new Error(`Failed to fetch IP address for user ${userId}: status ${ipResponse.status}`);
}
const { data: destIp } = await ipResponse.json();
uploadData.users.push({
userId,
destIp,
destPort: 3000, // Static destination port
fileName: fileInput.files[0].name
});
} catch (error) {
console.error('Error fetching user data:', error);
}
}
window.electronAPI.writeFile('usersDestTemp.json', JSON.stringify(uploadData))
.then(() => {
console.log('File saved successfully');
fadeOut('sending_file_confirmation.html');
})
.catch(error => console.error('Failed to save file:', error));
});
fetchUsersAndCreateCheckboxes().then(() => console.log('Page rendered'))
});
+5 -3
View File
@@ -17,9 +17,11 @@ document.addEventListener('DOMContentLoaded', async function () {
const formContent = document.querySelector('.signup-form-content');
Object.entries(data).forEach(([key, department]) => {
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label);
if(department.name !== 'CEO') {
const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label);
}
});
}).catch(async error => {
await window.electronAPI.showAlert(error.message)