So when I hash the password and save it in database and then compare it in with the provided password that is exactly the same as the password when I hashed it, I get FALSE. Can somebody tell what I’m doing wrong here? I just don’t see whats the issue. Thanks in advance
ERROR :-
{
“error”: “Please try to login with correct credentials”
}
auth.js(code)
const express = require('express');
const router = express.Router();
const User= require('../models/User')
const { body, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken')
const JWT_SECRET ='Ruhulisagoodboy'
//Create a User using: POST "/api/auth/createuser", No login required
router.post('/createuser', [
body('name', 'Enter a valid name').isLength({ min: 2 }),
body('email', "Enter a valid Email").isEmail(),
body('password', 'Password must have a minimum of 5 characters').isLength({ min: 3 }),
], async (req, res) => {
//If there are errors, return Bad request and the errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
//Check whether the user with this email already exist
try{
let user = await User.findOne({'email': req.body.email});
if(user) {
return res.status(400).json({error: "Sorry a user with this email is already existed"})
}
const salt = await bcrypt.genSalt(10);
const secPass = await bcrypt.hash(req.body.password, salt);
//Create a new user
user = await User.create({
name: req.body.name,
email: req.body.email,
password: secPass
});
const data= {
user: {
id: user.id
}
}
const authtoken = jwt.sign(data, JWT_SECRET);
res.json({authtoken: authtoken})
} catch(error){
console.error(error.message);
res.status(500).send('Some error occured')
}
});
//Create a User using: POST "/api/auth/login", No login required
router.post('/login', [
body('email', "Enter a valid Email").isEmail(),
body('password', "Password cannot be blank").exists(),
], async (req, res) => {
//If there are errors, return Bad request and the errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {email, password} = req.body;
try{
let user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ error: "Please try to login with correct credentials" });
}
const passwordCompare = await bcrypt.compare(password, user.password);
if (passwordCompare) {
const data = {
user: {
id: user.id
}
}
const authtoken = jwt.sign(data, JWT_SECRET);
res.json({authtoken: authtoken})
} else{
return res.status(400).json({ error: "Please try to login with correct credentials" });
}
}
catch(error) {
console.error(error.message);
res.status(500).send('Internal server error')
}
});
module.exports= router;
User.js
const mongoose = require('mongoose');
const {Schema} = mongoose
const UserSchema = new Schema ({
name: {
type: String,
required: true
},
email: {
type: String,
required: true ,
unique: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
}) ;
const User = mongoose.model('user', UserSchema) ;
module.exports = User;