Socket
Socket
Sign inDemoInstall

@queue-it/connector-javascript

Package Overview
Dependencies
1
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @queue-it/connector-javascript

Connector to integrate Queue-it into a javascript based server side application.


Version published
Weekly downloads
72
increased by71.43%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

connector-javascript

Before getting started please read the documentation to get acquainted with server-side connectors.

The connector was developed with TypeScript and verified using Nodejs v.8.12 and Express v.4.16.

You can find the latest released version here. or download latest npm package from here.

Implementation

The connector validation must be done on all requests except requests for static and cached pages, resources like images, css files and .... So, if you add the connector validation logic to a central place, then be sure that the Triggers only fire on page requests (including ajax requests) and not on e.g. image.

The following is an example route in express/nodejs which shows how to validate that a user has been through the queue. It assumes that your integration configuration file is located in root of the web application.

const QUEUEIT_FAILED_HEADERNAME = "x-queueit-failed";
const QUEUEIT_CONNECTOR_EXECUTED_HEADER_NAME = 'x-queueit-connector';
const QUEUEIT_CONNECTOR_NAME = "nodejs";
const QueueIT_Settings =  {
  QUEUEIT_CUSTOMER_ID: "",
  QUEUEIT_SECRET_KEY: "",
  QUEUEIT_API_KEY: "",  
  QUEUEIT_ENQT_ENABLED: true,
  QUEUEIT_ENQT_VALIDITY_TIME:  4 * 60 * 1000,
  QUEUEIT_ENQT_KEY_ENABLED: false 
};

var express = require('express');
var router = express.Router();
var fs = require('fs');

var QueueItConnector = require('@queue-it/connector-javascript');

function isIgnored(req){
  return req.method == 'HEAD' || req.method == 'OPTIONS'
}

/* GET home page. */
router.get('/', function (req, res, next) {
  try {
    res.header(QUEUEIT_CONNECTOR_EXECUTED_HEADER_NAME, QUEUEIT_CONNECTOR_NAME);
    if(isIgnored(req)){
      // Render page
      res.render('index', {
        node_version: process.version,
        express_version: require('express/package').version
      });
      return;
    }
    var integrationsConfigString = fs.readFileSync('integrationconfiguration.json', 'utf8');

    var customerId = QueueIT_Settings.QUEUEIT_CUSTOMER_ID; 
    var secretKey = QueueIT_Settings.QUEUEIT_SECRET_KEY; 
    var enqueueTokenValidityTime = QueueIT_Settings.QUEUEIT_ENQT_VALIDITY_TIME; 
    var enqueueTokenEnabled = QueueIT_Settings.QUEUEIT_ENQT_ENABLED;
    var enqueueTokenKeyEnabled = QueueIT_Settings.QUEUEIT_ENQT_KEY_ENABLED; 
    var settings = { customerId, secretKey, enqueueTokenEnabled, enqueueTokenValidityTime, enqueueTokenKeyEnabled };
    
    var contextProvider = initializeExpressContextProvider(req, res, settings);
    
    var connector = QueueITConnector.KnownUser;
    var queueitToken = req.query[connector.QueueITTokenKey];
    var requestUrl = contextProvider.getHttpRequest().getAbsoluteUri();
    var requestUrlWithoutToken = getRequestUrlWithoutToken(requestUrl);
    // The requestUrlWithoutToken is used to match Triggers and as the Target url (where to return the users to).
    // It is therefor important that this is exactly the url of the users browsers. So, if your webserver is
    // behind e.g. a load balancer that modifies the host name or port, reformat requestUrlWithoutToken before proceeding.

    var validationResult = connector.validateRequestByIntegrationConfig(
      requestUrlWithoutToken, queueitToken, integrationsConfigString,
      customerId, secretKey, contextProvider);

	if (validationResult.doRedirect()) {
      // Adding no cache headers to prevent browsers to cache requests
      res.set({
        'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
        'Pragma': 'no-cache',
        'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT'
      });

      if (validationResult.isAjaxResult) {
        // In case of ajax call send the user to the queue by sending a custom queue-it header and redirecting user to queue from javascript
	const headerName = validationResult.getAjaxQueueRedirectHeaderKey();
        res.set(headerName, validationResult.getAjaxRedirectUrl());
	res.set('Access-Control-Expose-Headers', headerName);
	
        // Render page
        res.render('index', {
          node_version: process.version,
          express_version: require('express/package').version
        });
      }
      else {
        // Send the user to the queue - either because hash was missing or because is was invalid
        res.redirect(validationResult.redirectUrl);
      }
    }
    else {      
	  // Request can continue - we remove queueittoken form querystring parameter to avoid sharing of user specific token
      if (requestUrl !== requestUrlWithoutToken && validationResult.actionType === "Queue") {
        res.redirect(requestUrlWithoutToken);
      }
      else {
        // Render page
        res.render('index', {
          node_version: process.version,
          express_version: require('express/package').version
        });
      }
    }
  }
  catch (e) {
    // There was an error validating the request
    // Use your own logging framework to log the error
    // This was a configuration error, so we let the user continue
    console.log("ERROR:" + e);
    res.header(QUEUEIT_FAILED_HEADERNAME, 'true');
  }
});

