-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
372 lines (337 loc) · 12.6 KB
/
db.js
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
const {PrismaClient} = require('@prisma/client');
const argon2 = require('argon2');
const createLogger = require('./logger');
const logger = createLogger(__filename);
const crypto = require('crypto');
require('dotenv').config();
const prisma = new PrismaClient();
/**
* Represents the database handling for RFID and user management.
* Utilizes Prisma as an ORM for database operations and Argon2 for hashing.
*/
class Database {
/**
* Constructs a new Database instance and sets the maximum users allowed.
*/
constructor() {
this.maxUsers = process.env.MAX_USERS || 5;
logger.info(`Database operation: Initialized Database instance with Prisma ORM. Max users set to ${this.maxUsers}.`);
}
async insertRfidTag(tagUid, username) {
try {
// Hash the RFID tag UID with SHA-256
const hash = crypto.createHash('sha256').update(tagUid).digest('hex');
const newTag = await prisma.validTag.create({
data: {
tag: hash,
username: username
}
});
return newTag;
} catch (err) {
logger.error(`Database operation error: Failed to insert RFID tag for user '${username}'. Error: ${err.message}`);
throw err;
}
}
/**
* Removes an RFID tag from the database.
*
* @param {string} tagUid - The unique identifier of the RFID tag to be removed.
* @throws {Error} If the tag is not found or a database error occurs.
*/
async removeRfidTag(tagUid) {
try {
logger.info(`Database operation: Attempting to remove RFID tag with UID '${tagUid}'.`)
const tags = await prisma.validTag.findMany();
const tagToDelete = tags.find(async t => await argon2.verify(t.tag, tagUid));
if (tagToDelete) {
await prisma.validTag.delete({
where: {id: tagToDelete.id} // Assuming 'id' is the primary key of the tag record
});
} else {
throw new Error('RFID tag not found');
}
} catch (err) {
logger.error(`Database operation error: Failed to remove RFID tag with UID '${tagUid}'. Error: ${err.message}`);
throw err;
}
}
/**
* Adds a new user to the database after hashing their password.
*
* @param {string} username - The username for the new user.
* @param {string} password - The password for the new user.
* @returns {Promise<Object>} The newly created user record.
* @throws {Error} If the username already exists or a database error occurs.
*/
async addUser(username, password) {
try {
logger.info(`Database operation: Attempting to add a new user '${username}'.`)
const existingUser = await prisma.user.findUnique({
where: {username}
});
if (existingUser) {
throw new Error('Username already exists');
}
const hashedPassword = await argon2.hash(password);
const newUser = await prisma.user.create({
data: {username, password: hashedPassword}
});
return newUser;
} catch (err) {
logger.error(`Database operation error: Failed to add user '${username}'. Error: ${err.message}`);
throw err;
}
}
/**
* Counts the number of users in the database.
*
* @returns {Promise<number>} The count of users in the database.
* @throws {Error} If a database error occurs.
*/
async getUserCount() {
try {
logger.info(`Database operation: Retrieving count of users in the database.`)
const count = await prisma.user.count();
return count;
} catch (err) {
logger.error(`Database operation error: Failed to retrieve user count. Error: ${err.message}`);
throw err;
}
}
/**
* Retrieves an RFID tag from the database based on its UID.
*
* @param {string} tagUid - The unique identifier of the RFID tag.
* @returns {Promise<Object|null>} The RFID tag record if found, otherwise null.
* @throws {Error} If a database error occurs.
*/
async getTag(tagUid) {
try {
logger.info(`Database operation: Attempting to retrieve RFID tag with UID '${tagUid}'.`)
const hashedTag = await argon2.hash(tagUid);
const tags = await prisma.validTag.findMany();
const tag = tags.find(t => argon2.verify(t.tag, hashedTag));
return tag;
} catch (err) {
logger.error(`Database operation error: Failed to retrieve RFID tag with UID '${tagUid}'. Error: ${err.message}`);
throw err;
}
}
/**
* Finds a user by their username.
*
* @param {string} username - The username of the user to find.
* @returns {Promise<Object|null>} The user record if found, otherwise null.
* @throws {Error} If a database error occurs.
*/
async findUserByUsername(username) {
try {
logger.info(`Database operation: Attempting to find user by username '${username}'.`)
const user = await prisma.user.findUnique({
where: {username}
});
return user;
} catch (err) {
logger.error(`Database operation error: Failed to find user '${username}'. Error: ${err.message}`);
throw err;
}
}
/**
* Verifies if the provided password matches the stored hash for a given user.
*
* @param {string} username - The username of the user.
* @param {string} password - The password to verify.
* @returns {Promise<boolean>} True if the password matches, otherwise false.
* @throws {Error} If a database error occurs.
*/
async verifyUserPassword(username, password) {
try {
logger.info(`Database operation: Verifying password for user '${username}'.`)
const user = await this.findUserByUsername(username);
if (user && await argon2.verify(user.password, password)) {
return true;
}
return false;
} catch (err) {
logger.error(`Database operation error: Password verification failed for user '${username}'. Error: ${err.message}`);
throw err;
}
}
/**
* Finds a user by their ID.
*
* @param {number} id - The ID of the user to find.
* @returns {Promise<Object|null>} The user record if found, otherwise null.
* @throws {Error} If a database error occurs.
*/
async findUserById(id) {
try {
logger.info(`Database operation: Attempting to find user by ID '${id}'.`)
const user = await prisma.user.findUnique({
where: {id}
});
return user;
} catch (err) {
logger.error(`Database operation error: Failed to find user with ID '${id}'. Error: ${err.message}`);
throw err;
}
}
/**
* Removes a user from the database by their username.
*
* @param {string} username - The username of the user to remove.
* @throws {Error} If the user is not found or a database error occurs.
*/
async removeUser(username) {
try {
logger.info(`Database operation: Attempting to remove user '${username}'.`)
const user = await prisma.user.findUnique({
where: {username}
});
if (!user) {
throw new Error('User not found');
}
await prisma.user.delete({
where: {id: user.id}
});
logger.info(`Database operation error: User ${username} removed successfully`);
} catch (err) {
logger.error(`Database operation error: Failed to remove user '${username}'. Error: ${err.message}`);
throw err;
}
}
/**
* Retrieves all users from the database.
*
* @returns {Promise<Array>} A list of user records.
* @throws {Error} If a database error occurs.
*/
async getUsers() {
try {
logger.info(`Database operation: Querying database for list of users.`);
const users = await prisma.user.findMany({
select: {
username: true,
createdAt: true,
}
});
// Format 'createdAt' for each user
const formattedUsers = users.map(user => {
return {
...user,
createdAt: this.formatDate(user.createdAt)
};
});
logger.info("Users retrieved:", formattedUsers);
return formattedUsers;
} catch (err) {
logger.error(`Database operation error: Failed to query users from database. Error: ${err.message}`, err);
throw err;
}
}
/**
* Formats a date to a more human-readable string.
*
* @param {Date} date - The date object to format.
* @returns {string} A formatted date string.
*/
formatDate(date) {
return date.toLocaleString('en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
}
/**
* Retrieves all RFID tags from the database.
*
* @returns {Promise<Array>} A list of RFID tag records.
* @throws {Error} If a database error occurs.
*/
async getRfidTags() {
try {
logger.info(`Database operation: Querying database for list of RFID tags.`);
const tags = await prisma.validTag.findMany();
return tags;
} catch (err) {
logger.error(`Database operation error: Failed to query RFID tags from database. Error: ${err.message}`, err);
throw err;
}
}
/**
* Retrieves all RFID log entries from the database.
*
* @returns {Promise<Array>} A list of RFID log entry records.
* @throws {Error} If a database error occurs.
*/
async getRfidLogEntries() {
try {
logger.info(`Database operation: Querying database for RFID log entries.`);
const logEntries = await prisma.rfidLog.findMany({
orderBy: {
timestamp: 'desc', // Assuming you might want to order by timestamp descending
},
select: {
id: true,
rfidId: true,
timestamp: true,
}
});
// Format the timestamp for each log entry
const formattedLogEntries = logEntries.map(entry => {
return {
...entry,
timestamp: this.formatDate(entry.timestamp),
rfidId: entry.rfidId.toString(), // Convert the BigInt to a string
};
});
return formattedLogEntries;
} catch (err) {
logger.error(`Database operation error: Failed to query RFID log entries from database. Error: ${err.message}`, err);
throw err;
}
}
/**
* Retrieves all log entries from the database.
*
* @returns {Promise<Array>} A list of log entry records.
* @throws {Error} If a database error occurs.
*/
async getLogEntries() {
try {
logger.info(`Database operation: Querying database for log entries.`);
const logEntries = await prisma.logEntry.findMany({
orderBy: {
timestamp: 'desc',
},
select: {
id: true,
level: true,
message: true,
timestamp: true,
}
});
// Format the timestamp for each log entry and rename it to 'date'
const formattedLogEntries = logEntries.map(entry => {
return {
id: entry.id,
level: entry.level,
message: entry.message,
date: this.formatDate(entry.timestamp) // Renaming 'timestamp' to 'date'
};
});
return formattedLogEntries;
} catch (err) {
logger.error(`Database operation error: Failed to query log entries from database. Error: ${err.message}`, err);
throw err;
}
}
async disconnect() {
await prisma.$disconnect();
}
}
module.exports = Database;