Is the user consistently experiencing redirection to a failure page with passport?

I've been struggling with the user login redirection issue on my website. No matter what changes I make, it keeps redirecting to failure instead of success. I'm not sure if I missed something or did something wrong. The documentation for passport was confusing for me when I tried reading it. If you need to review the rest of the code, here is the link to my GitHub repository: https://github.com/gego144/to-do-list-website/tree/main

const customFields = {
    usernameField: 'email',
    passwordField: 'password'
}

const verifyCallback = (username, password, done) => {
          user_exists = userName_Checker(username), function (err, user) {
            if (err) { return done(err); }
            if (userName_Checker(username) == false) {
                console.log('wrong user');
              return done(null, false, { message: 'Incorrect username.' });
            }
            if (password_finder(username, password)) {
                console.log('wrong pass');
              return done(null, false, { message: 'Incorrect password.' });
            }
            console.log('wtf');
            return done(null, user);
          };  
      ;

}

const strategy = new LocalStrategy(customFields, verifyCallback);

passport.use(strategy);

passport.serializeUser(function(user, done) {
    done(null, user);
});


passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });
});


// function that checks if the user's email is in the database
function userName_Checker(email_name){
    
    var sql = "select * from info where email = ?";
    var user_email = [[email_name]];

    db.query(sql, [user_email],function (err,result){
        if (err) throw err;
        var not_unique = result.length;
        if(not_unique == 0){
            return false;
        }
        else{
            return true;
        }
    }
    )}


// function that checks if the password in the database matches the email
function password_finder(email_name, pass){
    var sql = "SELECT password FROM info WHERE email = ?";
    var user_email = [[email_name]];
    db.query(sql, [user_email],function (err,result){
        if (err) throw err;
        
        bcrypt.compare(result, pass, function(err, res){
            if(err){ throw err};
            if(res){
                return true;
            }
            else{
                return false;
            }
        })
    }
)}

This is the post method in my other file:

app.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect:'/index.html',
    failureFlash: true
}))

Edit 1. I also noticed that the console logs in the verify Callback function are not logging anything for some reason.

Answer №1

There may be an issue with the serialization logic in your code.

When using passport.serializeUser, you are passing the entire user object, but during deserialization, only the id is passed.

Although I am not utilizing SQL, the concept should remain similar.

Here is how the code should look:

//  Session
// Pass the user id to keep session data minimal
passport.serializeUser((id, done) => {
    done(null, id);
});

// Deserialize when necessary by querying the DB for complete user details
passport.deserializeUser(async (id, done) => {
    try {

        const user = await User_DB.findById(id);
        done(null, user);
    } catch (err) {

        console.error(`Error Deserializing User: ${id}: ${err}`);
    }

});
// Exporting the passport module
module.exports = (passport) => {

    passport.use(new LocalStrategy({ usernameField: 'email', }, async (email, password, done) => {

        try {

            // Find the user 
            const userData = await User_DB.findOne({ email: email, }, { 
            password: 1, }); 

            // If user does not exist
            if (!userData) {

                return done(null, false);
            }

            // Hash and compare passwords
            const passMatch = await bcrypt.compare(password, userData.password);

            // If passwords do not match
            if (!passMatch) {
                return done(null, false);
            }

            // Return user id on success
            return done(null, userData.id);

        } catch (err) {
            passLog.error(`Login Error: ${err}`);
        }

    }));
};

These passport options seem to encounter issues frequently or display abnormal behavior, so I recommend handling redirection logic as seen in my controller.

{ successRedirect: '/good',
 failureRedirect: '/bad' }

Login controller logic: (Omitted session storage code and made modifications, but this code should suffice)

const login = (req, res, next) => {

    //Using passport-local
    passport.authenticate('local', async (err, user) => {


        //If user object does not exist, login failed
        if (!user) { return res.redirect('/unauthorized'); }


        //Successful login
        req.logIn(user, (err) => {

            if (err) { return res.status(401).json({ msg: 'Login Error', }); }

            // Send response to frontend
            return res.redirect('/good');
        });

      
        });
    })(req, res, next);


};

The actual route:

//  Import the controller
const {login} = require('../controllers/auth');

// Implement in the route
router.post('/auth/login', login);

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

What solutions are available to resolve the routing problem in React.js?

