modified some titles and fixed reset database I

This commit is contained in:
andrei-mihnea-cerbu
2025-02-14 12:55:04 +02:00
parent 5c7e723bdc
commit b2f1ea01d3
9 changed files with 46 additions and 88 deletions
@@ -13,7 +13,7 @@
<link href="https://fonts.googleapis.com/css2?family=Pridi:wght@200;300;400;500;600;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Pridi:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
<script src="../js/helpers.js"></script> <script src="../js/helpers.js"></script>
<title>Welcome</title> <title>Restore Backup</title>
</head> </head>
<body onload="fadeIn()"> <body onload="fadeIn()">
<div class="container"> <div class="container">
@@ -23,7 +23,7 @@
<img src="../assets/refresh-data.webp" alt="Backup Fetcher" class="backup-img"> <img src="../assets/refresh-data.webp" alt="Backup Fetcher" class="backup-img">
<div class="loading-section"> <div class="loading-section">
<div class="spinner"></div> <div class="spinner"></div>
<p>Backup is not searched, please wait...</p> <p>Backup is now searched, please wait...</p>
</div> </div>
</div> </div>
</body> </body>
@@ -13,7 +13,7 @@
<script src="../js/helpers.js"></script> <script src="../js/helpers.js"></script>
<script src="../js/reset_database.js"></script> <script src="../js/reset_database.js"></script>
<title>UC Not Found</title> <title>Reset Database</title>
</head> </head>
<body onload="fadeIn()"> <body onload="fadeIn()">
<div class="container"> <div class="container">
@@ -23,7 +23,7 @@
<img src="../assets/2581896.png" style="margin-left: 20px" alt="Connecting to server" class="server-img"> <img src="../assets/2581896.png" style="margin-left: 20px" alt="Connecting to server" class="server-img">
<div class="loading-section"> <div class="loading-section">
<div class="spinner"></div> <div class="spinner"></div>
<p>Please wait while we reset the database.</p> <p>Please wait while we reset the database...</p>
</div> </div>
</div> </div>
</body> </body>
+8 -2
View File
@@ -11,21 +11,27 @@ document.addEventListener('DOMContentLoaded', async function () {
// Open a TCP socket to the stored IP // Open a TCP socket to the stored IP
if (!await window.networkAPI.openUcSocket()) { if (!await window.networkAPI.openUcSocket()) {
await window.uiAPI.showAlert('Internal error of the application. Unable to open socket.'); await window.uiAPI.showAlert('Internal error of the application. Unable to open socket.');
await window.uiAPI.changeContent('main_menu');
return; return;
} }
if (!await window.networkAPI.sendUcMessage(codeResetDatabase)) { if (!await window.networkAPI.sendUcMessage(codeResetDatabase)) {
await window.uiAPI.showAlert('Failed to send login request.'); await window.uiAPI.showAlert('Failed to send login request.');
await window.uiAPI.changeContent('main_menu');
await window.networkAPI.closeUcSocket();
return; return;
} }
const response = await waitForResponse(); const response = await waitForResponse();
if (response && response.operationCode !== codeOk) { if (response && response.operationCode !== codeOk) {
await window.uiAPI.showAlert('Database reset failed.'); await window.uiAPI.showAlert('Database reset failed.');
await window.uiAPI.changeContent('main_menu');
await window.networkAPI.closeUcSocket();
return; return;
} }
await window.networkAPI.closeUcSocket(); await window.networkAPI.closeUcSocket();
await new Promise(resolve => setTimeout(resolve, 2000)); await new Promise(resolve => setTimeout(resolve, 2000));
fadeOut('login');
await window.databaseAPI.resetInternalDatabase();
await window.uiAPI.changeContent('welcome');
}); });
@@ -13,7 +13,7 @@
<link href="https://fonts.googleapis.com/css2?family=Pridi:wght@200;300;400;500;600;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Pridi:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
<script src="../js/helpers.js"></script> <script src="../js/helpers.js"></script>
<title>Welcome</title> <title>Restore Backup</title>
</head> </head>
<body onload="fadeIn()"> <body onload="fadeIn()">
<div class="container"> <div class="container">
@@ -14,12 +14,12 @@
<script src="../js/helpers.js"></script> <script src="../js/helpers.js"></script>
<script src="../js/reset_database.js"></script> <script src="../js/reset_database.js"></script>
<title>Welcome</title> <title>Reset Database</title>
</head> </head>
<body onload="fadeIn()"> <body onload="fadeIn()">
<div class="container"> <div class="container">
<div class="header"> <div class="header">
<h1 class="title">Welcome to TeamVault</h1> <h1 class="title">TeamVault</h1>
</div> </div>
<img src="../assets/2581896.png" style="margin-left: 20px" alt="Connecting to server" class="server-img"> <img src="../assets/2581896.png" style="margin-left: 20px" alt="Connecting to server" class="server-img">
<div class="loading-section"> <div class="loading-section">
+8 -26
View File
@@ -15,7 +15,7 @@ export class DepartmentDatabase {
} }
// Create the table if it doesn't exist // Create the table if it doesn't exist
private createTableIfNotExists() { public createTableIfNotExists() {
const createTableQuery = ` const createTableQuery = `
CREATE TABLE IF NOT EXISTS departments ( CREATE TABLE IF NOT EXISTS departments (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
@@ -25,7 +25,6 @@ export class DepartmentDatabase {
this.db.exec(createTableQuery); this.db.exec(createTableQuery);
const ceoDepartment = this.db.prepare('SELECT COUNT(*) as count FROM departments WHERE name = ?').get('CEO').count; const ceoDepartment = this.db.prepare('SELECT COUNT(*) as count FROM departments WHERE name = ?').get('CEO').count;
const defaultDepartment = this.db.prepare('SELECT COUNT(*) as count FROM departments WHERE name = ?').get('Worker').count;
// Create CEO department if it doesn't exist // Create CEO department if it doesn't exist
if (ceoDepartment === 0) { if (ceoDepartment === 0) {
@@ -35,13 +34,6 @@ export class DepartmentDatabase {
console.log('CEO department already exists.'); console.log('CEO department already exists.');
} }
if (defaultDepartment === 0) {
this.createDepartment('Worker');
console.log('Created Worker department.');
} else {
console.log('Worker department already exists.');
}
console.log('Departments table checked/created.'); console.log('Departments table checked/created.');
} }
@@ -92,25 +84,15 @@ export class DepartmentDatabase {
return stmt.all(); return stmt.all();
} }
public cleanTable(): { success: boolean; message: string } { public dropTable(): { success: boolean; message: string } {
try { try {
// Fetch the CEO department ID this.db.exec('DROP TABLE IF EXISTS departments;');
const ceoDepartmentRow = this.db.prepare(`SELECT id FROM departments WHERE LOWER(name) = 'ceo'`).get(); console.log('Departments table dropped successfully.');
if (!ceoDepartmentRow) { return { success: true, message: 'Departments table dropped successfully.' };
console.error('CEO department not found in the database.');
return { success: false, message: 'Failed to find CEO department.' };
}
const ceoDepartmentId = ceoDepartmentRow.id;
// Delete all departments except the CEO department
const deleteDepartmentsStmt = this.db.prepare(`DELETE FROM departments WHERE id != ?`);
deleteDepartmentsStmt.run(ceoDepartmentId);
return { success: true, message: 'All non-CEO departments have been deleted.' };
} catch (error) { } catch (error) {
console.error('Error while cleaning the departments table:', error); console.error('Error while dropping the departments table:', error);
return { success: false, message: 'Failed to clean departments table.' }; return { success: false, message: 'Failed to drop departments table.' };
} }
} }
} }
+9 -28
View File
@@ -14,19 +14,16 @@ export class KeyDatabase {
private db: any; private db: any;
constructor() { constructor() {
// Get the singleton instance of the database
this.db = SQLiteDatabase.getInstance(); this.db = SQLiteDatabase.getInstance();
// Create the keys table if it doesn't exist
this.createTableIfNotExists(); this.createTableIfNotExists();
} }
// Create the table if it doesn't exist // Create the table if it doesn't exist
private createTableIfNotExists() { public createTableIfNotExists() {
const createTableQuery = ` const createTableQuery = `
CREATE TABLE IF NOT EXISTS user_keys ( CREATE TABLE IF NOT EXISTS user_keys (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
userId TEXT UNIQUE NOT NULL, -- Ensure one key per user userId TEXT UNIQUE NOT NULL,
key TEXT NOT NULL, key TEXT NOT NULL,
iv TEXT NOT NULL, iv TEXT NOT NULL,
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
@@ -134,31 +131,15 @@ export class KeyDatabase {
return stmt.all(); return stmt.all();
} }
// Clean the table but keep CEO keys public dropTable(): { success: boolean; message: string } {
public cleanTable(): { success: boolean; message: string } {
try { try {
const departments = departmentDatabase.getAllDepartments(); this.db.exec('DROP TABLE IF EXISTS user_keys;');
const ceoDepartment = departments.find(dept => dept.name.toLowerCase() === 'ceo'); console.log('user_keys table dropped successfully.');
return { success: true, message: 'user_keys table dropped successfully.' };
if (!ceoDepartment) {
console.error('CEO department not found in the database.');
return { success: false, message: 'Failed to find CEO department.' };
}
// Fetch all users in the CEO department
const ceoUsers = userDatabase.findByDepartmentId(ceoDepartment.id);
const ceoUserIds = ceoUsers.map(user => user.id);
// Delete all keys except for the CEO users
const stmt = this.db.prepare(`
DELETE FROM user_keys WHERE userId NOT IN (${ceoUserIds.map(() => '?').join(', ')})
`);
stmt.run(...ceoUserIds);
return { success: true, message: 'All non-CEO keys have been deleted.' };
} catch (error) { } catch (error) {
console.error('Error while cleaning the keys table:', error); console.error('Error while dropping the user_keys table:', error);
return { success: false, message: 'Failed to clean keys table.' }; return { success: false, message: 'Failed to drop user_keys table.' };
} }
} }
} }
+7 -21
View File
@@ -28,7 +28,7 @@ export class UserDatabase {
} }
// Create the table if it doesn't exist // Create the table if it doesn't exist
private createTableIfNotExists() { public createTableIfNotExists() {
const createTableQuery = ` const createTableQuery = `
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
@@ -209,28 +209,14 @@ export class UserDatabase {
return pbkdf2Sync(password, salt, 1000, 64, 'sha256').toString('hex'); return pbkdf2Sync(password, salt, 1000, 64, 'sha256').toString('hex');
} }
public cleanTable(): { success: boolean; message: string } { public dropTable(): { success: boolean; message: string } {
try { try {
// Fetch departments this.db.exec('DROP TABLE IF EXISTS users;');
const departments = departmentDatabase.getAllDepartments(); console.log('Users table dropped successfully.');
return { success: true, message: 'Users table dropped successfully.' };
const ceoDepartment = departments.find(dept => dept.name.toLowerCase() === 'ceo');
if (!ceoDepartment) {
console.error('Admin or CEO department not found in the database.');
return { success: false, message: 'Failed to find Admin or CEO department.' };
}
// Delete users from the table except for those in the Admin and CEO departments
const stmt = this.db.prepare(`
DELETE FROM users WHERE departmentId NOT IN (?, ?)
`);
stmt.run(ceoDepartment.id);
return { success: true, message: 'All users except Admin and CEO have been deleted.' };
} catch (error) { } catch (error) {
console.error('Error while cleaning the users table:', error); console.error('Error while dropping the users table:', error);
return { success: false, message: 'Failed to clean users table.' }; return { success: false, message: 'Failed to drop users table.' };
} }
} }
} }
@@ -11,10 +11,13 @@ export class CeoOperations implements OperationPlugin {
public static async handleResetDatabase(): Promise<ParsedMessage> { public static async handleResetDatabase(): Promise<ParsedMessage> {
console.log('Resetting the database...'); console.log('Resetting the database...');
departmentDatabase.cleanTable(); keyDatabase.dropTable();
userDatabase.cleanTable(); userDatabase.dropTable();
keyDatabase.cleanTable(); departmentDatabase.dropTable();
departmentDatabase.createDepartment('Worker');
departmentDatabase.createTableIfNotExists();
userDatabase.createTableIfNotExists();
keyDatabase.createTableIfNotExists();
return { return {
operationCode: operationCodes.OK, operationCode: operationCodes.OK,