function getRequestUrlWithoutToken(requestUrl){
  try {
    const url = new URL(requestUrl);
    const params = new URLSearchParams(url.search);

    params.delete(QueueITConnector.KnownUser.QueueITTokenKey);
    url.search = params.toString();

    return url.toString();
  } catch (e) {
    console.error('[Queue IT] Could not remove token in URL', e);
    return requestUrl;
  }
}

module.exports = router;

Code to initialize a contextProvider in Express (requires node module 'cookie-parser'):


function initializeExpressContextProvider(req, res, settings) {
    return {
        getCryptoProvider: function() {
            // Code to configure hashing in the Connector (requires node module 'crypto'):
            return {
                getSha256Hash: function(secretKey, plaintext) {
                  const crypto = require('crypto');
                  const hash = crypto.createHmac('sha256', secretKey)
                    .update(plaintext) 
                    .digest('hex');
                  return hash;
                }
            };
        },
        getEnqueueTokenProvider: function(){
          if(!settings.enqueueTokenEnabled){
            return null;
          }
            return initializeEnqueueTokenProvider(req, settings); 
        },
        getHttpRequest: function () {
            var httpRequest = {
                getUserAgent: function () {
                    return this.getHeader("user-agent");
                },
                getHeader: function (headerName) {

                    if(headerName === 'x-queueit-clientip')
                        return this.getUserHostAddress();

                    var headerValue = req.header(headerName);

                    if (!headerValue)
                        return "";

                    return headerValue;
                },
                getAbsoluteUri: function () {
                    return req.protocol + '://' + req.get('host') + req.originalUrl;
                },
                getUserHostAddress: function () {
                    return req.ip;
                },
                getCookieValue: function (cookieKey) {
                    // This requires 'cookie-parser' node module (installed/used from app.js)
                    return req.cookies[cookieKey];
                }
            };
            return httpRequest;
        },
        getHttpResponse: function () {
            var httpResponse = {
                setCookie: function (cookieName, cookieValue, domain, expiration, isCookieHttpOnly, isCookieSecure) {
                    if (domain === "")
                        domain = null;

                    // expiration is in secs, but Date needs it in milisecs
                    const expirationDate = new Date(expiration * 1000);

                    // This requires 'cookie-parser' node module (installed/used from app.js)
                    res.cookie(
                        cookieName,
                        cookieValue,
                        {
                            expires: expirationDate,
                            path: "/",
                            domain: domain,
                            secure: isCookieSecure,
                            httpOnly: isCookieHttpOnly
                        });
                }
            };
            return httpResponse;
        }
    };
}

Code to initialize a EnqueueTokenProvider in Express

const {Token, Payload} = require("@queue-it/queue-token");

