Passport.js code encountered an issue stating: "authenticate must be overridden by subclass."

I have established the local strategy within the config/passport.js file. Here is the snippet of code for the strategy:

passport.use('local', new localStrategy({
    userNameField: 'email',
    passwordFiled: 'password',
    passReqToCallback: true
}, function(req, email, password, done){
    console.log("\n\n\n\nInside passport.js")
    User.findOne({'email':email}, function(err, user){
        if(err){
            return done(null, false);
        }
        if(user){
            return done(null, false, {message:"Email is already in use"});
        }

        var newUser = new User();
        newUser.email = email;
        newUser.password = newUser.encryptPassword(password);
        newUser.save(function(err, result){
            if(err){
                return done(err);
            }
            return done(null, newUser);
        });

    });
}));

The register route in routes/users.js utilizes this strategy. Here is the route:

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

router.post('/register', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/register',
    failureFlash: true
}));

Below is the HTML view for the registration page:

<div class="row">   
    <div class="col-md-4 col-md-offset-4">   
        <h1>Sign Up</h1>
        <br><br><br>
        <form action="/users/register" method="post">
            <div class="form-group">
                <label for="EmailAddress">Email Address</label>
                <input class="form-control" type="text" aria-describedby="emailHelp" name="email" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d0cdd4d8c5d9d0f5d2d8d4dcd99bd6dad8">[email protected]</a>">
                <small id="emailHelp" class="form-text text-muted">We will never share your email with anyone else</small>
            </div>
            <div class="form-group">
                <label for="Password">Password</label>
                <input class="form-control" type="password" aria-describedby="passwordHelp" name="password" placeholder="{{{hello}}}">
                <small id="passwordHelp" class="form-text text-muted"></small>
            </div>
            <button type="submit" class="btn btn-primary"> Sign Up </button>
        </form>
    </div>
</div>

When accessing the route localhost:3000/users/register, the following error occurs:

Error: Strategy#authenticate must be overridden by subclass
    at Strategy.authenticate (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\passport-strategy\lib\strategy.js:21:9)
    at attempt (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\passport\lib\middleware\authenticate.js:361:16)
    at authenticate (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\passport\lib\middleware\authenticate.js:362:7)
    at Layer.handle [as handle_request] (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Muhammad Hassam\Documents\Visual Studio 2017\Projects\Shopping Cart\Shopping Cart\node_modules\express\lib\router\index.js:335:12)

I have searched for a solution but could not find any relevant information regarding this specific error.

Answer №1

When utilizing the documentation, it is recommended to encapsulate your passport.authenticate within a function that includes the req and res arguments.

Consider implementing the following code snippet:

router.post('/register', ( req, res, next ) => {
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/register',
        failureFlash: true
    } )( req, res, next );
} );

Answer №2

Encountering the same issue when attempting to:

import {Strategy as LocalStrategy} from 'passport'

, however, utilizing

var LocalStrategy   = require('passport-local').Strategy

or

const LocalStrategy   = require('passport-local').Strategy

resolves the problem effectively.

Simply,

1): should I change the line of code with import to a line with const or var?

or

