Upon completion of the user registration process, the req.isAuthenticated method is showing a false

I've encountered this issue in a few of my previous apps and I'm unsure what's causing it. When I navigate to the login page and successfully log in a user, everything works as expected and I have access to the logged-in user. However, when I try to register a new user using the register route, despite calling passport.authenticate, the user is not authenticated and I end up with no user to work with. I even tried writing the register post route in callback format instead of using async/await, but that didn't make a difference. The strange part is that the users do get added to the database, so they are indeed registered.

Here is the code snippet:

router.get('/register', function(req, res) {
   res.render('register')
});

router.post('/register', async (req, res) => {
    try{
       var newUser = new User({username: req.body.username});
       await User.register(newUser, req.body.password);
       await passport.authenticate('local');
       console.log("The user is authenticated: " + req.isAuthenticated())
       res.redirect('/');
    }
    catch(err) {
        console.log(err);
        res.redirect('/');
    }
});

The console.log always returns false.

User model:

var mongoose              = require('mongoose'),
    passportLocalMongoose = require('passport-local-mongoose');

var UserSchema = new mongoose.Schema({
    username:     String,
    password: String
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', UserSchema);

Register page template:

<% include ./partials/header %>

<h1>Please Sign-Up</h1>

<form action='register' method='POST'>
    <label>Username</label>
    <input type='text' name='username'>
    <label>Password</label>
    <input type='password' name='password'>

    <button type='submit'>Submit</button>
</form>


<% include ./partials/footer %>

In my app.js file:

app.use(function(req,res,next) {
  console.log("Current user is: " + req.user)
  res.locals.currentUser = req.user;
  next();
});

Any help or insights on this matter would be greatly appreciated.

Answer №1

Primarily, the usage of passport.authenticate in this context is incorrect - this function actually provides the appropriate connect/express-compatible middleware for the specified strategy type, which in this case is local. To use it properly in your scenario, you would need to invoke it as

passport.authenticate('local')(req, res, next)
...however, it seems unlikely that this is what you intend to do.

In essence, there are three distinct operations taking place here:

  1. user registration
  2. user authentication
  3. user redirection

In my opinion, these actions should be handled by separate middlewares like so:

const registerUser = async (req, res, next) => {
  try {
    const { username, password } = req.body;
    const user = new User({ username });
    await User.register(user, password);
    return next();
  } catch (e) {
    return next(e);
  }
}

router.post('/register',
  registerUser, // register user in the DB
  passport.authenticate('local'), // authenticate user credentials
  (req, res) => res.redirect('/') // redirect user
)

To explain the flow here, upon hitting the /register route, the process begins with attempting to register the user through the registerUser middleware. Assuming successful registration, we proceed to call next to trigger the subsequent middleware, which handles the passport local strategy (the credentials remain in req.body from the initial request). Finally, if the authentication is successful, passport will execute the following middleware, leading to the desired redirection.

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

Having trouble serving static files with express.Router?

With my file system becoming more complex, I decided to switch from using app.use(express.static()) to utilizing express.Router(). Initially, I thought I could just replace app.use(express.static()) with router.use(express.static()), but unfortunately, thi ...

Verifying an array of objects in NodeJS

Here is an example of the array I am working with: settings: [ { key: 'maxImageSize', value: '512' }, { key: 'maxFileSize', value: '2048' }, { key: 'searchResultsLimit', value: '10' ...

Unraveling the process: Navigating into the Node.js application log launched with pm2

During the development of my Node.js application, I utilized Socket.IO, Express, MySql, and https. Initially, everything was functioning perfectly until I decided to "deamonize" it using pm2. Surprisingly, after this implementation, my socket connection ap ...

Which AWS service would be best suited for logging user application interaction events through Lambda; perhaps Cloudwatch could be the solution

Our team is currently working on developing an API server (using graphql, prisma, and node) that runs in a Lambda function deployed through Apex Up. We have a need to log various user events, including: Successful logins Failed login attempts User actio ...

Tips for incorporating routes in Polka.js in a way that resembles the functionality of express.Route()

One of the challenges I am facing is trying to import route logic from another file in my project. While using Express.js, this could be done easily with express.Route(). However, when attempting polka.Route(), an error occurs stating that Route doesn&apos ...

Having difficulty converting a local variable into a global variable in JavaScript and Express

I am facing challenges trying to convert a local variable into a global variable while working with Express and Javascript. Below is my JavaScript code snippet: // Setting up Express and EJS const express = require("express"); const JSON = requi ...

Is there a universal method to close all pop-up modals and cookie notifications with Puppeteer?

Is there a universal method to dismiss cookie warnings and modals when capturing a screenshot with puppeteer? ...

Having trouble installing Node JS version 8.9 or higher on Ubuntu 16.04?

I've attempted various methods to install the most recent version of nodejs on my operating system, but have been unsuccessful in doing so. Each time I try, it only installs version v.4.2.6 Whenever I use the following commands, an error pops up as ...

The Debian operating system has Nodejs installed, however npm is missing from the installation

While trying to install Nodejs v11.x on Debian by following the steps provided at https://github.com/nodesource/distributions, I encountered an issue. Even after successfully installing Nodejs, the command nodejs -v returns v4.8.2, indicating that npm has ...

I encountered an unexpected syntax error while using the npm command on my Mac: an unexpected token was found

Lately, I encountered this message while attempting to utilize npm Update available 5.3.0 → 7.11.1 │ │ Run npm i -g npm to update Consequently, I proceeded with the update, but since then, I have been facing an error whenever I try to exe ...

I encounter an issue when attempting to fetch data from multiple tables

I'm facing an issue with my query const a = await prisma.$queryRaw` SELECT r.name as name, r.profileId as profile, o.lastName as lastName FROM UserSetting r , User o WHERE r.userId=o.id ` After running the query, I am getting an error message stating ...

PHP (specifically openssl) is effective for decrypting data, whereas javascript (cryptojs) has proven to be ineffective

Decryption is functioning using php/openssl, and I can successfully retrieve my plain data. Here is the specific call that is defined: <?php function decryptString($data, $key) { return base64_decode(openssl_decrypt(base64_decode($data), "AES- ...

"The loop functionality appears to be malfunctioning within the context of a node

Below is the code snippet: for (var j in albums){ var album_images = albums[j].images var l = album_images.length for ( var i = 0; i < l; i++ ) { var image = album_images[i] Like.findOne({imageID : image._id, userIDs:user ...

Setting the port for Next.js on PM2 involves configuring the ecosystem file in the project

I am currently working on a standard next js application and have the following scripts in my package.json file. "scripts": { "dev": "next dev", "build": "next build", "start": " ...

Saving this object in Mongodb - here's how it's done

click here for imageCan you provide guidance on creating a schema and saving API data for this specific object in MongoDB? I am looking to store the information related to 'btcinr' as it will be fetched from an external API. Below is the sample ...

Socket connection issue causing Laravel Event not to display on registration

I want to display notifications for new users who have registered on my website, so that existing logged-in users can see messages like "blabla has registered...". To achieve this, I first created an Event class along with a channel setup: class UserSign ...

Is it possible to exclusively deploy the backend of my React Native app on Heroku?

I am currently developing a react native app with expo, using node.js and Express for the backend. My project structure consists of a frontend folder and a backend (server) folder within the root directory. Root | |Frontend |Various screens & assoc ...

Navigating the world of videoconferencing with the powerful combination of webrtc and

Greetings, I apologize for any language barriers in advance. I am currently attempting to set up a WebRTC video call, but unfortunately, it is not functioning as expected. For the server side, I am utilizing node.js, socket.io, and express. Any ...

Deactivate the remotebuild agent on a Mac to ensure security is not compromised

I am currently working on developing an app using Cordova on my Mac. To facilitate this process, I installed the remotebuild package via npm. After completing the installation, it was necessary to set "remotebuild --secure false" but when attempting to d ...

Sending requests from a React application to a Node.js backend hosted on an Nginx server with SSL enabled

After creating static files for a reactjs app using the create react app tool, I launched an nginx server on a docker container to serve the front end built with reactjs. This nginx server communicates with a node js in another container. Everything was r ...