function initializeEnqueueTokenProvider(req, settings){
       let enqueueTokenProvider =  new QueueITConnector.DefaultEnqueueTokenProvider(
        settings.customerId, 
        settings.secretKey, 
        settings.enqueueTokenValidityTime, 
        req.ip,
        settings.enqueueTokenKeyEnabled,
        Token,
        Payload);
    
    // If you need to send custom data then use following code.

    // enqueueTokenProvider.getEnqueueTokenCustomData = function(waitingRoomId){
    //     return [{"key": "", "value" : ""}];
    // };

    // If you need to use some specific key in the enqueue toke then you can use the following code.

    // enqueueTokenProvider.getEnqueueTokenKey = function(waitingRoomId){
    //     if (!settings.enqueueTokenKeyEnabled)
    //     {
    //         return null;
    //     }        
    //     return generateUUID()
    // };
    return enqueueTokenProvider;    
}

QueueIT variables

VariableRequiredValue
QUEUEIT_CUSTOMER_IDYesFind your Customer ID in the GO Queue-it Platform.
QUEUEIT_SECRET_KEYYesYour 72 char secret key as specified in Go Queue-it self-service platform.
QUEUEIT_ENQT_ENABLEDNoDefault: true If you do not need to add the enqueue token then set the value to false.
QUEUEIT_ENQT_VALIDITY_TIMENoRecommandation: 240000 ms or > 30000 ms
QUEUEIT_ENQT_KEY_ENABLEDNoDefault: false If you need to include custom key in the enqueue token then set value to true.

Implementation using inline queue configuration

Specify the configuration in code without using the Trigger/Action paradigm. In this case it is important only to queue-up page requests and not requests for resources or AJAX calls. This can be done by adding custom filtering logic before caling the connector.resolveQueueRequestByLocalConfig() method.

The following is an example (using Express/Nodejs) of how to specify the configuration in code:

const QUEUEIT_FAILED_HEADERNAME = "x-queueit-failed";
const QUEUEIT_CONNECTOR_EXECUTED_HEADER_NAME = 'x-queueit-connector';
const QUEUEIT_CONNECTOR_NAME = "nodejs"

var express = require('express');
var router = express.Router();
var fs = require('fs');

var QueueITConnector = require('@queue-it/connector-javascript');

function isIgnored(req){
  return req.method == 'HEAD' || req.method == 'OPTIONS'
}

