I am trying to make some middleware which checks wether a session is valid (meaning has a logged in user attached). To do this I am using sqlite3 for node.
I am not too familiar with javascript, so I don't know exactly what to try. But I tried using 'await' for the query to wait for the query to complete and then return something, but that only made 'Promise { undefined }' show up in the console.
This is the code that runs the query and that I want to return true or false (those statements are already in there), I don't know if return statements work in callbacks (I think this is a callback). DBmanager returns a working database object.
// there is a session id
// open db connection
let db = dbManager();
// check the database if there is a logged in session for this browser session id
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 gets found then that means that this was a logged in user
if (row) {
// we check whether the last time this user was active was more than 48 hours ago
if ((Math.round(new Date() / 1000)) - row.timelastactive > 172800) {
// if this is the case then we invalidate this users session
console.log('session older than 48 hours');
session.destroy();
return false;
} else {
// session is still valid so we update the timelastactive to the current time
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();