An issue occurred while trying to use the next() method with passport.authenticate('local') function

My current middleware setup involves the use of passport.js for user authentication before moving on to the next middleware:

exports.authenticate = (req, res, next) => {
  passport.authenticate('local', (err, user, info) => {
    console.log('You are authenticated!!')
    next()
  })(req, res, next)
}

Upon registering a new user, the message You are authenticated!! is logged in the console. Since this indicates successful authentication, I expected the user data to be attached to the req. Therefore, I proceeded to call next, transitioning to the following middleware where I intended to perform other tasks before redirection:

exports.createMatch = async (req, res) => {
  console.log(req.user._id)
}

However, an error displaying

TypeError: Cannot read property '_id' of undefined
appears on both my console and webpage. What could be causing this issue and how can it be resolved?

Here's a snippet from routes.js illustrating the middleware configuration:

router.post(
  '/register',
  userController.validateRegistration, // validate registration
  userController.register, // save user to database
  authController.authenticate, // authenticate user
  catchErrors(dataController.createMatch) // additional operations before redirection
)

I am relatively new to Express, so if more code snippets would be helpful please let me know. Apologies if a similar question has been answered elsewhere.

Thank you, James.

Answer №1

In the source code, this is where the variable req.user is defined:

https://github.com/jaredhanson/passport/blob/821a474342b1ae900849911b5c3d3ccc4ef5ab86/lib/http/request.js#L44

This assignment takes place within the method called req.login. For more information, you can refer to the documentation located here:

The documentation specifies:

After the login process is completed, the value of user will be stored in req.user.

Additionally:

The passport.authenticate() middleware automatically triggers req.login().

Everything seems to be functioning correctly based on this information...

However, if you look into the section regarding a Custom Callback, which is what you are implementing, it mentions:

If a custom callback is used, the application is responsible for creating a session (by calling req.login()) and sending a response.

There are multiple solutions available. You could eliminate the custom callback, incorporate the login function inside the callback, or manually set req.user = 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

Error encountered during Next.js project build: Entry point specified for implicit type library 'build'

While working on my nextjs project, I encountered the following error: Type error: Cannot find type definition file for 'build'. The file is in the program because: Entry point for implicit type library 'build' Can someone guide ...

Stop working to $(this) in jquery when clicking outside

I'm facing an issue with my code and would like some help. I have a button that toggles the visibility of a filter element, which is working fine. However, I now want to implement a "click outside" effect to close the filter when clicking on any body ...

Issue with scrolling feature in div

I am currently facing an issue with scrolling on my website. Visit this site to see the problem. When scrolling down, it causes the "hidden" part of the site to slide up. I want to achieve a similar sliding effect, but it needs to be smooth. I have attempt ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

Changing the route variable in React Native's bottom bar tab functionality

https://i.sstatic.net/ESGur.png I am looking to create a consistent bottom tab bar that remains the same on every screen, but I want the routes of the tabs at the bottom to change dynamically. For example, in Screen1, the tab at the bottom should route to ...

The program is designed to only allow up to two images to be wrapped

I'm struggling with a short jQuery program that I need help with. The problem is, I can't seem to get it to wrap more than two images in the same row. My goal is to create a website that side-scrolls, and I thought this approach would be the simp ...

Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp. Let's delve into async functions in Typescript. Which implementation is accurate? async function asyncFunctionOne(string1: string, string2: string, string3: string) { var returnOb ...

When a child component sends props to the parent's useState in React, it may result in the return value being undefined

Is there a way to avoid getting 'undefined' when trying to pass props from a child component to the parent component's useState value? Child component const FilterSelect = props => { const [filterUser, setFilterUser] = useState('a ...

The error message received states: "materialize-css Uncaught TypeError: Vel is not defined as

My current setup involves webpack as the bundler/loader, and I've successfully loaded materialize css (js/css). However, when attempting to use the toast feature, an error is thrown: Uncaught TypeError: Vel is not a function The library is being inc ...

Node.js: App crashed, standing by for file changes to initiate restart

While I was in the middle of a nodejs course on Udemy, I encountered an issue where the code suddenly started breaking and throwing errors. Even after attempting to replicate the instructor's code, the problem persisted. I sought guidance from this a ...

Can you suggest a solution for fixing this error in Angular Js?

I recently started learning Angular JS and encountered some issues while trying to implement routing. Click here for the error message <!DOCTYPE html> Main <a href="#!london">City 1</a> <a href="#!paris">City 2& ...

Choose a minimum of one validation for the list item

When I have a form in JSP that includes a drop-down view with multiple options, I want to ensure that at least one option is selected before the form can be submitted. If no options are selected, the form should not be able to submit. Thank you in advance ...

Performing an RxJS loop to retrieve the httpGet response, followed by executing httpPut and httpPost requests based

I am currently working on a UI form that allows users to update or add translation text. To achieve this, I need to create an rxjs statement that will perform the following tasks: Send an httpGet request to the database to retrieve translations in mult ...

Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected. Below is the service code: CreateItemController = $controller('Cre ...

The jQuery Select2 Plugin for Dynamic Dropdowns with Ajax Integration

Utilizing the Select2 plugin with Ajax to connect to my employee database has been quite helpful. It allows setting up a meeting and selecting all the employees you wish to invite. Here is an example of the code: $("#requiredAttendees").select2({ ...

Using a CSS style to modify a class based on another class at the same level in the hierarchy

I am working with a jQuery carousel that is adding an 'active' class to images within a div. Within the same div, there is also a span with a 'fade' class that has a CSS style of opacity: 0. Is there a way to change the CSS style of the ...

Disabling other fields with Bootstrap DateTimePicker

I am interested in understanding how the Bootstrap DateTimePicker stores dates. I need to disable other text box fields on my webpage based on this information. I have set up a page with multiple GridViews for querying purposes and I want to prevent users ...

When attempting to execute "nodemon," the command was not detected

When trying to use 'nodemon' in the command line, an error occurs stating that it is not recognized as a cmdlet, function, script file, or operable program. The system suggests checking the spelling of the name and verifying that the path is corr ...

Providing data in response to a completed form submission

As a beginner, I'm attempting to accomplish the following task: a user selects options from three dropdown menus within a form, and the chosen values are then sent to another file for processing. action="process.php" method="post" In the processing ...