Signing in using Passport.js with mongoDB authentication

Apologies if this question appears redundant, but I am struggling to resolve an issue with a "MISSING CREDENTIALS" error when trying to implement user login using email and password. Despite going through numerous responses, none have provided a solution.

Route File

const express = require('express');
const router = express.Router();
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');

passport.use(new LocalStrategy((email, password, done) => {
  User.getUserByEmail(email, (err, user) => {
    if(err) throw err;
    if(!user) {
      return done(null, false, {message: 'this account does not exist'});
    }

    User.comparePassword(password, user.password, (err, isMatch) => {
      if(err) throw err;
      if(isMatch) {
        return done(null, user);
      }
      else {
        return done(null, false, {message: 'oops! wrong password! try again'});
      }
    });
  });
}));

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.getUserById(id, (err, user) => {
    done(err, user);
  });
});

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

module.exports = router;

User.js file

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');

const UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    trim: true
  },
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  password: {
    type: String,
    required: true,
    trim: true
  },
  profilePhoto: {
    originalemail: String,
    imagePath: String
  },
  token: String
});

const User = module.exports = mongoose.model('User', UserSchema);

module.exports.registerUser = function(newUser, callback) {
  bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password, salt, (err, hash) => {
      if(err) {
        console.log(err);
      }
      newUser.password = hash;
      newUser.save(callback);
    });
  });
};

module.exports.getUserByEmail = function(email, callback) {
  const query = {
    email: email
  };
  User.findOne(query, callback);
};

module.exports.getUserById = function(id, callback) {
  User.findById(id, callback);
};

module.exports.comparePassword = function(candidatePassword, hash, callback) {
  bcrypt.compare( candidatePassword, hash, (err, isMatch) => {
    if(err) throw err;
    callback(null, isMatch);
  });
};

I have initialized passport in my app.js file along with session options. Additionally, here is the HTML handlebars code for the form:

<form method="post" action="/signInPage">
   <label for="mail"> Email </label>
   <input type="email" id="mail" name="email" />
   <label for="password"> Password</label>
   <input type="password" id="password" name="password"/>

  <button type="submit">Sign in</button>
  <p class="corp"> <a href="forgot.html">Forgot password?</a> </p>
</form>

Your assistance on resolving this issue would be greatly appreciated. I have been stuck debugging for some time now and cannot seem to pinpoint where I may have gone wrong. Kindly let me know if there are any formatting errors in my query that need to be addressed.

Answer №1

Grateful to someone who shared the solution link as I couldn't find the comment.

By default, Passport js logs in users with their usernames.

passport.use(new LocalStrategy((username, password, done) => {

}));

I tried using email instead of username.

passport.use(new LocalStrategy((email, password, done) => {

}));

To log a user in with email, I had to modify it like this:

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

This will change the default login from username to email.

Here is the solution link:

https://github.com/scotch-io/easy-node-authentication/blob/master/config/passport.js#L58

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

Issues with synchronizing Firebase and Node.js?

https://i.stack.imgur.com/3fwRO.png Here is the code snippet I used in my Node.js application: for(var v in sna.val()){ console.log("each "+va); console.log(v); var fourthRef = ref.child(val+'/reservation/&apos ...

AngularJS Error: The method serviceName.functionName() is not a valid function

I am trying to implement a function that will go back when the cancel button is clicked. Here is the view code: <div ng-controller="goodCtrl"> <button class="btn" ng-click="cancel()">Cancel</button> </div> And here is the Jav ...

JS unable to insert new row in table

I checked the input value before submitting it in the form and confirmed that it is correct, returning as a string.enter image description here const saveList = () => { const inputListNameText = inputListName.value; fetch('/api/lists' ...

What is the best method for accessing a value in IndexedDB while utilizing service workers?

I am feeling overwhelmed by the concepts of IndexedDB and serviceworkers as I try to transform them into a functional application. Despite my extensive research, including studying various examples, I am struggling to integrate the two technologies effecti ...

Managing Actions in React-Redux: Understanding the Dispatch Function

While I am delving into the world of React, I stumbled upon an example that looks like this: //index.js const store = createStore(reducer) render( <Provider store={store}> <AddTodo /> </Provider>, document.getElementById(' ...

How can I immediately disable a button upon clicking "cancel" on a modal that contains TextFields in React Version 18?

New to React development. Looking for a way to reset a button to its initial disabled state when canceling out of a modal. The scenario is that upon clicking a button, a dialog will appear with an "ADJUST" button that is initially disabled until text is ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

Preventing data duplication when refreshing a webpage using Node.js

I am currently utilizing Mustache and Nodejs to populate a dropdown menu with a list of options on my website. However, every time the page is refreshed, I encounter duplicate entries in the dropdown. How can this issue be resolved? I trust that my inquiry ...

Having trouble getting a basic file upload to work in Angular2+? Wondering what the easiest method is to make it function properly? Look no

I successfully created a MEAN stack CRUD board using Angular 2+, Node.js, Express, and MongoDB. However, I encountered an issue when trying to add an upload function. The error message displayed was: compiler.js:486 Uncaught Error: Template parse errors: ...

Sending Email Form in PHP using JQuery and Ajax for seamless user experience

Looking to create an email form in HTML with PHP, but running into the issue of the page reloading after submitting? Many people turn to jQuery and AJAX to solve this problem. While you may have come across solutions on Stack Overflow, as a non-native Engl ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Maximizing Efficiency of Vendor Bundle in Angular 2 with Webpack

My MEAN application's client side is built in Angular2 with Webpack, but I'm facing slow loading times due to a large vendor modules JS file. Is there a way to optimize this situation? I want to separate the vendor's JS file. Below is my we ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

Exploring the power of jQuery's deferred method and utilizing the ajax beforeSend

Using the deferred object in $.ajax allows for: Replacing the success-callback with the deferred-method done() Replacing the error-callback with the deferred-method fail() And replacing the complete-callback with always() When using: var jqxhr = $.ajax ...

"Step-by-step guide on assigning a class to a Component that has been

When attempting to pass a component as a prop of another component, it functions correctly. However, when I try to pass a Component and manage its CSS classes within the children, I find myself stuck. I am envisioning something like this: import Navbar fr ...

Need some assistance with Javascript Ajax? Specifically, dealing with multiple values?

My goal is to asynchronously post an array of messages using this code. Despite my efforts, I've encountered a challenge where it doesn't only post the four items in the array but also adds gibberish text. Additionally, there seems to be an issue ...

What is the proper way to retrieve the Nuxt context within the fetch() hook?

Is there a way to access the props within an async fetch() function when also using async fetch(context)? I'm trying to figure out how to work with both simultaneously. ...

Alter a prototype method belonging to another module

If I wanted to create a custom plugin or module that alters the behavior of an object exported in another module, how can I go about modifying one of its methods? The code below illustrates my attempt at achieving this, but it seems like there may be a cru ...

Is there a way to determine if a value exists within an array of objects?

Is it possible to determine if a specific value is present in an array of objects? I've tried a method, but it always returns false. What would be the most effective way to solve this issue? My approach: var dog_database = [ {"dog_name": "Joey" ...

What is the best way to access files stored in GridFs? The gfs.files.find() method is not functioning properly and just keeps

I am currently facing an issue where I need to display all the files stored, so my goal is to retrieve them as arrays first in order to map them on the frontend. I attempted to address this problem by watching a tutorial at https://www.youtube.com/watch?v ...