Getting a boolean response from an asynchronous SQLite query in Express

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

Answer №1

implement promise function and use .then or async/await for execution.

let db = dbManager();

// Query the database to check if there is an active session for this browser session id
let checkSessionSql = 'SELECT timelastactive timelastactive, sessionid id FROM session WHERE sessionid = ?';

function verifySession(params) {
    return new Promise((resolve, reject) => {

        db.get(checkSessionSql, [session.uniqueSessionID], (err, row) => {
            if (err) {
                console.error(err.message);
                return reject(err);
            }

            // If a row is found, it indicates that the user is logged in
            if (row) {
                // Check if the user was last active more than 48 hours ago
                if ((Math.round(new Date() / 1000)) - row.timelastactive > 172800) {
                    // Invalidate the session if inactive for over 48 hours
                    console.log('session older than 48 hours');
                    session.destroy();
                    return resolve(false);
                } else {
                    // Update the last active time to current time as session is still 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 resolve(true);
                }
            }
        });
    });
}

verifySession().then((result) => {
    console.log(result)
})

Answer №2

It's possible that the issue occurred because you included the async keyword in a callback function. To resolve this, you could consider removing the async keyword.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to retrieving the second value variable in an array based on the selected dropdown option within a controller

In my controller, I am trying to extract the second value in an array list that a user selects from a dropdown so that I can perform mathematical operations on it. $scope.dropdown = [ {name:'Name', value:'123'}] When a user chooses "N ...

change the return value to NaN instead of a number

Hey there, I have something similar to this: var abc1 = 1846; var abc2 = 1649; var abc3 = 174; var abc4 = 27; if(message.toLowerCase() == ('!xyz')) { client.say(channel, `abc1` +`(${+ abc1.toLocaleString()})` +` | abc2 `+`(${+ abc2.toLocaleStri ...

A guide to iterating over an array and displaying individual elements in Vue

In my application, there is a small form where users can add a date with multiple start and end times which are then stored in an array. This process can be repeated as many times as needed. Here is how the array structure looks: datesFinal: {meetingName: ...

Can you please explain the correct method for iterating over an array within an EJS template following an AJAX request (using ExpressJS)?

Currently, I am working on looping through an array of objects retrieved from an http call to my internal API using the request module. At this point, I have successfully obtained the data and displayed the entire object on my webpage. My goal now is to ut ...

What is the best way to ensure that navigation takes up the full width of the screen in pixels when

Trying to use jQuery to set a specific pixel width for my Bootstrap navbar that spans the entire width of the browser window. However, encountering some bugs as the width needs to be recalculated whenever the browser is resized. Currently, I have this cod ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...

AngularJS tree grid component with customizable cell templates

I have been utilizing the tree-grid component in AngularJS from this link: Here is an example of it on Plunker: http://plnkr.co/edit/CQwY0sNh3jcLLc0vMP5D?p=preview In comparison to ng-grid, I am unable to define cellTemplate, but I do require the abilit ...

Having trouble retrieving the desired data from the JSON file

My current code is not giving me the expected results while trying to access JSON values with jQuery. Any suggestions on how I can resolve this issue? // JSON response: [{ "private": "8044553.0" }, { "governmentdocs": "98952.0" }, { "officiald ...

What is causing the issue with Firebase not functioning on my Node.js server?

After reviewing the code below, I encountered an issue: var email = req.body.correo; var pass = req.body.pass; var firebase = require("firebase-admin"); var serviceAccount = require("./prueba-064cb79dba28.json"); firebase.initializeApp({ credential: fire ...

Tips for verifying the "truthiness" of an object, removing any falsy values, and making changes to the object

I am faced with the task of examining each property of an object to determine if it is truthy, and then removing any that are not. var user = { name: 'my name', email: null, pwHash: 'U+Ldlngx2BYQk', birthday: undefined, username: &ap ...

Express Router triggers XHR onreadystatechange 3

Having just started using Express, I am currently working on setting up a login authentication system. However, I have encountered an issue where XHR is not showing a ready state 4. This problem arose after implementing express.Router which I came across i ...

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

Encountering the Extjs 3.4 error ERR_UNKNOWN_URL_SCHEME while trying to access a legitimate JSON

Using Extjs 3.4, I am working on a simple ajax request: Ext.Ajax.request({ url: "localhost:3000/offers.json", success: function(response, opts) { var obj = Ext.decode(response.responseText); console.dir(obj); }, failure: funct ...

Error in content policy for CSS in Stripe Checkout

I am currently attempting to integrate Stripe Checkout into my Ionic App. I have created a Directive that injects the form into my content view, however, upon execution, the CSS fails due to a content policy violation: checkout.js:2Refused to load the s ...

Error Received While Attempting to Log in using Ajax

Having an issue with logging in using ajax and php. I am able to log in successfully, but when trying to display an alert message and refresh the page upon login, it gives me an error without refreshing. However, upon manually refreshing the page, I can se ...

Puppeteer: Locating elements using HTML attributes

I'm currently working on getting Puppeteer to locate an element on this webpage using its attribute data-form-field-value, which needs to match 244103310504090. Here is the HTML code for the button in question: <section class="fl-accordion-tab--c ...

Unusual behavior exhibited by AngularJS when working with Float32Arrays

After working with Float32Array values in AngularJS, I have noticed some unexpected behavior. During my testing, I encountered the following scenarios: angular.module("myApp", []).controller("myCtrl", function($scope) { $scope.n = 0.2; // Displays as 0 ...

Implement varying styles in React components

In my React project, I am attempting to create a unique progress bar with custom styling. Specifically, I have a dynamically calculated percentage that I want to assign as the width of a div element. Initially, I tried achieving this using Tailwind CSS: &l ...

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

Distribution of data in K6 according to percentage

Is it possible to distribute data based on percentages in K6? For instance, can you demonstrate how to do this using a .csv file? ...