Exploring the methods for retrieving and setting values with app.set() and app.get()

As I am granting access to pages using tools like connect-roles and loopback, a question arises regarding how I can retrieve the customer's role, read the session, and manage routes through connect-roles.

For instance, when a client logs in, I retrieve a string containing their assigned role and utilize it within a function that regulates page access.

This raises a query for me as I work on a large-scale service where multiple client sessions are often accessed simultaneously using a shared storage and check function.

Would it be efficient to store the customer's role using app.set() and app.get() functions?

  app.get('/session-details', function (req, res) {
    var AccessToken = app.models.AccessToken;
    AccessToken.findForRequest(req, {}, function (aux, accesstoken) {
      // console.log(aux, accesstoken);
      if (accesstoken == undefined) {
        res.status(401);
        res.send({
          'Error': 'Unauthorized',
          'Message': 'You need to be authenticated to access this endpoint'
        });
      } else {
        var UserModel = app.models.user;
        UserModel.findById(accesstoken.userId, function (err, user) {
          // console.log(user);
          res.status(200);
          res.json(user);
          // storing employee role
          app.set('employeeRole', user.accessLevel);
        });
      }
    });
  });

Everything seems to progress smoothly thus far; I successfully retrieve the role information linked with the client. Subsequently, I create a connect-roles function to validate this data.

var dsConfig = require('../datasources.json');
var path = require('path');

module.exports = function (app) {
  var User = app.models.user;
  var ConnectRoles = require('connect-roles');
  const employeeFunction = 'Developer';

  var user = new ConnectRoles({
    failureHandler: function (req, res, action) {
      // custom function to handle authorization failures
      var accept = req.headers.accept || '';
      res.status(403);
      if (~accept.indexOf('ejs')) {
        res.send('Access Denied - You don\'t have permission to: ' + action);
      } else {
        res.render('access-denied', {action: action});
        // here
        console.log(app.get('employeeRole'));
      }
    }
  });

  user.use('authorize access private page', function (req) {
    if (employeeFunction === 'Manager') {
      return true;
    }
  });

  app.get('/private/page', user.can('authorize access private page'), function (req, res) {
    res.render('channel-new');
  });

  app.use(user.middleware());
};

My concern lies particularly at the instance where I use

console.log(app.get('employeeRole'));
. Could there potentially be issues with concurrent connections?

  app.get('/private/page', user.can('authorize access private page'), function (req, res) {
    res.render('channel-new');
  });

Consider a scenario where clients x and y connect simultaneously and share the same function for storing session data. Would printing the string via

console.log(app.get('employeeRole'));
pose any challenges in such cases?

To address this, if my doubt is resolved and no problems arise with simultaneous connections, I plan to introduce a new variable with

var employeeFunction = app.get('employeeRole');
. This will enable my function to utilize the stored role object in
if (employeeFunction === 'Any Role')
; if the role matches the required one, the page is accessible, otherwise, the failureHandler callback is triggered.

My testing environment is currently limited to scenarios of this nature, so any guidance on this matter would be greatly appreciated!

Answer №1

Instead of using app.set, another approach is to create a session map similar to hashmaps. This method has been successfully implemented in one of my projects with great results. Here is the code snippet for reference:

hashmap.js

var hashmapSession = {};

exports.auth = auth = {
  set : function(key, value){
    hashmapSession[key] = value;
  },
  get : function(key){
    return hashmapSession[key];
  },
  delete : function(key){
    delete hashmapSession[key];
  },
  all : function(){
    return hashmapSession;
  }
};

app.js

var hashmap = require('./hashmap');
var testObj = { id : 1, name : "john doe" };

hashmap.auth.set('employeeRole', testObj);
hashmap.auth.get('employeeRole');
hashmap.auth.all();
hashmap.auth.delete('employeeRole');

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

The animations in three.js have come to a standstill

Currently, I am working on a real-time game using three.js and websockets. The project has been running smoothly until recently when I encountered a hurdle. While implementing animations, I noticed that the animations for the opposing client on the web pag ...

Utilize JavaScript to randomly choose images as background tiles in HTML

