Incorporating bcryptjs alongside MongoDB

I am currently developing a feature to securely encrypt user passwords using Bcrypt for my Angular application, which is integrated with MongoDB for the backend operations.

Here is the implemented code snippet:

Data Model

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
bcrypt = require('bcryptjs'),
    SALT_WORK_FACTOR = 10;

var UserSchema = new mongoose.Schema({
  name: String,
  username: { type: String, required: true, index: { unique: true } },
  email: String,
  password:  { type: String, required: true },
  created_at: Date,
  topics: [{type: Schema.Types.ObjectId, ref: 'Topic'}],
  posts: [{type: Schema.Types.ObjectId, ref: 'Post'}],
  comments: [{type: Schema.Types.ObjectId, ref: 'Comment'}]
});


UserSchema.pre('save', function(next) {
    var user = this;

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        // hash the password along with our new salt
        bcrypt.hash(user.password, salt, function(err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            user.password = hash;
            next();
        });
    });
});

UserSchema.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};

mongoose.model('User', UserSchema);

Create & Login inside Controller

var mongoose = require('mongoose');
var User = mongoose.model('User');

module.exports = (function() {
 return {
  login: function(req, res) {
     User.findOne({email: req.body.email}, function(err, user) {
       if(user === null) {
          var error = "User not found"
          console.log(error);
       }
       else{
        user.comparePassword(req.body.password, function(err, isMatch){
          if(err){
            console.log("Password doesn't match");
          } else{
              console.log(user)
              res.json(user);
            }
        })
       }
     })
  },
   create: function(req, res) {
  var user = new User({name: req.body.name, username:req.body.username, email:req.body.email, password:req.body.password, created_at: req.body.created_at});
  user.save(function(err) {
    if(err) {
      console.log('something went wrong');
    } else { 
      console.log('successfully added a user!');
      res.redirect('/');
    }
  })
  }
})();

The user creation process works smoothly and encrypts passwords properly. However, there seems to be an issue during user login where the encrypted password comparison does not function correctly, allowing access regardless of the inputted password.

Moreover, I would like guidance on displaying error messages for scenarios such as user not found and incorrect password matching (this is a secondary query).

My primary concern remains the acceptance of incorrect passwords. Any assistance you can provide would be greatly appreciated.

Thank you for your support.

Answer №1

Ensure that you are not only verifying if there is an error during password comparison, but also confirming if the input password matches the hashed one.

user.checkPassword(req.body.password, function(err, isMatch){
    if(err){
        return console.log("Passwords do not match");
    } 

    if (isMatch) {
        // Passwords match. Proceed with user authentication
    }
});

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

Child object in Three.js does not inherit transformation from its parent

Consider a scenario where there is a main object with multiple child objects in a given scene. Update: Here is the code snippet for creating a mesh (assuming the scene and camera are already set up). Code snippet for creating the parent group: var geome ...

What is the best method to update numerous low-resolution image sources with higher resolution images once they have finished loading?

I'm currently developing a website that implements a strategy of loading low-resolution images first, and then swapping them for high-resolution versions once they are fully loaded. By doing this, we aim to speed up the initial loading time by display ...

multiple executions of mouseup() within a mousedown() event

$("#canvas").on("mousedown", function(e){ var X1 = (e.pageX - this.offsetLeft) - 8; var Y1 = (e.pageY - this.offsetTop) - 8; $("#canvas").on("mouseup",function(e){ var X2 = (e.pageX - this.offsetLeft) - 8; var Y2 = (e.p ...

How can I transfer information from jQuery.ajax() to an angular controller?

In my javascript file script.js, I have a jQuery function named getData(a, b): function getData(a, b) { var d = []; while (a <= b) { $.ajax({ url: "someurl", dataType: 'json', success: function (data) { ...

JavaScript - utilize regular expressions to check if the argument starts with a forward slash

Currently, I am utilizing nodejs for API testing purposes. To properly test the logic within this if statement, I am in search of a string that aligns with this specific regular expression. if (arg.match(/^\/.*/)) { // ... } Would anyone be able ...

Why do I keep receiving undefined errors from my commands?

Why is this code not being recognized? It's confusing me because it should be working, or has something changed in node/discord that I am unaware of? When I use my command -balance -clear 10, it gives different undefined parts like: -balance - TypeEr ...

Utilizing Jquery to Pass an Optional Function to Another Function

I am currently working on a function that utilizes AJAX to submit data and then displays a dialog indicating whether the process was successful or not. Everything seems to be functioning smoothly, but I now want to add the capability of passing an addition ...

I'm looking for the location of Angular Materials' CSS directives. Where can I find them?

Currently, I am using components from https://material.angularjs.org/latest/ for a searcher project. One specific component I am working with is the md-datepicker, and I would like to implement some custom styles on it such as changing the background colo ...

In Express JS, the REST API encounters an issue where req.body is not defined

I am currently working on building a REST API with Express JS. When I use console.log(req.body), it is returning undefined as the output. Below is the code snippet from my routes.js file: const express = require('express'); const router = expres ...

JavaScript-powered dynamic dropdown form

I need help creating a dynamic drop-down form using JavaScript. The idea is to allow users to select the type of question they want to ask and then provide the necessary information based on their selection. For example, if they choose "Multiple Choice", t ...

Ways to show a corresponding number beneath every image that is generated dynamically

I have a requirement to show a specific image multiple times based on user input. I have achieved this functionality successfully. However, I now need to display a number below each image. For example, if the user enters '4', there should be 4 im ...

The FireBase dispatch functionality fails to update the real-time database

Struggling with a realtimeDB issue while using NuxtJS to manage state and send it to the DB. Saving data works fine, but editing results in a 400 BAD Request error. This error also occurs when trying to manually update information within Firebase realtime ...

What is the best way to restrict user input to only numbers (including decimal points) in a text field?

How can a textbox be restricted to only accept valid numbers? For instance, allowing users to enter “1.25” but preventing inputs like “1.a” or “1..”. Users should not be able to type the next character that would result in an invalid number. ...

MongoDB only sending back a single data item through the API endpoint

I encountered an issue with my endpoint - the objectId was not JSON serializable, so I had to remove it. How can I retrieve all records from my mongoDB? from flask import Flask, jsonify, request from flask_pymongo import PyMongo from pymongo import Mong ...

How can I access the marker's on-screen location in react-native-maps?

Looking to create a unique custom tooltip with a semi-transparent background that can overlay a map. The process involves drawing the MapView first, then upon pressing a marker on top of the MapView, an overlay with a background color of "#00000033" is dra ...

Issues with button hover causing background transition difficulties

I've been trying to achieve a smooth background image transition upon hovering over my buttons. Despite searching for solutions in various posts, I haven't been successful in applying any of them to my code. I realize that J Query is the way to ...

NextJS is throwing an error stating that the function file.endsWith is not recognized as a valid

After upgrading from nextJS version 9.x.x to 12.x.x, I encountered the following error. Any assistance would be greatly appreciated. TypeError: file.endsWith is not a function at eval (webpack-internal:///./node_modules/next/dist/pages/_document.js ...

Definitions that are displayed dynamically when hovering over a particular element

I am seeking a way to implement popup definitions that appear when a div is hovered over. My website showcases detailed camera specifications, and I want users to see a brief definition when they hover over the megapixel class called '.mp'. One o ...

Attaching Picture From Array To Vue

Is it possible for me to request assistance? I'm wondering how to bind an image to a vue component or more simply, how do you render an image from an array in vue? Allow me to share my code with you and explain in detail how I have approached this. W ...

Utilizing ajax for fetching a data table

I am new to using ajax and have successfully retrieved data from a table. However, I am now trying to pull in an entire data grid but not sure how to achieve this. In my index.php file, I have the following code: <html> <head><title>Aj ...