I am currently developing a middleware that verifies the validity of a session (meaning it has a logged-in user attached). For this purpose, I am utilizing sqlite3 for node.js.
Since I am not very familiar with JavaScript, I am facing some challenges figuring out the appropriate approach. Initially, I attempted to use 'await' in my query to ensure that it waits for completion before returning a result. However, all I received in the console was 'Promise { undefined }'.
The code snippet provided below executes the query and aims to return true or false based on certain conditions. Although I have included return statements in the callback functions, I am uncertain if they will function as intended. The DBManager function returns a functional database object.
// assuming there is an existing session ID
// establish a connection to the database
let db = dbManager();
// check the database to see if the session corresponds to a logged-in user
let checkSessionSql = 'SELECT timelastactive timelastactive, sessionid id FROM session WHERE sessionid = ?';
db.get(checkSessionSql, [session.uniqueSessionID], (err, row) => {
if (err) {
return console.error(err.message);
}
// if a row is found, it indicates a logged-in user
if (row) {
// verify if the user's last activity was more than 48 hours ago
if ((Math.round(new Date() / 1000)) - row.timelastactive > 172800) {
// invalidate the user's session if inactive for over 48 hours
console.log('session older than 48 hours');
session.destroy();
return false;
} else {
// update the timelastactive to the current time since the session is valid
let updateTimeLastActiveSql = 'UPDATE session SET timelastactive = ? WHERE sessionid = ?';
let currentTime = Math.round(new Date() / 1000);
db.run(updateTimeLastActiveSql, [currentTime, row.id], function (err) {
return console.error(err);
});
console.log('updated last active time for session ' + row.id);
return true;
}
}
});
db.close(); // close the database connection