Currently, I am in the process of developing a game using HTML/CSS/JavaScript. My background is currently set to a single image (100px / 100px) being repeated vertically and horizontally to tile across the entire page body; CSS: body { background-ima ...

Using Vue 3, Bootstrap, and Pinia to create an innovative Global Modal experience

After creating a ModalComponent.vue file that I intend to use across different sections, I encountered an issue with closing the modal after calling my Pinia stores. The modal includes slots for the title, body, and footer, along with a standard close butt ...

"Implement image uploading and retrieval functionality in your application by utilizing Parse and Back4App with the help of Node

It seems like I have a question that may have already been answered, but I can't find the right solution for my issue. I'm facing trouble with my code and can't figure out what's wrong. The problem arises when I try to upload specific ...

Maximum number of days that can be selected with Bootstrap Datepicker

I currently have a datepicker set with the multidate option and I am looking to specify a maximum number of days that users can select, say 5 days. Once a user has selected 5 days, any additional days should become disabled dynamically. How can this be a ...

Using JavaScript to find the weekday of the same date next year

Struggling to determine the weekday of a particular date next year? Take for example Tuesday, April 19, 2016 as the given date. What we need to calculate is: TUESDAY, April 18, 2017. Consistency with weekdays is crucial in this scenario. The challenge lie ...

What is the best way to connect my data with my Backbone Views?

I have successfully set up my views to show test data, and now I want to implement asynchronous data loading to fetch real information. However, I'm a bit confused on the best method to achieve this. Should I manually create AJAX calls? Or maybe utili ...

Choosing2 - incorporate a style to a distinct choice

Let's talk about a select element I have: <select id="mySelect"> <option>Volvo</option> <option value="Cat" class="red">Cat</option> <option value="Dog" class="r ...

Update the text input field from a different webpage

I am working with two PHP pages, let's call them page1.php and page2.php. On page1.php, there is a textbox with a default value of 0, while on page2.php, there is a button. I have these two pages open in different tabs in a browser. My goal is to have ...

Stripe detects that no signatures match the expected payload

Currently working on setting up a checkout session using Stripe that triggers my webhook upon successful completion. The issue I am facing is an error message stating "error: No signatures found matching the expected signature for payload. Are you passing ...

Adjusting the size of all elements on a webpage

Upon completing my project, I noticed that my localhost:3000 is zoomed in at 125%, causing it to appear less than ideal at 100% zoom. Is there a way to adjust the zoom/scale of my website to match how it appeared on my localhost environment? I came across ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Differences between using "break + return" and simply "return" in

Currently, I am developing a nodejs Heap and ensuring top performance is key. The code snippet I have looks like this: while(true) if(x) do something return if(y) do ... return if(z) do ... else return Suggestions were made to me to incorporate ...

transferring information between two ajax calls upon completion of the first ajax request

Attempting to pass data to jvectormap from an ajax call, using a when function to ensure the code runs after the ajax call has finished loading. The issue I'm facing is that the map appears empty and I encounter an error. Uncaught ReferenceError: ...

Tips for monitoring multiple values in a Vue 3 script setup

Within my code, I currently have a watcher set up like this (inside <script setup>): const form = reactive({ body: '', image: '' }) watch(() => form.image, () => { console.log(form.image) }) I am looking to enh ...

Variable missing in the ExpressJs view

Hey there! I'm new to Nodejs and currently experimenting with it. I've been trying to convert some of my basic Python codes to JavaScript. In one of my projects, I am sending a get request to the YouTube API and receiving 50 results in JSON forma ...

Confirm that the array contains exactly 2 elements

Is there a way to confirm that an array contains exactly two specific values, for example: ['foo', 'bar'] After trying different approaches, the closest solution I found looks like this: Yup.array() .of(Yup.mixed().oneOf(['foo&a ...

The error encountered is due to an invalid assignment on the left-hand side

I'm encountering the error below: Uncaught ReferenceError: Invalid left-hand side in assignment This is the problematic code: if (!oPrismaticMaterial = "") { for (var i = 0; i < oPrismaticMaterial.length; i++) { if (oPrismaticMater ...

Is there any method to avoid the hassle of constantly adjusting margins and paddings on my one-page website?

One issue I encountered was that the buttons weren't scrolling me to the top of the anchor, instead scrolling too far into the section due to the fixed navbar overlapping. I tried solving it with margins and paddings but believe there must be a simpl ...

What is the process for including a static file on an http server?

Looking to create a chatroom using node.js. Utilizing the socket.io template for this project. var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var fs = require(&ap ...