NodeJS: Implement session refresh mechanism following permission changes made by other users

Utilizing express-session in my NodeJS application for managing sessions, express-mysql-session to store session data in MariaDB, Passport for authentication, and Sequelize for ORM.

Encountering an issue where I am unsure how to refresh a user's session after their permissions have been modified by an admin.

Attempted using req.logIn(), but only updates the admin's session making the changes.

The relevant section of my code is:

editUser = function (req, res) {
    var userData.id = req.body.id;
    userData.access = req.body.access;
    models.User.update(userData, {where: {id: userData.id}})
        .then(function (affectedRows) {
            // User has been updated.
            // Changes should be reflected without requiring user to log out and back in
        });
}

Seeking suggestions on how to refresh the session of a user whose permissions have been altered by another user?

Answer №1

Using the express-mysql-session requires a specific table and certain fields to be configured in order to store session information.

One important field is named expires.

If you assign the current timestamp to this field using Date.now(), the user's session will expire as intended.

Update:

Upon reviewing your comment and examining their code, it appears that the data stored in the session row in the database is serialized JSON.

Since you can locate the user's session in the database, you have the ability to:

  • Retrieve the session's data,
  • Parse it using JSON.parse(),
  • Modify the .roles array (which stores the user's role),
  • Stringify it with JSON.stringify(), and then save it back to the database.

Answer №2

After much searching, I finally found a solution to my issue in this helpful thread PassportJS - Is it possible to change req.user for another user?

To fix the problem, I made changes to my passport.deserializeUser() function by including a database query to reload the user. The updated code now looks like this:

passport.deserializeUser(function(user, done) {
    models.User.findOne({where: {id: user.id}})
        .then(function(updatedUser) {
            done(null, updatedUser);
        }, function(err) {
            console.error(err);
            done(null, user);
        });
});

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

Adding data to MongoDB using Mongoose and Angular

Recently, I decided to explore nodejs and ventured into using mongoose for mongodb. Below is the code structure that I created, however, I seem to have made a mistake along the way. The scenario is from angular, where I am utilizing $http.post to send an o ...

Is it possible to implement sanctum on multiple Vue projects simultaneously?

Greetings! I am currently using Sanctum to authenticate users in the system. My goal is for a user who logs in to vue project num1 to also be automatically logged in to vue project num2. I attempted to implement this functionality using cookies like so: $ ...

Define the post route methods effectively

I encountered a routing error while working on an application using express.js with node. Despite my best efforts, I am unable to handle post requests properly and consistently receive an HTTP 500 error. Below is the code snippet from my server.js file: v ...

Using the database object pattern in ExpressJS for MVC architecture

tl:dr; I'm looking for guidance on how to pass the database object to my models and controllers in ExpressJS. Longer explanation: Coming from a background of working with Codeigniter's active-record implementation, I wanted to build a simple s ...

When attempting to install the reactjs app using npm, an error with code E404 was

I recently started learning reactjs and decided to create a react app. I followed the steps on the React website but encountered an error. My Node version is v8.11.1 and npx version is 9.7.1. Interestingly, I was able to create the app using npx create-re ...

Exploring the world of microservices with Express.js and docker

My journey into node.js, docker, and microservices architecture has just begun. I am diving into the depths of what microservices architecture truly entails and grasping the theoretical aspects. Below you will find the implementation I have been tinkering ...

What is the most straightforward method to convert a current Express node app into a static site?

After primarily working with React and create-react-app, I've grown accustomed to the convenience of having a build utility for npm that simplifies deploying projects to static web hosting platforms like github pages or surge. This process ultimately ...

The integration of Express server with static ejs files, CSS, and JavaScript is experiencing technical difficulties

I am currently working on a website using node.js and have created two routes: /home and /contact. Everything was functioning properly until I added CSS and JS files to both routes. For some reason, the second call does not work as expected. When I access ...

Using NPM may lead to segmentation faults

Every time I attempt to use npm in the command line on my Windows 8.1 system, I encounter segmentation faults. Despite multiple attempts at uninstalling and reinstalling node.js using various x64 msi files from the official website, the issue persists. Is ...

What is the method to disable response validation for image endpoints in Swagger API?

I'm working with a Swagger YAML function that looks like this: /acitem/image: x-swagger-router-controller: image_send get: description: Returns 'image' to the caller operationId: imageSend parameters: ...

After using promise.all, I successfully obtained an array of links. Now, how do I calculate the total number of links in the array?

function verifyAndTallyURLs(linksArray) { let validations = linksArray.map((link) =>{ return fetch(link) .then((response) => { return { webpageURL: response.url, status: response.status, ...

Exploring the Benefits of Using Gatsby with Material-UI: The Importance of Creating a Page

Upon reviewing the gatsby demo showcased on the material-ui project github page, I found myself puzzled by a few lines of code. In the specific file getPageContext.js export default function getPageContext() { // Ensuring each server-side request has i ...

Eliminate any line breaks from the information retrieved from the node event process.stdin.on("data") function

I've been struggling to find a solution to this issue. No matter what approach I take, I can't seem to remove the new line character at the end of my string. Take a look at my code below. I attempted using str.replace() in an effort to eliminate ...

Learn how to display MongoDB collections in your Node.js application to retrieve them as a response

In my environment on Cloude 9, I am working on developing a nodejs application. Currently, I have the code to connect to a mongodb database and successfully add records to a collection. However, I am facing an issue when trying to send the collection info ...

What is the best way to save data generated in Angular to a file using Node.js?

After researching, I have discovered the method for saving data in a file using node.js save(): void { this.modeler.saveXML((err: any, xml: any) => console.log('Result of saving XML: ', err, xml)); } } ...

What is the process for displaying all the commands that are at your disposal in package.json?

There are several commands that can be included in a package.json, such as npm start and npm test. However, there are typically many more commands available. Is there a method to display a complete list of all available commands? My current approach is u ...

Creating nested directories in Node.js

I am attempting to accomplish the following task Create a function (in any programming language) that takes one parameter (depth) to generate folders and files as described below: At depth 0, create a folder named 0, and inside it, create a file with its ...

The request.body in Express.js is currently undefined

const express = require('express'); const cors = require('cors'); const app = express(); app.use(express.json()) app.use(cors()); app.post('/', (req,res) => { console.log(req.body); res.send('received') ...

Strategies for managing multiple request keys that share the same value

In the process of this project, I am creating models and passing values from a POST request's body. My main objective is to properly define these models. Here is a JSON sample that I intend to post to MongoDB: { "signageId": "5cd857c4965f863b7c8 ...

Is it not possible to access the email verification link through a web browser?

Issue: After creating an email verification function for user registration, I encountered a problem when trying to access the link sent with a hash code. Here is an example of the link format: let link = `http://localhost:3000/api/user/verify?id=${ ...