-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.js
More file actions
220 lines (181 loc) · 7.98 KB
/
Copy pathfunctions.js
File metadata and controls
220 lines (181 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Declare the db variable in the global scope
let db1;
// Function to open or create IndexedDB
function setupIndexedDB() {
const request = indexedDB.open("AdminsDB", 1);
request.onupgradeneeded = function (event) {
db1 = event.target.result;
// Create "admins" object store
if (!db1.objectStoreNames.contains("admins")) {
const adminStore = db1.createObjectStore("admins", { keyPath: "id" });
adminStore.createIndex("email", "email", { unique: true });
}
// Create "userLogins" object store
if (!db1.objectStoreNames.contains("userLogins")) {
const userLoginsStore = db1.createObjectStore("userLogins", { autoIncrement: true });
userLoginsStore.createIndex("username", "username", { unique: true });
}
};
request.onsuccess = function (event) {
db1 = event.target.result; // Assign the db object to the global variable
console.log("IndexedDB initialized successfully.");
fetchAndStoreAdminData(); // Fetch and store data after DB is ready
populateAdminSelect(); // Populate data in the select dropdown
};
request.onerror = function (event) {
console.error("Error opening IndexedDB:", event.target.error);
};
}
// Function to fetch and store JSON data in the "admins" table
function fetchAndStoreAdminData() {
const url = "https://jsethi-mdx.github.io/cst2572.github.io/admin.json";
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => {
console.log("JSON data fetched successfully:", data);
const transaction = db1.transaction(["admins"], "readwrite");
const objectStore = transaction.objectStore("admins");
data.forEach(admin => {
objectStore.put(admin);
});
transaction.oncomplete = function () {
console.log("All admin data added to IndexedDB.");
};
transaction.onerror = function (event) {
console.error("Transaction error:", event.target.error);
};
})
.catch(error => {
console.error("Error fetching JSON:", error);
});
}
// Function to populate the admin select dropdown
function populateAdminSelect() {
const adminSelect = document.getElementById('adminSelect');
if (!db1) {
console.error("Database not initialized.");
return;
}
const transaction = db1.transaction(['admins'], 'readonly');
const objectStore = transaction.objectStore('admins');
const request = objectStore.getAll();
request.onsuccess = function (event) {
const admins = event.target.result;
if (adminSelect) {
admins.forEach(admin => {
const option = document.createElement('option');
option.value = admin.id; // Use admin ID as the value
option.textContent = `${admin.first_name} ${admin.last_name}`; // Display full name
adminSelect.appendChild(option);
});
}
};
request.onerror = function (event) {
console.error('Error loading admins:', event.target.error);
};
}
// Helper function to open the database (Promise-based)
function getDatabase() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("AdminsDB", 1);
request.onsuccess = function (event) {
resolve(event.target.result);
};
request.onerror = function (event) {
reject(event.target.error);
};
});
}
// Function to store login details
async function storeLoginDetails(username, password) {
if (!db1) {
console.error("Database not initialized.");
return;
}
const transaction = db1.transaction(['userLogins'], 'readwrite');
const objectStore = transaction.objectStore('userLogins');
const hashedPassword = await hashPassword(password);
const request = objectStore.add({ username, password: hashedPassword });
request.onsuccess = function () {
console.log("User login details saved successfully.");
};
request.onerror = function (event) {
console.error("Error saving login details:", event.target.error);
};
}
// Example password hashing function (replace with a secure library in production)
async function hashPassword(password) {
const encoder = new TextEncoder();
const data = encoder.encode(password);
const hash = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, "0"))
.join("");
}
// Function to validate login
async function validateAdminLogin() {
if (!db1) {
console.error("Database not initialized.");
return false;
}
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const hashedPassword = await hashPassword(password);
const transaction = db1.transaction(['userLogins'], 'readonly');
const objectStore = transaction.objectStore('userLogins');
const request = objectStore.getAll();
request.onsuccess = function (event) {
const users = event.target.result;
const user = users.find(u => u.username === username && u.password === hashedPassword); // matches user password with hashed password, and their username
// if user found
if (user) {
alert("Login successful"); // display alert to user saying successful
localStorage.setItem('isAdminLoggedIn', 'true'); // set in local storage - similar to a cookie
localStorage.setItem('loggedInAdminUsername', username); // set in local storage the username of current logged in admin user
localStorage.setItem('loggedInAdminID', user.id); // set in local storage the logged in admin's ID using OOP to access this value
window.location.href = "admin.html"; // redirect
} else {
alert("Invalid username or password."); // display msg to user saying invalid login details if user not found based on inputted login details
}
};
// error handling
request.onerror = function (event) {
console.error("Error validating login", event.target.error);
};
return false;
}
// Create admin login details
async function createAdminLoginDetails() {
let adminId = document.getElementById('adminSelect').value; // get value of inputted/selected value into the adminSelect
let password = document.getElementById('password').value; // get value of password form field and store as variable here
const hashedPassword = await hashPassword(password); // hash password for security reasons
let transaction = db1.transaction(['admins', 'userLogins'], 'readwrite'); // read write permissions
let adminStore = transaction.objectStore('admins'); // access object store called logins
let loginStore = transaction.objectStore('userLogins'); // access object store called userLogins
let adminRequest = adminStore.get(parseInt(adminId)); // convert admin ID to integer and get from object store
adminRequest.onsuccess = function(event) {
let admin = event.target.result;
if (admin) {
// use OOP to map form submitted data to fields within our DB
let loginData = {
id: adminId,
username: admin.email,
password: hashedPassword
};
// add new login details via loginData parameter to our object store in DB
let loginRequest = loginStore.add(loginData);
loginRequest.onsuccess = function() {
alert("Admin login details created successfully!"); // display msg prompt to user
};
}
};
}
// Start the database when the page loads
window.onload = function() {
setupIndexedDB(); // Execute DB initialization
};