The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue?

What could be causing this error to occur?

Concerning Passport.js

const LocalStrategy = require('passport').Strategy

const mongoose = require('mongoose')

const bcrypt = require('bcrypt')

const User = require('../models/User')

module.exports = function(passport) {

    passport.use("local",

        new LocalStrategy({usernameField:"email"}, (email, password, done)=>{

            User.findOne({email:email})

                .then(user=>{

                    if(!user){

                        return done(null, false,{message:"That email is not registered"})
                    }

                    bcrypt.compare(password, user.password, (err, isMatch)=>{

                        if(err) throw err

                        if(isMatch){

                            return done(null, user)

                        }else {

                            return done (null, false,{message:"password incorrect"})

                        }
                    })
                })

                .catch(err=>console.log(err))

        })
    )

    passport.serializeUser(function (user, done) {

        done(null, user.id)

    })

    passport.deserializeUser(function (id, done) {

        User.findById(id, function (err, user) {

            done(err, user)
        })
    })
}

Login.js

const express = require('express');

const passport = require("passport");

const router = express.Router();

/* GET users listing. */

router.get('/login', function (req, res, next) {

    res.render('login')

})



router.post('/login', function(req, res, next) {

    passport.authenticate('local', function(err, user, info) {

        if (err) { return next(err); }

        if (!user) { return res.redirect('/login'); }

        req.logIn(user, function(err) {

            if (err) { return next(err); }

            return res.redirect('/');

        });

    })
(req, res, next);

});



module.exports = router

app.js

const express = require('express')

const app = express()

const mongoose = require('mongoose')

const bodyParser = require('body-parser')

const logIn = require('./routes/login')

const flash = require('connect-flash')

const session = require('express-session')

const passport = require("passport");

require('./config/passport')(passport)

app.use(bodyParser.urlencoded({extended : false}))

//express session

app.use(session({

    secret:'secret',

    resave: false,

    saveUninitialized: true,

}))

app.use(passport.initialize())

app.use(passport.session())

//flash connect

app.use(flash())

app.use((req, res, next)=>{

    res.locals.success_msg = req.flash('success_msg')

    res.locals.failure_msg = req.flash('error_msg')

    next()
})

app.use(logIn)

Answer №1

If you're encountering this issue, it may be due to a failure in initializing the passport strategy instance. After reviewing your code, everything seems correct. My recommendation is to try uninstalling and then reinstalling passport to see if that resolves the problem.

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

Rendering on the server with a focus on the header

Can server side rendering be limited to only <head></head> data? I am exploring options similar to next.js: export async function getServerSideProps(context) { return { props: {}, // will be passed to the page component as props } } Ba ...

Loading Disqus comments dynamically upon clicking a button within a Next.js application

After noticing a significant decrease in page performance scores due to Disqus comments embedded on Vercel Analytics, I am considering implementing a "Load comments" button instead of loading the actual comments onClick. I have been using the disqus-react ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

React - Incorporating Axios catch errors directly within form components

When a user registers, my backend checks if the email and/or username provided are already in use by another user. The response from Axios catch error is logged into the web console. I want to associate each email and username with their respective fields ...

Tips for positioning divs on top of an image with Twitter Bootstrap

I'm having an issue with displaying an image and dividing it using bootstrap div columns. The problem is that the image is overlapping the divs, making it impossible to click or attach jQuery events to it. Here is the code I am currently using: #view ...

Leveraging react-query with next-mdx-remote MDX Components?

I have been using next-mdx-remote in my next.js project. One of the components I've passed to it makes API calls using axios, which has been working well. However, I now want to switch to using react-query. When implementing this change, I encountered ...

enable jQuery timer to persist even after page refresh

code: <div class="readTiming"> <time>00:00:00</time><br/> </div> <input type="hidden" name="readTime" id="readTime"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script&g ...

What exactly does the 'cookie-parser' middleware do?

I have experience building back-end applications with express.js, utilizing both express-session and cookie-session. However, I recently came across the cookie-parser package on npm, which seems to be quite popular. This has sparked my curiosity, Can so ...

A Beginner's Guide to Duplicating Bootstrap Containers in Jade

I am working with JSON data that is being transmitted from an Express and Mongoose Stack to be displayed on the user interface created in Jade. I am wondering which Jade Construct I should use to loop through a Bootstrap Container of col-md-4 using Jade s ...

Displaying information on a chartJS by connecting to an API using axios in VueJS

Struggling with inputting data into a ChartJS line-chart instance. The chart only displays one point with the right data but an incorrect label (named 'label'): Check out the plot image The odd thing is, the extracted arrays appear to be accura ...

Switching Column Content with jQuery on Mobile Devices

In my design, I have a dynamic two-column layout created using Twitter Bootstrap 3. The layout switches between image-text and text-image alignment for each row. The goal is to adjust it for smaller screens (less than 768px) so that rows with images on th ...

Navigating the Promise Flow in NodeJS: Tips for Regulating Execution

I am trying to gain a better understanding of nodeJS by using the following code to execute CMD operations one by one. However, I have noticed that due to the event loop, it gets executed in random variations. Here is my code: const exec = require('c ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

Clicking outside of a focused div does not trigger a jQuery function

Check out this HTML snippet: $html .= " <td><div class='edit_course' data-id='{$id}' data-type='_title' contenteditable='true'>{$obj->title}</div></td>"; Next, see the jQuery code below: ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

Insert a picture within the text input field

I'm facing a specific scenario where I need to add text followed by an image, then more text followed by another image and so on. Please see the input text with values in the image below. Can someone guide me on how to accomplish this with jQuery and ...

Troubleshooting: jQuery $.post not functioning as expected in certain circumstances

I'm currently experimenting with inserting data into a MySQL database using AJAX and jQuery's $.post method. To test this functionality, I have created the following setup: In my index.html file (which already includes jQuery for various other f ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

MERN Stack Application Error: Unable to set headers after they have already been sent to the client

Can someone help me with redirecting users after authentication based on their role using user.role? I am encountering the following error message: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to t ...