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
+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;
}
@@ -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>
+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));
});
}