Using Passport.js with a custom callback function that accepts parameters

I currently have this block of code:

app.post('/login', passport.authenticate('local', {
        failureRedirect: '/login',
        failureFlash: true
    }), function(req, res) {
        return res.redirect('/profile/' + req.user.username);
    });

The successful login functionality is working as expected. However, in cases where the login fails, the redirection is done via a GET request to /login. To handle this scenario, additional code like below needs to be implemented:

app.get('/login', ...);

In order to populate the username back into the form when there is a failed POST redirecting to the GET, I need to send the username that caused the failure. This way, the username field doesn't get cleared every time someone unsuccessfully tries to log in due to an incorrect username.

Is there a way to achieve this?

UPDATE: Here is how I set up my strategy.


passport.use(User.createStrategy());


User.js


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

var User = new Schema({
    username: String,
    firstName: String,
    lastName: String,
    dateOfBirth: Date,
    email: String,
    mobileNumber: Number,
    favouriteWebsite: String,
    favouriteColour: String
});

User.methods.getFullName = function() {
    return this.firstName + " " + this.lastName;
}
User.methods.getAge = function() {
    return ~~((Date.now() - new Date(this.dateOfBirth)) / (31557600000));
}

User.plugin(passportLocalMongoose, {
    usernameQueryFields: ["username", "email"], // TODO not working
    errorMessages: {
        IncorrectPasswordError: "Incorrect password!",
        IncorrectUsernameError: "Username does not exist!"
    }
});

module.exports = mongoose.model("User", User);

Answer №1

One approach is to directly invoke passport.authenticate with (req, res, next), providing a callback function to determine the success of the process.

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err || !user) {
      // handle failed authentication
    } else {
      // handle successful authentication
    }
  })(req, res, next);
});

It's important to consider handling err and !user (user === false) separately. An err indicates internal errors, while false for user means the user doesn't exist. The strategy implementation plays a role in how this is managed.

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

Retrieve all records from a table using Prisma client

I need to retrieve all data from a table using Prisma. How can I achieve this? (SELECT * FROM application) const applications = prisma.application.findMany({ // Retrieves all fields for the user include: { posts: { ...

Using QuerySelector with Angular Directive will throw an error as it is not a recognized

When creating a directive that integrates a jQuery carousel, I want to hide it at the beginning until it is fully ready. Here's the directive code snippet: return { restrict: 'E', replace: true, scope: true, templateUrl: ...

How can I retrieve the user id of the current logged-in user in Odoo and Node.js?

I am looking to fetch the user-id of the currently logged in user. To achieve this, I am utilizing the odoo-xmlrpc node package to establish a connection between my express application and an Odoo instance. odoo.execute_kw("res.users", "search_read", para ...

The IntroJs step is only partially visible on the screen

Currently, I am incorporating introJS into my application and encountering an issue where one of the steps is only partially visible on the screen. Despite trying various position settings such as auto, left, right, etc., this particular item consistentl ...

Tips for keeping data on a page up-to-date using Node.js and Express

Currently delving into the world of Node.js and Express, I am immersed in a project that involves pinging websites and exhibiting the results on a web page. Leveraging HoganJS for templating as well. My primary focus is to decipher the steps necessary to m ...

Express strangely appends a forward slash to the end of the URL

While working on my website using Node.js and the Express framework, I encountered an unusual issue with a URL. Whenever I click on a link related to the images section, the URL changes to "localhost:3000/images/" with an extra slash added at the end. Ho ...

Failed to cast value "undefined" to ObjectId in the "_id" path for the model "User"

I've been encountering an issue that I can't seem to resolve despite searching on Stack and Google. My ProfileScreen.js is meant to display a user's profile, but when attempting to view the profile, I receive this error: "Cast to ObjectId fa ...

Error code 403 has been reported by Stripe's payment_init.php as a forbidden request

Having some trouble incorporating a Stripe payment method into my web application. I've hit a roadblock: payment_init.php isn't loading when I'm redirected to the page. Instead, I'm greeted with a 403 Forbidden error code ("Forbidden. Y ...

Utilizing React Native to dynamically generate buttons through a loop

I am currently working on retrieving data from the Eventbrite API. The information I am hoping to extract is the event names, which will then be added to a list. Within the render function, I aim to dynamically create buttons based on the number of event ...

Is there a way to remove text from a div when the div width is reduced to 0?

Upon loading the page, my menu is initially set to a width of 0px. When an icon is clicked, a jQuery script smoothly animates the menu's width to fill the entire viewport, displaying all menu items (links) perfectly. The issue I'm facing is that ...

Display JSON values in sequence using Material-UI animations

I have received an array of JSON data from the API that looks like this: "fruits": [ { "id": "1", "fruit": "APPLE", }, { "id": "2", "fruit": ...

Have you ever wondered why the expression `Number(new Boolean(false))` always returns `0

In the case of Boolean(new Boolean(...)) === true, it is because new Boolean(...) is treated as an object. However, why does Number(new Boolean(false)) === 0 (+new Boolean(false) === 0) and Number(new Boolean(true)) === 1? Instead of resulting in NaN. Wh ...

Oops! Looks like there was an issue with setting headers after they have already been sent to the client. Let's work together to solve this

Hey there, I'm encountering an issue with Node.js and Express.js while trying to register a user in the database for our pizza ordering app. Here is the problem: node:internal/errors:464 ErrorCaptureStackTrace(err); ^ Error [ERR_HTTP_HEADERS ...

Automatically generated list items are failing to react to the active class

I am facing an issue with two divs in my project. The first div uses the Bootstrap class list-group and is populated with a basic example provided by Bootstrap. The second div is supposed to be populated with list-group-items obtained from an AJAX GET requ ...

Resolving a CSS Layout Dilemma: How to Overlay Sidebar on Wrappers

I've run into a challenge while attempting to position a sidebar over page wrappers. The issue with absolute positioning arises when the sidebar needs to align with the corner of the blue header. I have contemplated using JavaScript to maintain its cu ...

Merge the content of a single file with the contents of several other files using Gulp

I'm still getting the hang of Gulp, so I hope this question isn't too basic. My project is pretty complex with multiple files, and thanks to Gulp's magic, I can combine, minify, babel, and more. I've been using Grunt for a long time, so ...

Encountered a 'SyntaxError: await is only valid in async function' error while trying to utilize the top-level await feature in Node v14.14.0

I'm excited to use the new top-level await feature that was introduced in Node version 14.8. For more information, you can check out this link and here. I did a thorough search but couldn't find any questions related to issues with the new featur ...

Executing processes individually within AngularJS

Just making sure I understand correctly, I have a simple web service resource query function set up like this //Get country lists $scope.getCountry = function(){ $http({ method : 'GET', url : cdnLinks('country&apos ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

Explain the contrast between specifying a function name in the onclick react event versus invoking it using a callback

Can someone explain the distinction between these two React statements? <Button onClick={this.Callme}></Button> <Button onClick={()=>this.Callme()}></Button> Is it merely a syntax difference or is there an impact on functional ...