2): create an instance of LocalStrategy (I haven't tested it yet, but it might work as well)?

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

Previewing an uploaded image before submitting with FileBase64: A step-by-step guide

How can I implement a preview for an uploaded image before submitting the form? I have the upload functionality working but I would like to add a preview feature for the image. Below is the code snippet I am currently using: const [shop, setShop] = us ...

Creating Articles with Express.js and Body-parser

app.post("/article/submit", function(req, res) { let newPost = new Article(); newPost.title = req.body.title; newPost.author = req.body.author; newPost.content = req.body.content; newPost.save(function(error) { if (error) { console.log ...

Awaiting the completion of multiple asynchronous function executions

I am currently working on a promise function that executes an async function multiple times in a loop for different data. I would like to ensure that all async functions are completed before resolving the promise or calling a callback function within a non ...

JavaScript - array of dates, constructing links

I need help figuring out how to make the eventName a clickable link instead of just text. If I add a link directly in the code, it shows up as plain text. Is there a simple trick or do I need to create a new function for this? Any advice would be greatly ...

Exploring the isolate scope within a compiled directive

I successfully managed to compile a directive using this piece of code: let element, $injector, $compile, link, scope; element = angular.element(document.getElementById(#whatever)); $injector = element.injector(); $compile = $injector.get('$compile& ...

Unable to access an element using jquery

This is an example of an HTML file: <div id ="main"> </div> Here is the JavaScript code: //creating a new div element var divElem = $('<div class="divText"></div>'); //creating an input element inside the div var i ...

What's preventing me from changing module.exports? Why is my browser suddenly giving me errors after `npm run build` ran smoothly?

How come the browser is preventing me from executing the following code: Getters.js let Getters = {} Getters.foo = function(){ return 1; } Getters.bar = function(){ return 2; } module.exports = Getters; However, after running npm run build and serve -s ...

When iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...

Joomla website experiencing issues with Bootstrap popover functionality

Just wanted to share that I am currently working on this page: I found an example that inspired me from here: I have a feeling that Joomla might be including a resource that is causing conflicts with the popover not showing. This is the code snippet I h ...

Pressing the tab key makes all placeholders vanish

case 'input': echo '<div class="col-md-3"> <div class="placeholder"> <img src="images/person.png" /> &l ...

What steps are involved in uploading data to serve as a filter while running a PHP script to retrieve data from an SQL database?

Currently, I am retrieving data from a PHP file using miniAjax. The code snippet below demonstrates how the process begins: microAjax("genjsonphp.php", function(data) { var json = JSON.parse(data); var points = json; //code continues In the c ...

How to upload a document to Alfresco using JavaScript API

I am facing an issue while attempting to upload a file from a node application to my local Alfresco server. I have been able to login, create, and delete folders successfully, but I am encountering difficulties when trying to upload files. let AlfrescoApi ...

JavaScript - filter out values not included in specified list of attributes

I am seeking a technique that, when provided with a list of attributes, retains only the values associated with keys present in the list. For instance: attrs = ['a', 'b', 'c'] obj = {'a': 1, 'b': 2, &apos ...

Establishing baked goods in protractor

Attempting to create a cookie in a protractor testing scenario. Using Protractor 3.3.0, Angular 1.5.x, and Node.js 6.9.1 Here is the specified test: (function() { 'use strict'; describe('Dummytest', function() { befor ...

Angular, ui-router enabling "dynamic" URL binding without the need for refreshing the page

I have a unique query and I'm curious about the possibility of achieving it. My goal is to dynamically update the URL as users interact with the app. For example, when they click on different elements on the page, I want the URL to reflect the param ...

js - displaying function results in an HTML table

I have developed a tool that can display the repayment schedule over the loan term. I have successfully calculated the monthly payment, interest, and remaining loan amount, but I am facing difficulty in presenting this data in a table format. I aim to hav ...

Expanding the functionality of Jquery with extend or bind techniques

Can someone clarify whether I should be using .bind() or .extend() and provide guidance on how to implement it? I am working with two checkboxes where a process is triggered once they are checked. In addition, there is a button that, when clicked, will ch ...

Managing numerous callbacks for a specific route within Express.js

After going through the Express.js documentation, I came across a section discussing how to handle callbacks for routes using the syntax: app.get(path, callback [, callback ...]) However, I encountered difficulty in finding an example that demonstrates ...

Node.js nightmare conditions

In my express application, I have two main layers. The first layer consists of modules with functions responsible for handling database queries, filesystem operations, and similar tasks. The second layer is in charge of handling requests, also referred to ...

Utilizing Angular and the Kendo UI framework to customize the dimensions of a Kendo window

Is there a way to dynamically set the height and width of the kendo window based on the content of the kendo grid? Below is the code snippet for my kendo-window: <div kendo-window="Operation.OperCustWind" k-width="800" k-height="700" ...