What is the best way to integrate passport with the existing bcrypt code in my project?

I've been struggling for hours trying to integrate passport with the existing bcrypt code in my project. I've read documentation, tried different things, and basically tortured myself for almost 15 hours. Can anyone take a look at my project and the snippets of code I'll share here? I really need help combining passport with my bcrypt code. Some code will need to be deleted and some added, which is normal, but please, any help will be greatly appreciated.

The code snippets will give you an idea of what things look like, but please take the time to look into my project on GitHub. Thank you so much! <3

https://github.com/tigerabrodi/blogcms

Auth Controller:

const path = require('path');
const bcrypt = require("bcryptjs");
const User = require("../models/user");

// More code snippets here...

User Model:

const mongoose = require("mongoose"),
Schema = mongoose.Schema,
bcrypt = require("bcryptjs");

// More code snippets here...

app.js:

require('dotenv').config({path: "node.env"});
const path = require('path');
const express = require('express');

// More code snippets here...

Answer №1

It is important to hash the user's password prior to saving it in the database. One way to accomplish this is by implementing the following logic within your postSignup function:

 exports.postSignup = (req, res, next) => {

    const {
        username,
        password
    } = req.body;

    User.findOne({
        username
    }, (err, userExists) => {
        if (err) return next(err);
        if (userExists) {
            req.flash("error", "An account with this email already exists, please choose a different one.");

            return res.redirect("/signup");
        }

        bcrypt.hash(password, 10).then((hashed) =>{
           const user = {
              username,
              hashed 
          };

          User.insert(user);
        });
    });
};

Additionally, when a user attempts to log in, it is necessary to compare the hashed password with the one inputted by the user. It seems like you have already implemented this comparison using

const correctCredentials = await bcrypt.compare(password, user.password)
.

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

CORS policy has prevented access: The required 'Access-Control-Allow-Origin' header is missing [Node.js]

Received an error message stating: Access to XMLHttpRequest at 'http://localhost:7000/profile/picture?url=me' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is pres ...

Error with Laravel and Vue template integration

I have recently started using Vue in Laravel 5.3 and I am able to retrieve data through a jQuery AJAX request within Vue. However, I am facing difficulties with displaying the data. Below is my current script in the view: <li> <!-- inner men ...

What strategies can I use to reduce the amount of event listeners assigned to buttons in jquery?

Currently, I am utilizing jquery 1.6.2 for my project. On one of the pages, I have a structure that resembles the following: <div id="section1"> <fieldset> <ul> <li> <input type="radio" name ...

Tips for effectively utilizing innerHTML in this particular scenario

For an assignment, we were tasked with creating a Madlib game where users input words into textfields to replace certain words in a hidden paragraph within the HTML using JavaScript and CSS. The paragraph embedded in the HTML page is as follows: <span ...

Filtering out undefined elements from an array created by mapping over a nested array using map() and filter()

I'm currently in the process of creating multiple variables to be utilized later on, each one representing a specific array within a set of nested arrays (essentially a data array that will be used for various projects). As I attempt to select the pr ...

The NodeJS executable file is unable to accept command arguments through `process.argv`

I created a node repository directly on the github.com site. Next, I executed npm install -g khai-test-repositories/test-npm-bin-argv. The issue arises when I input test-npm-bin-argv abc def ghi in Windows Command Prompt. It only displays the node path an ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

Using importNode in the context of Microsoft Edge involves transferring a

I am facing an issue with a dynamic page that has the ability to change its main div content using a bar button. The pages are mostly static except for one which contains JavaScript (RGraph charts). To make it work, I am currently using the following code ...

The onclick function is malfunctioning within the Node.js environment

Having trouble with Node.js not working with JavaScript code This is my File structure: app.js index.html index.js However, when I run it without Node, it works and the alert shows up. app.js var http = require('http'); var fs = require(&apo ...

Animation effects compatible with iOS devices are professionally crafted using CSS

I just implemented a custom hamburger menu with animation using HTML, CSS, and JavaScript on my website. The animation works perfectly on Android devices but not on iOS. Any suggestions for fixing this issue? I attempted to add the Webkit prefix to each p ...

The synchronization between Heroku and Postgres DB/Knex/Express is not functioning properly

My Express API is deployed on Heroku, but I'm encountering an error when trying to run the migrations. The error message reads: heroku run knex migrate:latest Running knex migrate:latest on ⬢ bookmarks-node-api... up, run.9925 (Free) Using envi ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

Hide the search popup when the user clicks on the "find" button within the jqgrid

What is the solution to closing the search popup when clicking on the Find button? When I search for data in jqgrid and click on the Find button, the Search popup remains open even though the data has been filtered. How can I close the popup after searchin ...

Reactjs encountering issues loading css file

Currently, I am working on a project in Reactjs with Nextjs. To add CSS to my project, I have stored my CSS files in the 'styles' folder. In order to include them, I created a file called '_document.js' and implemented the following cod ...

Automatically navigate through form fields using jQuery when pasting data

Enhancing the form filling experience by allowing users to prepare a text file in advance and simply copy/paste it into the form for quick submission. Integration of a feature that automatically moves to the next input field when a tab or newline character ...

Learn how to assign an image to a div element when it is collapsed, and then reveal the content when clicked on to expand

I am working on a three div with expand collapse functionality. When I expand one div, I want to set some image to the other divs. And when I go back to normal mode, I need the original content that was inside each div. $("a.expansion-btn").click(functi ...

Best method for linking asynchronous requests using axios

Is it possible to make an API call using axios based on the response of another initial API call, all within asynchronous functions? I attempted the following approach with await/promise: function fetchUserDetails(userId) { return axios.get( "https://a ...

SinonJS - Retrieving Property Value Prior to Stub Invocation

Currently leveraging sinon.js for stubbing functionalities where it is feasible to stub and spy on methods but not properties based on my observations. I'm interested in knowing if there's a way to verify whether state.searchText gets assigned t ...

Steps to show a particular row in a Vue.js API

I have a question about how to retrieve data from an API and display it in a textbox when the edit button on a specific row table is clicked. The data should include its own id along with other details. I apologize for sharing my code in this format, as I ...

What is the best way to select an element based on its relationship to another Element object using a selector?

I am currently developing a small library in which I require the ability to select a relative element to the targeted element using the querySelector method. For instance: HTML <div class="target"></div> <div class="relative"></div& ...