Incepere creare procese separate

This commit is contained in:
andrei-mihnea-cerbu
2024-04-03 23:22:38 +03:00
parent 038b809dd8
commit ffeebf1177
58 changed files with 913 additions and 479 deletions
+4
View File
@@ -27,6 +27,10 @@ app.set('backupSchemesDB', backupSchemesDB);
app.set('ceoDB', ceoDB); app.set('ceoDB', ceoDB);
app.set('adminDB', adminDB); app.set('adminDB', adminDB);
app.use('/heartbeat', (req, res) => {
return res.status(200).json({message: 'Server ap and running.'});
})
const checkJson = require('./middlewares/checkJson'); const checkJson = require('./middlewares/checkJson');
const apiKeyValidation = require('./middlewares/apiKeyValidation'); const apiKeyValidation = require('./middlewares/apiKeyValidation');
+9 -1
View File
@@ -1 +1,9 @@
[] [
{
"id": "4659e71f-9bb4-4902-97d8-097efa138333",
"name": "Andrei Cerbu",
"email": "a@c.com",
"password": "5447045dc3cfaafdb49b365e31dad41eb88616b0b1449930e55fd3a70bd8cee4",
"department": "Contabili"
}
]
+1 -38
View File
@@ -33,43 +33,6 @@ const httpStatus = {
SERVICE_UNAVAILABLE: 503 SERVICE_UNAVAILABLE: 503
}; };
const httpStatusMessages = {
// Informational
[httpStatus.CONTINUE]: "Continue",
[httpStatus.SWITCHING_PROTOCOLS]: "Switching Protocols",
[httpStatus.PROCESSING]: "Processing",
// Success
[httpStatus.OK]: "OK",
[httpStatus.CREATED]: "Created",
[httpStatus.ACCEPTED]: "Accepted",
[httpStatus.NO_CONTENT]: "No Content",
// Redirection module.exports = {httpStatus};
[httpStatus.MOVED_PERMANENTLY]: "Moved Permanently",
[httpStatus.FOUND]: "Found",
[httpStatus.SEE_OTHER]: "See Other",
[httpStatus.NOT_MODIFIED]: "Not Modified",
[httpStatus.TEMPORARY_REDIRECT]: "Temporary Redirect",
// Client Error
[httpStatus.BAD_REQUEST]: "Bad Request",
[httpStatus.UNAUTHORIZED]: "Unauthorized",
[httpStatus.FORBIDDEN]: "Forbidden",
[httpStatus.NOT_FOUND]: "Not Found",
[httpStatus.METHOD_NOT_ALLOWED]: "Method Not Allowed",
[httpStatus.CONFLICT]: "Conflict",
[httpStatus.GONE]: "Gone",
[httpStatus.UNSUPPORTED_MEDIA_TYPE]: "Unsupported Media Type",
// Server Error
[httpStatus.INTERNAL_SERVER_ERROR]: "Internal Server Error",
[httpStatus.NOT_IMPLEMENTED]: "Not Implemented",
[httpStatus.SERVICE_UNAVAILABLE]: "Service Unavailable"
};
const httpHeaders = {
JSON: { 'name': 'Content-Type', 'value': 'application/json' }
};
module.exports = {httpStatus, httpStatusMessages, httpHeaders};
-21
View File
@@ -1,21 +0,0 @@
const {httpHeaders} = require("./httpResponses");
const headers = {
[httpHeaders.JSON.name]: httpHeaders.JSON.value
}
function sendResponse(res, statusCode, message, data = null, headers_parsed = {}) {
Object.entries(headers).forEach(([key, value]) => {
res.setHeader(key, value);
});
// Set headers if provided
Object.entries(headers_parsed).forEach(([key, value]) => {
res.setHeader(key, value);
});
// Send the response with status code, message, and optional data
res.status(statusCode).json({ message, data });
}
module.exports = { sendResponse };
@@ -1,10 +1,9 @@
const { sendResponse } = require('../helpers/responseHelper');
const {httpStatus, httpStatusMessages} = require('../helpers/httpResponses') const {httpStatus, httpStatusMessages} = require('../helpers/httpResponses')
function apiKeyValidation(req, res, next) { function apiKeyValidation(req, res, next) {
const apiKey = req.headers['x-api-key']; const apiKey = req.headers['x-api-key'];
if (apiKey !== req.app.locals.apiKey) { if (apiKey !== req.app.locals.apiKey) {
return sendResponse(res, httpStatus.UNAUTHORIZED, httpStatusMessages[httpStatus.UNAUTHORIZED]); return res.status(httpStatus.UNAUTHORIZED).json({message: 'Invalid API key'});
} }
next(); next();
} }
+3 -3
View File
@@ -1,5 +1,5 @@
const { sendResponse } = require('../helpers/responseHelper');
const {httpStatus, httpStatusMessages} = require("../helpers/httpResponses"); const {httpStatus} = require("../helpers/httpResponses");
function checkJson(req, res, next) { function checkJson(req, res, next) {
if(req.method === 'GET'){ if(req.method === 'GET'){
@@ -7,7 +7,7 @@ function checkJson(req, res, next) {
} }
if (['POST', 'PUT', 'PATCH'].includes(req.method) && req.headers['content-type'] !== 'application/json') { if (['POST', 'PUT', 'PATCH'].includes(req.method) && req.headers['content-type'] !== 'application/json') {
return sendResponse(res, httpStatus.BAD_REQUEST, httpStatusMessages[httpStatus.BAD_REQUEST]); return res.status(httpStatus.BAD_REQUEST).json({message: "Body missing in action."});
} }
next(); next();
@@ -6,6 +6,10 @@ const dirStructureModel = Joi.object({
'string.empty': 'ID must not be empty', 'string.empty': 'ID must not be empty',
'string.guid': 'ID must be a valid GUID' 'string.guid': 'ID must be a valid GUID'
}), }),
ip: Joi.string().ip().required().messages({
'string.ip': 'The IP address "{{#value}}" is not valid.',
'any.required': 'IP address is required.'
}),
dir_config: Joi.string().required().messages({ dir_config: Joi.string().required().messages({
'any.required': 'Directory configuration is required', 'any.required': 'Directory configuration is required',
'string.empty': 'Directory configuration must not be empty' 'string.empty': 'Directory configuration must not be empty'
@@ -5,6 +5,10 @@ const UserDepartmentPatchModel = Joi.object({
'any.required': 'User ID is required', 'any.required': 'User ID is required',
'string.empty': 'User ID must not be empty', 'string.empty': 'User ID must not be empty',
'string.uuid': 'User ID must be a valid UUID' 'string.uuid': 'User ID must be a valid UUID'
}),
department: Joi.string().required().messages({
'any.required': 'User ID is required',
'string.empty': 'User ID must not be empty',
}) })
}); });
+2 -3
View File
@@ -16,10 +16,9 @@ const usersRegisterModel = Joi.object({
'string.min': 'Password must be at least {#limit} characters long', 'string.min': 'Password must be at least {#limit} characters long',
'string.max': 'Password must be at most {#limit} characters long' 'string.max': 'Password must be at most {#limit} characters long'
}), }),
department: Joi.string().uuid().required().messages({ department: Joi.string().required().messages({
'any.required': 'Department ID is required', 'any.required': 'Department ID is required',
'string.empty': 'Department ID must not be empty', 'string.empty': 'Department ID must not be empty'
'string.uuid': 'Department ID must be a valid UUID'
}) })
}); });
+4
View File
@@ -48,4 +48,8 @@ router.get('/users', validateBody, (req, res) => {
res.status(httpStatus.OK).json({ message: "Retrieving users info...", data: usersDB.readFile() }) // Corrected to readFile res.status(httpStatus.OK).json({ message: "Retrieving users info...", data: usersDB.readFile() }) // Corrected to readFile
}); });
router.use((req, res) => {
return res.status(httpStatus.NOT_FOUND).json({message: "Endpoint not found"});
})
module.exports = router; module.exports = router;
+34
View File
@@ -1,15 +1,49 @@
const express = require('express'); const express = require('express');
const {httpStatus} = require("../helpers/httpResponses");
const {schemas} = require("../models/schemaMapper");
const router = express.Router(); const router = express.Router();
function validateBody(req, res, next) { function validateBody(req, res, next) {
let validationSchema = undefined;
if(req.path === '/' && req.method === 'PATCH'){
validationSchema = schemas.dirStructureModelSchema
}
if(validationSchema !== undefined){
const {error} = validationSchema.validate(req.body);
if(error){
const errorMessage = error.details.map(detail => detail.message).join(', ');
return res.status(httpStatus.BAD_REQUEST).json({ message: errorMessage });
}
}
next(); next();
} }
router.patch('/', validateBody, (req, res) => { router.patch('/', validateBody, (req, res) => {
const backupSchemesDB = req.app.get('backupSchemesDB');
const { id, ip, backup_schema, size } = req.body; const { id, ip, backup_schema, size } = req.body;
let backupSchemesJson = backupSchemesDB.readFile();
backupSchemesJson[id] = {
ip: ip,
backup_schema: backup_schema,
size: size
}
return res.status(httpStatus.OK).json({message: 'Backup schema updated'});
}); });
router.get('/', validateBody, (req, res) => { router.get('/', validateBody, (req, res) => {
const backupSchemesDB = req.app.get('backupSchemesDB');
return res.status(httpStatus.OK).json({
message: 'Backup Schemes fetched.',
data: backupSchemesDB.readFile()
});
}); });
router.use((req, res) => {
return res.status(httpStatus.NOT_FOUND).json({message: "Endpoint not found"});
})
module.exports = router; module.exports = router;
+4
View File
@@ -184,4 +184,8 @@ router.get('/get_decrypt_keys', (req, res) => {
}); });
}); });
router.use((req, res) => {
return res.status(httpStatus.NOT_FOUND).json({message: "Endpoint not found"});
})
module.exports = router; module.exports = router;
+30 -5
View File
@@ -1,9 +1,11 @@
const express = require('express'); const express = require('express');
const { v4: uuidv4 } = require('uuid'); const { v4: uuidv4 } = require('uuid');
const crypto = require('crypto');
const {schemas} = require('../models/schemaMapper'); const {schemas} = require('../models/schemaMapper');
const {httpStatus} = require("../helpers/httpResponses"); const {httpStatus} = require("../helpers/httpResponses");
const router = express.Router(); const router = express.Router();
function validateBody(req, res, next) { function validateBody(req, res, next) {
@@ -16,6 +18,9 @@ function validateBody(req, res, next) {
case '/login': case '/login':
validationSchema = schemas.usersLoginModelSchema; validationSchema = schemas.usersLoginModelSchema;
break; break;
case '/validate_ceo_password':
validationSchema = schemas.ceoPasswordModelSchema;
break;
case '/validate_email': case '/validate_email':
validationSchema = schemas.emailVerificationSchema; validationSchema = schemas.emailVerificationSchema;
break; break;
@@ -24,16 +29,15 @@ function validateBody(req, res, next) {
validationSchema = schemas.usersModifyModelSchema; validationSchema = schemas.usersModifyModelSchema;
} }
break; break;
case 'change_department': case '/change_department':
validationSchema = schemas.userDepartmentPatchSchema; validationSchema = schemas.userDepartmentPatchSchema;
break; break;
default: default:
validationSchema = undefined; validationSchema = undefined;
} }
console.log(validationSchema);
if(validationSchema !== undefined){ if(validationSchema !== undefined){
console.log(req.body);
const {error} = validationSchema.validate(req.body); const {error} = validationSchema.validate(req.body);
if(error){ if(error){
const errorMessage = error.details.map(detail => detail.message).join(', '); const errorMessage = error.details.map(detail => detail.message).join(', ');
@@ -69,14 +73,35 @@ router.post('/login', validateBody, (req, res) => {
const { email, password } = req.body; const { email, password } = req.body;
const hashedPassword = crypto.createHash('sha256').update(password).digest('hex'); const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
if(usersDB.readFile().length === 0){
return res.status(httpStatus.NOT_FOUND).json({message: 'Invalid credentials.'});
}
if(usersDB.findIndexByKeyValueInArray('email', email) !== if(usersDB.findIndexByKeyValueInArray('email', email) !==
usersDB.findIndexByKeyValueInArray('password', hashedPassword)){ usersDB.findIndexByKeyValueInArray('password', hashedPassword)){
return res.status(httpStatus.NOT_FOUND).json({message: 'Invalid credentials.'}); return res.status(httpStatus.NOT_FOUND).json({message: 'Invalid credentials.'});
} }
return res.status(httpStatus.Ok).json({message: 'Logged in.'}); const userIndex = usersDB.findIndexByKeyValueInArray('email', email);
return res.status(httpStatus.OK).json({
message: 'Logged in.',
data: usersDB.readFile()[userIndex]
});
}); });
router.post('/validate_ceo_password', validateBody, (req, res) => {
const ceoDB = req.app.get('ceoDB');
const { password } = req.body;
const ceoJson = ceoDB.readFile();
if(ceoJson.password !== password){
return res.status(httpStatus.UNAUTHORIZED).json({message: 'Incorrect CEO password'});
}
return res.status(httpStatus.OK).json({message: 'Password verified.'})
})
router.post('/validate_email', validateBody, (req, res) => { router.post('/validate_email', validateBody, (req, res) => {
const usersDB = req.app.get('usersDB'); const usersDB = req.app.get('usersDB');
const { email } = req.body; const { email } = req.body;
@@ -159,7 +184,7 @@ router.patch('/change_department', validateBody, (req, res) => {
usersJson[userIndex] = userInfo usersJson[userIndex] = userInfo
usersDB.writeFile(usersJson); usersDB.writeFile(usersJson);
return res.status(httpStatus.Ok).json({message: "Department modified."}); return res.status(httpStatus.OK).json({message: "Department modified."});
}); });
router.get('/get_decrypt_keys', (req, res) => { router.get('/get_decrypt_keys', (req, res) => {
+21
View File
@@ -0,0 +1,21 @@
Taskuri
-
- create form which upon submission set's the ip location (also create a button which can change this one and have to
create a IPC for retrieving the ip when making the requests).
- create the encryption process when writing a file on disk / decryption process when reading a file form disk
- configure endpoint for 'backup_schemes' completely
- refactor the JS code from all the html to make it with .then statements and show the messages
from the UC
- finish the CEO interface
- create process which will update the backup scheme with:
- IP
- user_id
- dir_schema
- size
- create process which will fetch the large schema and encryption keys and compare it with the one on local;
if is the same, hibernate; else, make requests for the files
- create process which will get the user database and combine it with the ip and at the request will share a
specific file
- create process which will decrypt all the files from the backup scheme locally
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/iv.key" charset="US-ASCII" />
</component>
</project>
+1
View File
@@ -0,0 +1 @@
ԗ۰s_(kK:Fn]C$
+1
View File
@@ -0,0 +1 @@
äï§¡’a%l:ðIÇ÷ÑÝ
View File
View File
View File
View File
View File
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
4~n`'TnoC:%:x
+76
View File
@@ -0,0 +1,76 @@
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);
});
}
module.exports = {
encryptFileInPlace,
decryptFileInPlace
}
+134 -12
View File
@@ -1,13 +1,57 @@
const { app, BrowserWindow, screen, ipcMain, dialog } = require('electron'); const { app, BrowserWindow, screen, ipcMain, dialog } = require('electron');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const crypto = require('crypto');
const { fork } = require('child_process');
const {encryptFileInPlace, decryptFileInPlace} = require('./aes_encrypt');
const isMac = process.platform === 'darwin'; const isMac = process.platform === 'darwin';
let html_page = undefined; let html_page = undefined;
let mainWindow = undefined; let mainWindow = undefined;
let alertWindow = undefined; let alertWindow = undefined;
const createMainWindow = ((title, width, height) => { let backupProcess = null;
let receiverProcess = null;
let fetcherProcess = 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({ mainWindow = new BrowserWindow({
title: title, title: title,
width: width, width: width,
@@ -19,9 +63,25 @@ const createMainWindow = ((title, width, height) => {
} }
}); });
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'; html_page = 'login.html';
} catch (err) {
html_page = 'ip_submit.html';
}
//mainWindow.setMenu(null); //mainWindow.setMenu(null);
mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', 'login.html')) mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', html_page))
.then(() => { .then(() => {
console.log('Main window loaded!') console.log('Main window loaded!')
}) })
@@ -79,6 +139,18 @@ app.whenReady().then(() => {
}); });
}); });
app.on('before-quit', () => {
if (backupProcess !== null) {
backupProcess.kill();
}
if (receiverProcess !== null) {
receiverProcess.kill();
}
if (fetcherProcess !== null) {
fetcherProcess.kill();
}
});
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
if(!isMac){ if(!isMac){
app.quit(); app.quit();
@@ -89,6 +161,7 @@ ipcMain.handle('write-file', async (event, fileName, content) => {
try { try {
let filePath = path.join(__dirname, '..', '..', fileName); let filePath = path.join(__dirname, '..', '..', fileName);
await fs.promises.writeFile(filePath, content); await fs.promises.writeFile(filePath, content);
await encryptFileInPlace(filePath);
console.log(`File successfully written to ${filePath}`); console.log(`File successfully written to ${filePath}`);
return { success: true }; return { success: true };
} catch (error) { } catch (error) {
@@ -113,8 +186,10 @@ ipcMain.handle('delete-file', async (event, fileName) => {
ipcMain.handle('read-file', async (event, fileName) => { ipcMain.handle('read-file', async (event, fileName) => {
try { try {
let filePath = path.join(__dirname, '..', '..', fileName); let filePath = path.join(__dirname, '..', '..', fileName);
await decryptFileInPlace(filePath);
const content = await fs.promises.readFile(filePath, 'utf-8'); const content = await fs.promises.readFile(filePath, 'utf-8');
await encryptFileInPlace(filePath);
return { success: true, content }; return { success: true, content };
} catch (error) { } catch (error) {
console.error('Error reading file:', error); console.error('Error reading file:', error);
@@ -125,16 +200,7 @@ ipcMain.handle('read-file', async (event, fileName) => {
ipcMain.handle('change-content', async (event, nextPage) => { ipcMain.handle('change-content', async (event, nextPage) => {
try { try {
html_page = nextPage; 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)); await mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', nextPage));
mainWindow.webContents.executeJavaScript(`
document.body.classList.add('fade-in');
`);
return true; return true;
} catch (error) { } catch (error) {
console.error('Error changing content:', error); console.error('Error changing content:', error);
@@ -197,3 +263,59 @@ ipcMain.on('close-alert-window', () => {
alertWindow = undefined; alertWindow = undefined;
} }
}); });
//External processes
ipcMain.handle('start-fetcher', async (event, args) => {
if (fetcherProcess === null) {
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
});
}
return true; // Indicate that the operation has started
});
// Handler to start the backup process
ipcMain.handle('start-backup', async (event, args) => {
if (backupProcess === null) { // Should this be a unique variable for backupProcess instead?
backupProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'backup.js'), args, { silent: false });
backupProcess.on('exit', () => {
backupProcess = null;
// Optionally, notify the renderer process that the backup has finished
});
}
return true; // Indicate that the operation has started
});
// Handler to start the decrypt-files process
ipcMain.handle('start-decrypt-files', async (event, args) => {
const decryptFilesProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'decrypt_files.js'), args, { silent: false });
decryptFilesProcess.on('exit', () => {
event.sender.send('decrypt-files-finished', true); // Notify renderer process
});
return true; // Indicate that the operation has started
});
// Handler to start the send_files process
ipcMain.handle('start-send_files', async (event, args) => {
// This seems to duplicate the 'start-decrypt-files' process; assuming a different script is intended
const sendFilesProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'send_files.js'), args, { silent: false });
sendFilesProcess.on('exit', () => {
event.sender.send('send-files-finished', true); // Notify renderer process
});
return true; // Indicate that the operation has started
});
// Handler to start the receiver process
ipcMain.handle('start-receiver', async (event, args) => {
if (receiverProcess === null) {
receiverProcess = fork(path.join(__dirname, '..', '..', 'jobs', 'receiver.js'), args, { silent: false });
receiverProcess.on('exit', () => {
receiverProcess = null;
// Optionally, notify the renderer process that the receiver has finished
});
}
return true; // Indicate that the operation has started
});
+7 -1
View File
@@ -9,5 +9,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
closeAlertWindow: () => ipcRenderer.send('close-alert-window'), closeAlertWindow: () => ipcRenderer.send('close-alert-window'),
openBackupDirDialog: () => ipcRenderer.invoke('open-backup-dir-dialog'), openBackupDirDialog: () => ipcRenderer.invoke('open-backup-dir-dialog'),
openFileDialog: () => ipcRenderer.invoke('open-file-dialog'), openFileDialog: () => ipcRenderer.invoke('open-file-dialog'),
checkFileExists: (fileName) => ipcRenderer.invoke('check-file-exists', fileName) 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)
}); });
@@ -15,6 +15,8 @@ body, html {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
+98
View File
@@ -0,0 +1,98 @@
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 {
opacity: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
min-height: 100vh;
}
.ip-form {
background-color: #535C91;
opacity: 71;
padding: 9vh 3vh 5vh;
border-radius: 1rem;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.9);
width: 25%;
}
.ip-form-title{
margin: 0 0 5vh 0;
text-align: center;
}
.ip-form-title h2{
color: #FFFFFF;
font-size: 5vh;
margin: 0;
padding: 0;
}
.ip-form hr{
width: 40%;
}
.ip-form-content{
display: flex;
flex-wrap: wrap;
justify-content: center;
}
input {
text-align: center;
color: white;
font-weight: bold;
font-size: 1.2rem;
width: 70%;
padding: 1rem;
margin: 0.7rem;
background-color: #1B1A55;
border-radius: 10px;
}
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;
align-content: center;
align-items: center;
justify-content: space-evenly;
}
button[name="submit"] {
background-color: #F44336;
color: white;
}
+3 -1
View File
@@ -15,6 +15,8 @@ body, html {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
@@ -102,7 +104,7 @@ button[name="submit"] {
color: white; color: white;
} }
button[name="signin"] { button[name="signup"] {
background-color: #2196F3; background-color: #2196F3;
color: white; color: white;
} }
+2
View File
@@ -85,6 +85,8 @@ input {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
+2
View File
@@ -15,6 +15,8 @@ body, html {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
@@ -15,6 +15,8 @@ body, html {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
+2
View File
@@ -15,6 +15,8 @@ body, html {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
@@ -15,6 +15,8 @@ body, html {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
@@ -15,6 +15,8 @@ body, html {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
@@ -15,6 +15,8 @@ body, html {
} }
.container { .container {
opacity: 0;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-evenly; justify-content: space-evenly;
@@ -9,10 +9,11 @@
<link rel="stylesheet" href="../css/transition.css"> <link rel="stylesheet" href="../css/transition.css">
<script src="../js/change_department.js"></script> <script src="../js/change_department.js"></script>
<script src="../js/transition.js"></script>
<title>Department Selection</title> <title>Department Selection</title>
</head> </head>
<body> <body onload="fadeIn()">
<div class="container"> <div class="container">
<form id="departmentForm" class="department-form"> <form id="departmentForm" class="department-form">
<div class="department-form-title"> <div class="department-form-title">
@@ -0,0 +1,25 @@
<!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/sending_file_confirmation.css">
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/transition.js"></script>
<title>Setup Completion</title>
</head>
<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">
</div>
</div>
</body>
</html>
+32
View File
@@ -0,0 +1,32 @@
<!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/ip_submit.css">
<link rel="stylesheet" href="../css/transition.css">
<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 id="ipForm" class="ip-form">
<div class="ip-form-title">
<h2>IP Config</h2>
<hr>
</div>
<div class="ip-form-content">
<input id="ipInput" type="text" name="ip" placeholder="192.168.x.x : Port">
</div>
<div class="ip-form-footer">
<button id="submit" type="submit" name="submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
+6 -2
View File
@@ -4,12 +4,16 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <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="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/login.css"> <link rel="stylesheet" href="../css/login.css">
<link rel="stylesheet" href="../css/transition.css"> <link rel="stylesheet" href="../css/transition.css">
<script src="../js/login.js"></script> <script src="../js/login.js"></script>
<script src="../js/transition.js"></script>
<title>Login</title> <title>Login</title>
</head> </head>
<body> <body onload="fadeIn()">
<div class="container"> <div class="container">
<div class="header"> <div class="header">
<h1>DO WE KNOW</h1> <h1>DO WE KNOW</h1>
@@ -25,7 +29,7 @@
<input type="password" name="password" placeholder="Password"> <input type="password" name="password" placeholder="Password">
</div> </div>
<div class="login-form-footer"> <div class="login-form-footer">
<button id="signin" type="submit" name="signin">Sign in</button> <button id="signup" type="submit" name="signup">Sign Up</button>
<button id="submit" type="submit" name="submit">Submit</button> <button id="submit" type="submit" name="submit">Submit</button>
</div> </div>
</form> </form>
+3 -1
View File
@@ -4,15 +4,17 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <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="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/main_menu.css"> <link rel="stylesheet" href="../css/main_menu.css">
<link rel="stylesheet" href="../css/transition.css"> <link rel="stylesheet" href="../css/transition.css">
<script src="../js/main_menu.js"></script> <script src="../js/main_menu.js"></script>
<script src="../js/transition.js"></script>
<title>Main Page</title> <title>Main Page</title>
</head> </head>
<body> <body onload="fadeIn()">
<div id="overlay" class="overlay"> <div id="overlay" class="overlay">
<form id="ceo_validation" class="ceo-validation-form"> <form id="ceo_validation" class="ceo-validation-form">
<h2>CEO Authentication</h2> <h2>CEO Authentication</h2>
+2 -1
View File
@@ -9,10 +9,11 @@
<link rel="stylesheet" href="../css/transition.css"> <link rel="stylesheet" href="../css/transition.css">
<script src="../js/profile.js"></script> <script src="../js/profile.js"></script>
<script src="../js/transition.js"></script>
<title>Profile</title> <title>Profile</title>
</head> </head>
<body> <body onload="fadeIn()">
<div class="container"> <div class="container">
<form id="profileForm" class="profile-form"> <form id="profileForm" class="profile-form">
<div class="profile-form-title"> <div class="profile-form-title">
@@ -4,10 +4,15 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <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="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<title>Setup Completion</title>
<link rel="stylesheet" href="../css/sending_file_confirmation.css"> <link rel="stylesheet" href="../css/sending_file_confirmation.css">
<link rel="stylesheet" href="../css/transition.css">
<script src="../js/transition.js"></script>
<title>Setup Completion</title>
</head> </head>
<body> <body onload="fadeIn()">
<div class="container"> <div class="container">
<div class="header"> <div class="header">
<h1>SENDING THE FILE!</h1> <h1>SENDING THE FILE!</h1>
+3 -1
View File
@@ -9,9 +9,11 @@
<link rel="stylesheet" href="../css/transition.css"> <link rel="stylesheet" href="../css/transition.css">
<script src="../js/share_file.js"></script> <script src="../js/share_file.js"></script>
<script src="../js/transition.js"></script>
<title>Share File</title> <title>Share File</title>
</head> </head>
<body> <body onload="fadeIn()">
<div class="container"> <div class="container">
<div class="left_block"> <div class="left_block">
<div class="left_block_top"> <div class="left_block_top">
@@ -4,12 +4,16 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <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="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/sign_up_confirmation.css"> <link rel="stylesheet" href="../css/sign_up_confirmation.css">
<link rel="stylesheet" href="../css/transition.css"> <link rel="stylesheet" href="../css/transition.css">
<script src="../js/sign_up_confirmation.js"></script> <script src="../js/sign_up_confirmation.js"></script>
<script src="../js/transition.js"></script>
<title>Setup Completion</title> <title>Setup Completion</title>
</head> </head>
<body> <body onload="fadeIn()">
<div class="container"> <div class="container">
<div class="header"> <div class="header">
<h1>ALL THE SETUP IS DONE!</h1> <h1>ALL THE SETUP IS DONE!</h1>
@@ -9,10 +9,11 @@
<link rel="stylesheet" href="../css/transition.css"> <link rel="stylesheet" href="../css/transition.css">
<script src="../js/sign_up_departments.js"></script> <script src="../js/sign_up_departments.js"></script>
<script src="../js/transition.js"></script>
<title>Department Selection</title> <title>Department Selection</title>
</head> </head>
<body> <body onload="fadeIn()">
<div class="container"> <div class="container">
<div class="header"> <div class="header">
<h1>TELL ME MORE</h1> <h1>TELL ME MORE</h1>
+5 -1
View File
@@ -4,12 +4,16 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <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="icon" href="../assets/hard-disk.ico" type="image/x-icon">
<link rel="stylesheet" href="../css/transition.css"> <link rel="stylesheet" href="../css/transition.css">
<link rel="stylesheet" href="../css/sing_up_profile.css"> <link rel="stylesheet" href="../css/sing_up_profile.css">
<script src="../js/sign_up_profile.js"></script> <script src="../js/sign_up_profile.js"></script>
<script src="../js/transition.js"></script>
<title>Signup</title> <title>Signup</title>
</head> </head>
<body> <body onload="fadeIn()">
<div class="container"> <div class="container">
<div class="header"> <div class="header">
<h1>LET US MEET</h1> <h1>LET US MEET</h1>
+25 -29
View File
@@ -1,42 +1,45 @@
document.addEventListener('DOMContentLoaded', async function() { document.addEventListener('DOMContentLoaded', async function () {
try { let ip = '';
// Make API call to fetch department data await window.electronAPI.readFile('ipConfig.json')
const response = await fetch('http://localhost:5000/departments', { .then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
await fetch(`http://${ip}/users/departments`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-api-key': 'uc_api' 'x-api-key': 'uc_api'
} }
}); }).then(async result => {
const res = await response.json(); const res = await result.json();
const data = res['data']; const data = res['data'];
const formContent = document.querySelector('.department-form-content'); const formContent = document.querySelector('.department-form-content');
data.forEach(department => { Object.entries(data).forEach(([key, department]) => {
const label = document.createElement('label'); const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.id}">${department.name}`; label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label); formContent.appendChild(label);
}); });
} catch (error) { }).catch(async error => {
await window.electronAPI.showAlert(error.message) await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error)); .catch(error => console.error('Error changing content:', error));
} });
document.getElementById('back').addEventListener('click', async function () { document.getElementById('back').addEventListener('click', async function () {
try { try {
await window.electronAPI.changeContent('main_menu.html'); await fadeOut('main_menu.html');
console.log('Content changed successfully'); console.log('Content changed successfully');
} catch (error) { } catch (error) {
console.error('Error changing content:', error); console.error('Error changing content:', error);
} }
}); });
document.getElementById('submit').addEventListener('click', async function(e) { document.getElementById('submit').addEventListener('click', async function (e) {
e.preventDefault(); e.preventDefault();
const selectedDept = document.querySelector('input[name="dept"]:checked').value; const selectedDept = document.querySelector('input[name="dept"]:checked').value;
try {
if (!selectedDept) { if (!selectedDept) {
throw new Error('No department had been selected!.'); throw new Error('No department had been selected!.');
} }
@@ -46,37 +49,30 @@ document.addEventListener('DOMContentLoaded', async function() {
throw new Error('Error reading the file. Please try again later.'); throw new Error('Error reading the file. Please try again later.');
} }
const data = JSON.parse(result.content); const data = JSON.parse(await result.content);
const id = data.id; const id = data.id;
await fetch(`http://localhost:5000/users/${id}`, { await fetch(`http://${ip}/users/change_department`, {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': 'uc_api' 'x-api-key': 'uc_api'
}, },
body: JSON.stringify({ body: JSON.stringify({
id: id,
department: selectedDept, department: selectedDept,
}) })
}).then(async response => { }).then(async response => {
if(!response.ok){ 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));
return; return;
} }
window.electronAPI.changeContent('main_menu.html') fadeOut('main_menu.html')
.then(() => console.log('Content changed successfully')) }).catch(async error => {
.catch(error => console.error('Error changing content:', error));
}).catch(error => {
console.error(error); console.error(error);
});
} catch (error) {
await window.electronAPI.showAlert(error.message) await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error)); .catch(error => console.error('Error changing content:', error));
}
}); });
}); });
})
+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));
}
});
});
+46 -42
View File
@@ -1,13 +1,28 @@
document.addEventListener('DOMContentLoaded', async function () { document.addEventListener('DOMContentLoaded', async function () {
const signinButton = document.getElementById('signin'); const signupButton = document.getElementById('signup');
const submitButton = document.getElementById('submit'); const submitButton = document.getElementById('submit');
const signupDataExists = await window.electronAPI.checkFileExists('signupData.json');
if(signupDataExists){
await window.electronAPI.deleteFile('signupData.json');
}
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') await window.electronAPI.readFile('loginData.json')
.then(async result => { .then(async result => {
const loginData = JSON.parse(result.content); const loginData = JSON.parse(result.content);
const { email, password } = loginData; console.log(loginData);
const {email, password} = loginData;
const response = await fetch('http://localhost:5000/users/login', { await fetch(`http://${ip}/users/login`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -17,26 +32,27 @@ document.addEventListener('DOMContentLoaded', async function () {
email: email, email: email,
password: password password: password
}) })
}); }).then(response => {
if (response.ok) {
if(response.ok) { fadeOut('main_menu.html');
window.electronAPI.changeContent('main_menu.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
} }
}).catch(async error => { }).catch(error => {
console.error('Can\'t read loginData'); console.error(error);
await window.electronAPI.deleteFile('loginData.json')
}); });
})
.catch(async error => {
console.error('Can\'t read loginData');
await window.electronAPI.deleteFile('loginData.json');
});
}
signinButton.addEventListener('click', function (e) { signupButton.addEventListener('click', function (e) {
window.electronAPI.changeContent('sign_up_profile.html') e.preventDefault();
.then(() => console.log('Content changed successfully')) console.log('Sign up button clicked.')
.catch(error => console.error('Error changing content:', error)); fadeOut('sign_up_profile.html');
}); });
submitButton.addEventListener('click', async function (e) { submitButton.addEventListener('click', async function (e) {
try {
e.preventDefault(); e.preventDefault();
console.log('Submit button clicked'); console.log('Submit button clicked');
@@ -46,11 +62,7 @@ document.addEventListener('DOMContentLoaded', async function () {
const email = formData.get('email'); const email = formData.get('email');
const password = formData.get('password'); const password = formData.get('password');
if (!email || !password) { await fetch(`http://${ip}/users/login`, {
throw new Error('Both email and password are required.');
}
const response = await fetch('http://localhost:5000/users/login', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -60,30 +72,22 @@ document.addEventListener('DOMContentLoaded', async function () {
email: email, email: email,
password: password password: password
}) })
}); }).then(async response => {
if (!response.ok) {
switch (response.status) { const data = await response.json();
case 401: throw new Error(data.message);
throw new Error('Invalid credentials!');
case 500:
throw new Error('Internal server error. Try again later!');
} }
const responseBody = await response.json(); return response.json();
}).then(async data => {
const result = await window.electronAPI.writeFile('loginData.json', JSON.stringify(responseBody.message, null, 2)); console.log(data)
if (!result.success) { await window.electronAPI.writeFile('loginData.json', JSON.stringify(responseBody.message, null, 2));
throw new Error('Error writing to file. Please try again later.'); fadeOut('main_menu.html');
} })
.catch(async error => {
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) await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)); .catch(error => console.error('Error showing alert:', error));
} })
}); });
}); });
+20 -61
View File
@@ -10,8 +10,16 @@ document.addEventListener('DOMContentLoaded', async function () {
const ceoBackButton = document.getElementById('back_button'); const ceoBackButton = document.getElementById('back_button');
const ceoSubmitButton = document.getElementById('submit_button'); const ceoSubmitButton = document.getElementById('submit_button');
let ip = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
let triggerSource = ''; let triggerSource = '';
function handleOverlayOpen(buttonId) { function handleOverlayOpen(buttonId) {
overlay.style.display = 'block'; overlay.style.display = 'block';
triggerSource = buttonId; // Remember the button that triggered the overlay triggerSource = buttonId; // Remember the button that triggered the overlay
@@ -26,69 +34,34 @@ document.addEventListener('DOMContentLoaded', async function () {
handleOverlayOpen('decrypt'); handleOverlayOpen('decrypt');
}); });
// Hide the form when the "Back" button is clicked
ceoBackButton.addEventListener('click', function() { ceoBackButton.addEventListener('click', function() {
overlay.style.display = 'none'; overlay.style.display = 'none';
}); });
// Validate and process the form when submitted
ceoSubmitButton.addEventListener('click', async function(event) { ceoSubmitButton.addEventListener('click', async function(event) {
event.preventDefault(); event.preventDefault();
const password = document.getElementById('ceo_password').value; const password = document.getElementById('ceo_password').value;
if (password === '') { await fetch(`http://${ip}/users/validate_ceo_password`, {
await window.electronAPI.showAlert('Please enter password')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
return;
}
let fetchResult;
let fetchJson = undefined;
fetchResult = await fetch('http://localhost:5000/admin/reset_key', {
method: 'GET',
headers: {
'x-api-key': 'uc_api'
}
})
if(!fetchResult.ok){
await window.electronAPI.showAlert('Internal server error. Please try again later!')
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
return;
}
fetchJson = await fetchResult.json();
const adminKey = fetchJson['data'];
fetchResult = await fetch('http://localhost:5000/admin/validate_admin_password', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': 'uc_api', 'x-api-key': 'uc_api',
'admin-key': adminKey
}, },
body: JSON.stringify({ body: JSON.stringify({
password: password password: password
}) })
}) }).then(async result => {
const data = await result.json();
if(!fetchResult.ok){ if(!result.ok){
await window.electronAPI.showAlert('The password is incorrect') throw new Error(data.message);
.then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error));
return;
} }
if (triggerSource === 'change_department') { if (triggerSource === 'change_department') {
window.electronAPI.changeContent('change_department.html') fadeOut('change_department.html');
.then(() => console.log('Navigated to dashboard')) }else if (triggerSource === 'decrypt'){
.catch(error => console.error('Error navigating:', error)); fadeOut('decrypting_files.html');
} else if (triggerSource === 'decrypt') {
await decryptFiles()
} }
})
overlay.style.display = 'none'; overlay.style.display = 'none';
triggerSource = ''; triggerSource = '';
@@ -110,29 +83,19 @@ document.addEventListener('DOMContentLoaded', async function () {
changeInfoButton.addEventListener('click', function () { changeInfoButton.addEventListener('click', function () {
console.log('Change your info button clicked!'); 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));
}); });
shareFileButton.addEventListener('click', function () { shareFileButton.addEventListener('click', function () {
console.log('Share a file button clicked!'); console.log('Share a file button clicked!');
fadeOut('share_file.html');
window.electronAPI.changeContent('share_file.html')
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
}); });
logoutButton.addEventListener('click', async function () { logoutButton.addEventListener('click', async function () {
console.log('Logout button clicked!'); console.log('Logout button clicked!');
await window.electronAPI.deleteFile('loginData.json'); await window.electronAPI.deleteFile('loginData.json');
window.electronAPI.changeContent('login.html') fadeOut('login.html');
.then(() => console.log('Navigated to dashboard'))
.catch(error => console.error('Error navigating:', error));
}); });
async function checkDirBackupFileExists() { async function checkDirBackupFileExists() {
@@ -184,8 +147,4 @@ document.addEventListener('DOMContentLoaded', async function () {
usernameField.textContent = 'User!'; usernameField.textContent = 'User!';
} }
} }
async function decryptFiles(){
}
}); });
+16 -23
View File
@@ -1,9 +1,15 @@
document.addEventListener('DOMContentLoaded', async function () { document.addEventListener('DOMContentLoaded', async function () {
try {
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 result = await window.electronAPI.readFile('loginData.json');
const loginData = JSON.parse(result.content); const loginData = JSON.parse(result.content);
// Set values for the inputs
const emailInput = document.querySelector('input[name="email"]'); const emailInput = document.querySelector('input[name="email"]');
const usernameInput = document.querySelector('input[name="username"]'); const usernameInput = document.querySelector('input[name="username"]');
const passwordInput = document.querySelector('input[name="password"]'); const passwordInput = document.querySelector('input[name="password"]');
@@ -12,14 +18,9 @@ document.addEventListener('DOMContentLoaded', async function () {
usernameInput.value = loginData.name; usernameInput.value = loginData.name;
passwordInput.value = loginData.password; passwordInput.value = loginData.password;
} catch (error) {
console.error('Error reading login data:', error);
}
const backButton = document.querySelector('button[name="login"]'); const backButton = document.querySelector('button[name="login"]');
const submitButton = document.querySelector('button[name="submit"]'); const submitButton = document.querySelector('button[name="submit"]');
// Add event listeners for the back and submit buttons
backButton.addEventListener('click', function () { backButton.addEventListener('click', function () {
console.log('Back button clicked!'); console.log('Back button clicked!');
@@ -29,7 +30,6 @@ document.addEventListener('DOMContentLoaded', async function () {
}); });
submitButton.addEventListener('click', async function (e) { submitButton.addEventListener('click', async function (e) {
try {
e.preventDefault(); e.preventDefault();
console.log('Submit button clicked!'); console.log('Submit button clicked!');
@@ -45,7 +45,7 @@ document.addEventListener('DOMContentLoaded', async function () {
const name = usernameInput.value; const name = usernameInput.value;
const password = passwordInput.value; const password = passwordInput.value;
const response = await fetch(`http://localhost:5000/users/${id}`, { await fetch(`http://${ip}/users`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -56,15 +56,10 @@ document.addEventListener('DOMContentLoaded', async function () {
email: email, email: email,
password: password password: password
}) })
}); }).then(async result => {
const data = await result.json();
switch (response.status) { if (!result.ok) {
case 400: throw new Error(data.message);
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 window.electronAPI.writeFile('loginData.json', JSON.stringify({ await window.electronAPI.writeFile('loginData.json', JSON.stringify({
@@ -75,13 +70,11 @@ document.addEventListener('DOMContentLoaded', async function () {
department: department department: department
})); }));
window.electronAPI.changeContent('main_menu.html') fadeOut('main_menu.html');
.then(() => console.log('Navigated to dashboard')) }).catch(async error => {
.catch(error => console.error('Error navigating:', error));
}catch(error) {
await window.electronAPI.showAlert(error.message) await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error showing alert:', error)); .catch(error => console.error('Error showing alert:', error));
} })
}); });
}); });
+1 -8
View File
@@ -10,7 +10,6 @@ document.addEventListener("DOMContentLoaded", function() {
} }
} }
// Call the function to update file name on DOMContentLoaded
updateFileName(); updateFileName();
async function fetchUsersAndCreateCheckboxes() { async function fetchUsersAndCreateCheckboxes() {
@@ -60,13 +59,7 @@ document.addEventListener("DOMContentLoaded", function() {
document.getElementById('backButton').addEventListener('click', async function () { document.getElementById('backButton').addEventListener('click', async function () {
console.log('Back button clicked'); console.log('Back button clicked');
fadeOut('main_menu.html');
try {
await window.electronAPI.changeContent('main_menu.html');
console.log('Content changed successfully');
} catch (error) {
console.error('Error changing content:', error);
}
}); });
document.getElementById('submitButton').addEventListener('click', async function (event) { document.getElementById('submitButton').addEventListener('click', async function (event) {
+1 -4
View File
@@ -1,7 +1,4 @@
document.addEventListener('DOMContentLoaded', async function() { document.addEventListener('DOMContentLoaded', async function() {
await new Promise(resolve => setTimeout(resolve, 2000)); await new Promise(resolve => setTimeout(resolve, 2000));
fadeOut('login.html');
window.electronAPI.changeContent('login.html')
.then(() => console.log('Content changed successfully'))
.catch(error => console.error('Error changing content:', error));
}); });
+43 -48
View File
@@ -1,93 +1,88 @@
document.addEventListener('DOMContentLoaded', async function() { document.addEventListener('DOMContentLoaded', async function () {
try { let ip = '';
// Make API call to fetch department data await window.electronAPI.readFile('ipConfig.json')
const response = await fetch('http://localhost:5000/departments', { .then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
await fetch(`http://${ip}/users/departments`, {
method: 'GET', method: 'GET',
headers: { headers: {
'x-api-key': 'uc_api' 'x-api-key': 'uc_api'
} }
}); }).then(async result => {
const res = await response.json(); const res = await result.json();
const data = res['data']; const data = res['data'];
const formContent = document.querySelector('.signup-form-content'); const formContent = document.querySelector('.signup-form-content');
data.forEach(department => { Object.entries(data).forEach(([key, department]) => {
const label = document.createElement('label'); const label = document.createElement('label');
label.innerHTML = `<input type="radio" name="dept" value="${department.id}">${department.name}`; label.innerHTML = `<input type="radio" name="dept" value="${department.name}">${department.name}`;
formContent.appendChild(label); formContent.appendChild(label);
}); });
} catch (error) { }).catch(async error => {
await window.electronAPI.showAlert(error.message) await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error)); .catch(error => console.error('Error changing content:', error));
} });
document.getElementById('back').addEventListener('click', async function() { document.getElementById('back').addEventListener('click', async function () {
try { fadeOut('sign_up_profile.html');
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 // Handler for the continue button
document.getElementById('submit').addEventListener('click', async function(e) { document.getElementById('submit').addEventListener('click', async function (e) {
e.preventDefault(); e.preventDefault();
await window.electronAPI.readFile('signupData.json')
.then(async result => {
const selectedDept = document.querySelector('input[name="dept"]:checked').value; const selectedDept = document.querySelector('input[name="dept"]:checked').value;
try {
if (!selectedDept) { if (!selectedDept) {
throw new Error('No department had been selected!.'); 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 data = JSON.parse(result.content);
const email = data.email; const email = data.email;
const name = data.name; const name = data.name;
const password = data.password; const password = data.password;
result = await window.electronAPI.deleteFile('signupData.json'); const userData = {
if (!result.success) { name: name,
throw new Error('Error deleting the file. Please try again later.'); email: email,
password: password,
department: selectedDept,
} }
await fetch('http://localhost:5000/users/register', { await fetch(`http://${ip}/users/register`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-api-key': 'uc_api' 'x-api-key': 'uc_api'
}, },
body: JSON.stringify({ body: JSON.stringify(userData)
name: name,
email: email,
password: password,
department: selectedDept,
}) })
}).then(async response => { .then(async response => {
if(!response.ok){ let data = await response.json();
await window.electronAPI.showAlert("Internal server error. Try again later!")
.then(() => console.log('Alert window opened')) if (!response.ok) {
.catch(error => console.error('Error changing content:', error)); console.log(data);
throw new Error(data.message);
} }
window.electronAPI.changeContent('sign_up_confirmation.html') data = data.data;
.then(() => console.log('Content changed successfully')) userData['id'] = data.id;
.catch(error => console.error('Error changing content:', error));
}).catch(error => {
console.error(error);
});
} catch (error) { await window.electronAPI.writeFile('loginData.json', JSON.stringify(userData));
fadeOut('sign_up_confirmation.html');
})
})
.catch(async error => {
await window.electronAPI.showAlert(error.message) await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error)); .catch(error => console.error('Error changing content:', error));
} })
}); });
}); })
+35 -45
View File
@@ -1,16 +1,36 @@
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', async function () {
const cancelButton = document.getElementById('login'); const cancelButton = document.getElementById('login');
const continueButton = document.getElementById('continue'); const continueButton = document.getElementById('continue');
const signupDataExists = await window.electronAPI.checkFileExists('signupData.json');
if(signupDataExists){
await window.electronAPI.readFile('signupData.json')
.then(result => {
const signupData = JSON.parse(result.content);
// Assign the values to the form inputs
if (signupData.email) document.querySelector('input[name="email"]').value = signupData.email;
if (signupData.name) document.querySelector('input[name="name"]').value = signupData.name;
if (signupData.password) document.querySelector('input[name="password"]').value = signupData.password;
})
.catch(error => {
console.error('Error reading signup data:', error.message);
});
}
let ip = '';
await window.electronAPI.readFile('ipConfig.json')
.then(result => {
const jsonData = JSON.parse(result.content);
ip = jsonData.ip;
})
cancelButton.addEventListener('click', function () { cancelButton.addEventListener('click', function () {
console.log(`'Login' button clicked!`); console.log(`'Login' button clicked!`);
window.electronAPI.changeContent('login.html') fadeOut('login.html');
.then(() => console.log('Content changed successfully'))
.catch(error => console.error('Error changing content:', error));
}); });
continueButton.addEventListener('click', async function (e) { continueButton.addEventListener('click', async function (e) {
try {
e.preventDefault(); e.preventDefault();
console.log('Continue button clicked'); console.log('Continue button clicked');
@@ -18,20 +38,8 @@ document.addEventListener('DOMContentLoaded', function () {
const formData = new FormData(form); const formData = new FormData(form);
const email = formData.get('email'); const email = formData.get('email');
const name = formData.get('name');
const password = formData.get('password');
if (!email || !name || !password) { await fetch(`http://${ip}/users/validate_email`, {
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', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -41,41 +49,23 @@ document.addEventListener('DOMContentLoaded', function () {
email: email email: email
}) })
}).then(async response => { }).then(async response => {
const responseData = await response.json(); if (!response.ok) {
statusFetch = response.status; const data = await response.json();
console.error(responseData.message); throw new Error(data.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!');
} }
}).then(async () => {
const formDataJSON = {}; const formDataJSON = {};
formData.forEach((value, key) => { formData.forEach((value, key) => {
formDataJSON[key] = value; formDataJSON[key] = value;
}); });
const result = await window.electronAPI.writeFile('signupData.json', JSON.stringify(formDataJSON)); await window.electronAPI.writeFile('signupData.json', JSON.stringify(formDataJSON));
if (!result.success) { fadeOut('sign_up_departments.html');
throw new Error('Error writing to file. Please try again later.'); }).catch(async error => {
}
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) await window.electronAPI.showAlert(error.message)
.then(() => console.log('Alert window opened')) .then(() => console.log('Alert window opened'))
.catch(error => console.error('Error changing content:', error));; .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));
});
}