Problem with utilizing Passport-Local while executing a Mongoose.save operation

I've been troubleshooting the following code snippet:

router.post('/register', function(req, res) {
      User.register(new User({ username : req.body.username }),
          req.body.password, function(err, user) {
          if (err) {
              return res.status(500).json({err: err});

        }
      if(req.body.firstname) {
        user.firstname = req.body.firstname;
      }

      if(req.body.lastname) {
        user.lastname = req.body.lastname;
      }

      user.save( function(err, user) {
        passport.authenticate('local')(req, res, function () {
          return res.status(200).json({status: 'Registration Successful!'}); 
        });
      });
  });
});

The output of this code is:

{
        "_id" : ObjectId("59a631ff29e0a506c81032b3"),
        "salt" : null,
        "hash" : null,
        "username" : "admin",
        "admin" : false,
        "lastname" : "Last",
        "firstname" : "Test",
        "__v" : 0
}

The salt and hash values are generated by the passport.authenticate('local') function. If I remove the user.save(function(err, user) {...}); code block around the passport.authenticate, it does not update the lastname or firstname fields, but the salt and hash values do get updated.

I've explored this forum, Passport (), and Passport-local github (https://github.com/jaredhanson/passport-local) for possible solutions, but haven't come across a similar issue or resolution.

If anyone has suggestions, I would greatly appreciate it.

Answer №1

After a thorough investigation, I have discovered a code snippet that effectively resolves the issue I was facing. With this snippet, the First Name, Last Name, Salt, and Hash are updated correctly.

I am still baffled as to why the original code was generating a 401 / Unauthorized error when calling passport.authenticate from within the user.save function.

 router.post('/register', function(req, res) {
    User.register(new User({
                            username : req.body.username,
                            firstname : req.body.firstname,
                            lastname : req.body.lastname,
                          }),
        req.body.password, function(err, user) {
        if (err) {
            return res.status(500).json({err: err});
        }
        passport.authenticate('local')(req, res, function () {
          return res.status(200).json({status: 'Registration Successful!'});
        });
    });
});

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

Determining if a user is already logged in from a different device using express-session

After a user logs in, I assign the username to their session with the code: req.session.username = "...."; This identifies the session with a username, but now I need to figure out how to detect if this same username is already logged in from another dev ...

Ways to prevent mouse selection in an input field without disabling or making it read-only

Imagine this scenario: <input type="text"> The task at hand is to prevent text selection within the <input> field. ...

Guide to running code repeatedly in node.js

Is there a way to repeat the console.log function 5 times in Node.js using the 'repeating' npm package? I am working on a node application that needs to run a specific code multiple times, but I can't seem to figure out how to achieve this. ...

Is there a method to redirect the entire webpage using a script within an iframe?

I am seeking a solution to redirect the entire window to another page when clicking a link inside an iframe. It is important that it redirects the entire window, not just the iframe itself. Is this even possible? I would prefer to implement this in JavaSc ...

Retrieve every HTML element that is currently visible on the screen as a result

I have a dynamic HTML table that updates frequently, with the potential for over 1000 rows. Instead of replacing the entire table each time it updates, I am exploring options to only update the visible rows. My initial approach involved iterating through ...

Guide on utilizing substring string functions in the updated version of Selenium IDE

I am facing a challenge with extracting the word "Automation" from a given string "Welcome to the Automation World" using Selenium IDE Record and Play feature. I have tried using the execute script command, but it doesn't seem to be working as expecte ...

Utilizing PHP to fetch data from a separate webpage

This is a question that has sparked my curiosity. I am not facing any particular issue that requires an immediate solution nor do I possess the knowledge on how to achieve it. I have been contemplating whether it is feasible to utilize PHP for fetching co ...

Encountering an issue while fetching information from a JSON file using JavaScript

I am encountering an Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data let mydata = JSON.parse("file.json"); console.log(myJSON) Here is a sample of the JSON file's data: [[1,1,0,1,1,0,0,0,1,1,1,1,1, ...

A guide on integrating a stacked bar chart from ApexCharts into a modal or v-dialog component

I'm facing a minor issue with vue-apexcharts while attempting to showcase some data in a stacked bar chart. Here is the simple component I have created: <template> <div v-if="this.loaded"> <apexchart w ...

Unlimited Cycle using Vue Router Global Precautionary Measures

Currently, I am facing an issue with redirecting users using Firebase Auth and Vue Router. The problem arises when the Router redirects the user to '/' as it results in a blank white screen on the website. I am aware that there is an error in m ...

jQuery DatePicker Not Displaying Calendar

I've been attempting to implement a date picker in jQuery. I've included the necessary code within the head tag: <link rel="stylesheet" type="text/css" media="screen" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jqu ...

How can you alter a property within an array of records retrieved from a Mongoose query?

const images = await tbl .find({ creator_id: req.user._id, }) .select({ creator_id: 0, }) .exec() .then((images) => images.forEach((image) => { image.file_name = process.env.IMAGE_ ...

Are certain browsers unable to play dynamically generated HTML5 audio files?

While working on my project, I encountered an issue with creating and controlling an audio element in JavaScript. The element works perfectly fine in Firefox, Chrome, and Opera; however, it fails to function properly in IE and Safari. In these browsers, ...

Prevent selection duplication in adjacent select by disabling the option in AngularJS ng-options

In my table, I have 2 select options that change dynamically. <tr> <th>Start time</th> <th>End time</th> </tr> <tr ng-repeat="s in config.time"> <td> <select ng-model="s.start_time" ...

What is the procedure for turning off hover color on an href element?

Working on a website that utilizes MUI components, I have incorporated href into the Tab elements within the navigation bar. <Tab label={element} id={index} sx={{display: {xs: 'none', md: 'inherit'}}} href={`#${navElements[element ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

transferring function from server to the client module named Next 13

After referencing the documentation for the app directory in Next.js, it is recommended to fetch data inside Server Components whenever feasible. Server Components always carry out data fetching on the server. This advice is particularly helpful for me as ...

Choose a Vue filter according to the variable selected

My Current Table Dilemma Creating a table from a 2D array in Vue2 has been successful for me, as I've managed to display all the values correctly. However, I am facing issues with formatting. The template code is structured like this: <table> ...

Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below. "City":[ { "Name":"Delhi", "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd", "Towns":[ ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...