Mongoose does not compare BCRYPT passwords that are empty

I'm currently working on incorporating bcrypt into my mongoose model using typescript. Referencing this link as a guide.

However, since my project is in typescript, I'm unable to directly use the provided code. I'm confused about how they're fetching the password for comparison with the user's input.

Upon comparing the passwords, one of them appears to be undefined. Here's the snippet of my code, any assistance would be greatly appreciated.

 PersonTestSchema.pre<PersonTestModel>('save', function (next) {
  const user = this;
  if (this.password && this.password.length > 4) {
    bcrypt.genSalt(10, function (err, salt) {
      bcrypt.hash(user.password, salt, (err, hash) => {
        user.password = hash;
        next();
      });
    });
  } else {
    next();
  }
});

PersonTestSchema.methods.verifyPassword = function (candidatePassword: string) {
  const user = this;
  return bcrypt.compareSync(candidatePassword, user.password);

While logging the candidate password shows its value, checking the user's password returns empty. This makes sense in my scenario, but I'm unsure where they're obtaining it from based on their example code.

Answer №1

After some investigation, I managed to solve the issue. It seems that the solution involved making adjustments to their passportConfig file and passing the password from the database through there.

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

The client continues to request the file through the REST API

I have noticed a behavior with an audio file stored on the server that clients can request via a REST API. It seems that every time the audio is played again, a new request is sent to the server for the file. Is there a way to prevent this or cache the dat ...

Crafting Functions That Can Be Typed from Factory Function

My goal is to create a generic function from a factory function that can be typed later. However, I am encountering an issue where I am required to define the return type of the factory function at the time of its definition: export type TypeFunction<T& ...

The state of dynamically created Angular components is not being preserved

My current task involves dynamically creating multiple components to be placed in a table. The code successfully achieves this objective, but the state seems to be getting jumbled up at the level of the dynamically generated components. When a component is ...

Comparison of Grant and Passport.js: Which One to Choose?

Are you unsure about the distinctions between Grant and Passport.js? How do you decide when to utilize Grant over passport.js, and vice versa? If your goal is to create a social media platform that tracks user activities and posts them on a news feed, whi ...

TypeScript equivalent to Python's method for removing non-whitespace characters is achieved by

I understand that I can utilize .trim() to eliminate trailing spaces Is there a method to trim non-space characters instead? In [1]: str = 'abc/def/ghi/' In [2]: s.strip('/') Out[2]: 'abc/def/ghi' I am referring to the funct ...

Exploring JWT Authorization with Mocha and Chai

Struggling to create a test for the get endpoint that requires an admin token to fetch a list of users. This is the user endpoint: app.get("/users", (req,res) => { const payload = req.payload if (payload && payload.user === "ad ...

Creating a 301 Redirect in NextJS on Vercel - Step by Step Guide

Is there a way to create 301 redirects from one URL to another in NextJS application hosted on Vercel? I attempted to implement custom express server using server.js file but the redirects only function locally. Upon further research, I discovered this me ...

Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend. { "components": [ { "label": "Textfield1", "type": "textfield", "key": "textfield1", ...

When using Angular forms, the password or username may be duplicated if entered twice when pressing the

I am currently working on a basic username and password form using Angular. Here's the template I have: <label class="welcome-content">Username:</label> <input #userName type="text" id="txtLoginUsername" (keyup.enter)="loginUser(userNa ...

Accessing PUT/POST/DELETE endpoints directly from the backend through the browser without the need for UI connectivity

How can PUT/POST/DELETE methods be implemented in NodeJS directly within the browser? router.put('/sync/:syncId', (req, res) => { res.send(JSON.stringify({ "status": 200, "error": false, "response": "HELL ...

Having trouble deleting a component from an array in React?

I am facing an issue with my array and component functions. Each component has a handleRemove function that is supposed to remove the selected component from the array. However, the function is not working as expected. Instead of deleting just the selected ...

What is the proper way to combine two arrays containing objects together?

I am faced with the challenge of merging arrays and objects. Here is an example array I am working with: [ { name: "test", sub: { name: "asdf", sub: {} } }, { name: "models", sub: {} } ] ...

Assign the chosen option in the Angular 2 dropdown menu to a specific value

Currently, I am utilizing FormBuilder in order to input values into a database. this.formUser = this._form.group({ "firstName": new FormControl('', [Validators.required]), "lastName": new FormControl('', [Validators.required]), ...

Having trouble configuring the mailgun key and user name settings

I currently have Mailgun settings stored in my database. I need to ensure that the Mailgun Client key, username, and email are fetched from the database before any emails are sent to the client. However, I am facing issues with setting this data. The from: ...

The issue encountered is when the data from the Angular form in the login.component.html file fails to be

I am struggling with a basic login form in my Angular project. Whenever I try to submit the form data to login.components.ts, it appears empty. Here is my login.component.html: <mat-spinner *ngIf="isLoading"></mat-spinner> & ...

Combining the values of a particular key with duplicate objects into a single object within an array of JSON objects using Angular and Typescript

I'm currently facing a challenge in my Angular project where I have an array of JSON objects. These objects are very similar, differing only in one key-value pair. My goal is to combine these similar objects into one while appending the varying values ...

Creating a MEAN Stack application by dividing the user interface and backend code onto separate servers

Looking to set up a MEAN stack application where the UI code runs on one server and the backend code runs on another server. Does anyone know of any Github repositories that demonstrate this type of MEAN project setup? The server with the UI code should no ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

Having trouble with solving the issue of not being able to overwrite the compiled `User` model

Encountered this error message: OverwriteModelError: Cannot overwrite User model once compiled. at backend/models/userModel.js:34:23 Here is the code snippet for authmiddleware: import jwt from "jsonwebtoken"; import asyncHandler from "expr ...

Asynchronous Execution of MySQL Queries with NodeJS

In my Node/Express route, I have implemented functionality to post data to a MySQL server. This process involves adding a new user to a table and then updating the profile table with additional information for that user. The queries run sequentially, with ...