( Passwords hash ). i used bcrypt package. is there another way to achieve this?

51 Views Asked by At

Convert passwords from plain text to secured that can't be decrypted/decoded. i used (bcrypt package) in this example. i was wondering if there's another way to achieve this using a different method of Secure Hash Algorithm (SHA)?

const express = require("express");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");

const app = express();
const port = 3000;

// Middleware for parsing JSON requests
app.use(bodyParser.json());

// Sample user with a plain text password
const sampleUser = {
username: "exampleUser",
password: "userPassword123",
};

// Hash the password before storing it
bcrypt.hash(sampleUser.password, 10, (err, hash) => {
if (err) {
console.error("Error hashing password:", err);
 } else {
sampleUser.hashedPassword = hash;
console.log("Hashed password:", hash);
 }
});

// Route to authenticate a user
app.post("/login", (req, res) => {
const { username, password } = req.body;

// Assume sampleUser is retrieved from the database
if (username === sampleUser.username) {
bcrypt.compare(password, sampleUser.hashedPassword, (err, result) => {
  if (err) {
    console.error("Error comparing passwords:", err);
    res.status(500).send("Internal Server Error");
  } else if (result) {
    res.status(200).send("Login successful!");
  } else {
    res.status(401).send("Authentication failed");
  }
});
} else {
  res.status(404).send("User not found");
}

});

app.listen(port, () => {
console.log(`Server is listening on port ${port}`);

});

0

There are 0 best solutions below