On my fourth day working with Node and React.js, I am creating a custom offline search function for Docusaurus 2. I've built a JSON index and implemented a search function using elasticlunr. My goal is to redirect to a separate results page, but I&apo ...

Tips for ensuring that req.query only accepts date formats in the format yyyy-mm-dd

Can someone help me figure out how to restrict my req.query so that it only accepts dates in the format YYYY-MM-DD? Right now, my code is allowing random numbers like "123456" to be entered into the query. ...

Error encountered: `npm ERR! code E503`

While attempting to execute npm install on my project, which was cloned from my GitHub repository, I encountered the following error: npm ERR! code E503 npm ERR! 503 Maximum threads for service reached: fs-extra@https://registry.npmjs.org/fs-extra/-/fs-ex ...

retrieving information from the database and passing it to the controller

I'm in the process of developing a new API with Express, following the MVC architecture. However, I've been facing difficulties getting the data to successfully return from the database access file to the controllers file. Initially, I attempted ...

Does npm-check-updates have the ability to lock specific dependencies during the execution of ncu -ua command?

Utilizing npm-check-updates, we are managing updates for our dependencies listed in the package.json. We are encountering challenges due to having numerous small projects that require fixed versions of specific dependencies. As a module writer, we prefer ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Forwarding the geographic coordinates directly to the system's database

I have a unique script that retrieves the precise latitude and longitude position. It then automatically sends this data to a database without the need for user input. <script> function getPosition(position) { var latitude = position.coor ...

Getting a URL path in Next.js without relying on the Link component when the basePath is configured

Base Path from the next.js documentation states: For instance, by setting basePath to /docs, /about will automatically transform into /docs/about. export default function HomePage() { return ( <> <Link href="/about"> ...

Express not receiving data from HTML form submission

Check out my HTML form below: <form method="post" id="registration-form" action="/register"> <div class="form-group"> <label for="UsernameRegistration">Username:</label> <input type="text" class="form- ...

Deliver feedback from NodeJS Server to JavaScript on the client side

I have set up an HTTP server in NodeJS by utilizing the http.createServer(...) method. In my client-side JavaScript file, I sent a query using the POST method to the localhost URL. The server effectively received the data from the client, but now I am enco ...

Why won't the infowindow close when I press the close button in the markercluster of Google Maps API v3?

initialize map function initializeMap() { var cluster = []; infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map"), { cen ...

How can I convert a string to an integer in Node.js/JavaScript in terms of cardinality?

Imagine a scenario where a user can input any string such as "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. The goal is to assign an integer value to each of these strings: "1st" -> 0 "2nd" -> 1 "third" -> 2 "fourth" -> 3 "fifth" -&g ...

What is the method for accessing an anonymous function within a JavaScript Object?

Currently facing an issue with a Node.js package called Telegraf, which is a bot framework. The problem arises when trying to create typings for it in TypeScript. The package exports the following: module.exports = Object.assign(Telegraf, { Composer, ...

The only thing you can see in MongoDB output is the objectid

Trying to save data in mongodb using an open schema. After making a post request, the only thing showing up in the database is the objectid. As someone new to MongoDB and Node.js, I'm struggling to identify where my mistake lies. // <---------se ...

The Yarn Start Command encountered a hiccup and exited with error code 1

Recently, I created a React app using create-react-app and installed react-admin. However, when I attempted to start the development server with yarn start, an error occurred that was unhandled and stated "Command failed with exit code 1." Even after con ...

Troubleshooting problem with cookies in express-session

I've been working on an app with express.js and vue 3, incorporating session-based authentication. While everything functions perfectly locally, I've encountered issues when trying to deploy to production. Here's a snippet of the code where ...

The system was unable to locate node.js with socket.io

I'm having trouble locating the file. According to the documentation I reviewed, socket.io is supposed to be automatically exposed. Encountered Error: polling-xhr.js?bd56:264 GET http://localhost:8081/socket.io/?EIO=3&transport=polling&t=LyY ...

Ways to utilize Pub / Sub Notifications for Cloud Storage

In order to utilize Pub/Sub Notifications for Cloud Storage, I am working with storage files on Firebase and need to perform various processes. These processes result in additional data being stored in different fields on Firebase. However, there are insta ...

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

What is the process for adding pictures and information to a MySQL database through PHP?

I'm encountering an issue when trying to save data to the database. My connection details and SQL insert query are correct, and the image is successfully uploading to the folder. However, I can't figure out why the data, along with the image, isn ...