/* GET home page. */
router.get('/', function (req, res, next) {
  try {
    res.header(QUEUEIT_CONNECTOR_EXECUTED_HEADER_NAME, QUEUEIT_CONNECTOR_NAME);
    if(isIgnored(req)){
      // Render page
      res.render('index', {
        node_version: process.version,
        express_version: require('express/package').version
      });
      return;
    }
    
    var integrationsConfigString = fs.readFileSync('integrationconfiguration.json', 'utf8');

    var customerId = QueueIT_Settings.QUEUEIT_CUSTOMER_ID; 
    var secretKey = QueueIT_Settings.QUEUEIT_SECRET_KEY; 
    var enqueueTokenValidityTime = QueueIT_Settings.QUEUEIT_ENQT_VALIDITY_TIME; 
    var enqueueTokenEnabled = QueueIT_Settings.QUEUEIT_ENQT_ENABLED;
    var enqueueTokenKeyEnabled = QueueIT_Settings.QUEUEIT_ENQT_KEY_ENABLED; 
    var settings = { customerId, secretKey, enqueueTokenEnabled, enqueueTokenValidityTime, enqueueTokenKeyEnabled };

    var queueConfig = new QueueITConnector.QueueEventConfig();
    queueConfig.eventId = "" // ID of the queue to use
    queueConfig.queueDomain = "xxx.queue-it.net" // Domain name of the queue
    // queueConfig.cookieDomain = ".my-shop.com" // Optional - Domain name where the Queue-it session cookie should be saved
    queueConfig.cookieValidityMinute = 15 // Validity of the Queue-it session cookie should be positive number.
    queueConfig.extendCookieValidity = true //Should the Queue-it session cookie validity time be extended each time the validation runs?
    // queueConfig.culture = "da-DK" // Optional - Culture of the queue layout in the format specified here: https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx. If unspecified then settings from Event will be used.
    // queueConfig.layoutName = "NameOfYourCustomLayout" // Optional - Name of the queue layout. If unspecified then settings from Event will be used.
   
    var contextProvider = initializeExpressContextProvider(req, res,settings);

    var connector = QueueITConnector.KnownUser;
    var queueitToken = req.query[connector.QueueITTokenKey];
    var requestUrl = contextProvider.getHttpRequest().getAbsoluteUri();
    var requestUrlWithoutToken = getRequestUrlWithoutToken(requestUrl);
    // The requestUrlWithoutToken is used to match Triggers and as the Target url (where to return the users to).
    // It is therefor important that this is exactly the url of the users browsers. So, if your webserver is
    // behind e.g. a load balancer that modifies the host name or port, reformat requestUrlWithoutToken before proceeding.

    var validationResult = connector.resolveQueueRequestByLocalConfig(
		requestUrlWithoutToken, queueitToken, queueConfig, 
		customerId, secretKey, contextProvider);
	  
    if (validationResult.doRedirect()) {
      // Adding no cache headers to prevent browsers to cache requests
      res.set({
        'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
        'Pragma': 'no-cache',
        'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT'
      });

      if (validationResult.isAjaxResult) {
        // In case of ajax call send the user to the queue by sending a custom queue-it header and redirecting user to queue from javascript
	const headerName = validationResult.getAjaxQueueRedirectHeaderKey();
        res.set(headerName, validationResult.getAjaxRedirectUrl());
	res.set('Access-Control-Expose-Headers', headerName);

        // Render page
        res.render('index', {
          node_version: process.version,
          express_version: require('express/package').version
        });
      }
      else {
        // Send the user to the queue - either because hash was missing or because is was invalid
        res.redirect(validationResult.redirectUrl);
      }      
    }
    else {      
	  // Request can continue - we remove queueittoken form querystring parameter to avoid sharing of user specific token
      if (requestUrl !== requestUrlWithoutToken && validationResult.actionType === "Queue") {
        res.redirect(requestUrlWithoutToken);
      }
      else {
        // Render page
        res.render('index', {
          node_version: process.version,
          express_version: require('express/package').version
        });
      }
    }
  }
  catch (e) {
    // There was an error validating the request
    // Use your own logging framework to log the error
    // This was a configuration error, so we let the user continue
    console.log("ERROR:" + e);
    res.header(QUEUEIT_FAILED_HEADERNAME, 'true');
  }
});

function getRequestUrlWithoutToken(requestUrl){
  try {
    const url = new URL(requestUrl);
    const params = new URLSearchParams(url.search);

    params.delete(QueueITConnector.KnownUser.QueueITTokenKey);
    url.search = params.toString();

    return url.toString();
  } catch (e) {
    console.error('[Queue IT] Could not remove token in URL', e);
    return requestUrl;
  }
}

module.exports = router;

EnqueueToken

An enqueue token can be used for allowing access to waiting room(s). Any user without it can't join the queue. The token will be included when the user is redirected from the connector to the queue. QueueToken package has been used to generate this token. The generated token will be valid for 4 minute.

Follow the steps below to enable use of enqueue token:

  • The waiting room should be configured to require token to enter it. Use Queue-it Go platform or API to setup your waiting room.
  • Add a variable with name QUEUEIT_ENQT_ENABLED in settings as mentioned in the example code and value 'true'.

Request body trigger (advanced)

The connector supports triggering on request body content. An example could be a POST call with specific item ID where you want end-users to queue up for. For this to work, you will need to contact Queue-it support or enable request body triggers in your integration settings in your GO Queue-it platform account. Once enabled you will need to update your integration so request body is available for the connector.
You may need to add the following middleware in your express app:

const bodyParser = require('body-parser');

// ... in your app setup

app.use(bodyParser.text());

And then add this to the httpRequest object in your http context provider:

getRequestBodyAsString: function () {
  if(!req.body || !req.body.toString){
    return "";
  }
  return JSON.stringify(req.body.toString());
}

FAQs

Last updated on 14 Sep 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc