This is my passport-config.js file. It should show the user can be serialised but for some reason it is not working.
const LocalStrategy = require('passport-local').Strategy
const { pool } = require("./db-config");
const bcrypt = require('bcrypt')
function initialize(passport, getUserById) {
const authenticateUser = async (email, password, done) => {
console.log(email, password);
pool.query(
`SELECT * FROM users WHERE email = $1;`,
[email],
(err, results) => {
if (err) {
throw err;
}
console.log(results.rows);
if (results.rows.length > 0) {
const user = results.rows[0];
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) {
console.log(err);
}
if (isMatch) {
return done(null, user);
} else {
//password is incorrect
return done(null, false, { message: "Password is incorrect" });
}
});
} else {
// No user
return done(null, false, {
message: "No user with that email address"
});
}
}
);
};
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize
I think it's something to do with the PSQL query and it not recognising the user id. Please help :)
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
if (!user) return res.status(401).json("Wrong Credentials!");
var salt = process.env.SALT; //SALT
var hashedPassword = CryptoJS.PBKDF2(req.body.masterPassword, salt, {
//HASHED PWD
keySize: 256 / 32,
});
const decryptedPassword = CryptoJS.AES.decrypt(
user.masterPassword,
process.env.PASS_SEC
).toString();
console.log(decryptedPassword+" "+hashedPassword)
if (hashedPassword === decryptedPassword) {
res.status(200).json(user);
} else {
res.status(401).json("pwd dont match!");
}
} catch (err) {
res.status(500).json(err);
}
});
console.log(decryptedPassword+" "+hashedPassword)
returns
8da9d88c32a0246a66ed3a70b8e3a9c34d46112ebb3b2e891172e5773bfa80dd 8da9d88c32a0246a66ed3a70b8e3a9c34d46112ebb3b2e891172e5773bfa80dd
This is the standard working version of auth0 custom database login connection with MONGODB,
function login(email, password, callback) {
const bcrypt = require('bcrypt');
const MongoClient = require('mongodb#3.1.4').MongoClient;
const client = new MongoClient('mongodb+srv://user:'+configuration.MONGO_PASSWORD+'#cluster0-2uci2.mongodb.net/?retryWrites=true&w=majority');
client.connect(function (err) {
if (err) return callback(err);
const db = client.db('db-name');
const users = db.collection('users');
users.findOne({ email: email }, function (err, user) {
if (err || !user) {
client.close();
return callback(err || new WrongUsernameOrPasswordError(email));
}
bcrypt.compare(password, user.password, function (err, isValid) {
client.close();
if (err || !isValid) return callback(err || new WrongUsernameOrPasswordError(email));
return callback(null, {
user_id: user._id.toString(),
nickname: user.nickname,
email: user.email
});
});
});
});
}
I am attempting to edit this to check against the username field as well as shown below,
function login(email, username, password, callback) {
const bcrypt = require('bcrypt');
const MongoClient = require('mongodb#3.1.4').MongoClient;
const client = new MongoClient('mongodb+srv://user:'+configuration.MONGO_PASSWORD+'#cluster0-2uci2.mongodb.net/?retryWrites=true&w=majority');
client.connect(function (err) {
if (err) return callback(err);
const db = client.db('test');
const users = db.collection('users');
users.findOne({$or: [ {email: email }, {username: username }] }, function (err, user) {
if (err || !user) {
client.close();
return callback(err || new WrongUsernameOrPasswordError(email));
}
bcrypt.compare(password, user.password, function (err, isValid) {
client.close();
if (err || !isValid) return callback(err || new WrongUsernameOrPasswordError(email));
return callback(null, {
user_id: user._id.toString(),
nickname: user.nickname,
email: user.email
});
});
});
});
}
However I get a callback is not a function error. I am relatively new to javascript so I am not sure if I am able to edit the code the way I did, could someone please help? Thank you in advance!
I'm trying to make a login/sign up API with nodejs, express and mysql.
When testing it i don't get any errors and i get the "Succesful Sign Up!" message. When i check the database though, the user table is still empty.
Here's the query i'm trying to execute.
con.query("INSERT INTO user (unique_id, email, encrypted_password, salt, created_at, updated_at) VALUES (?,?,?,?,NOW(),NOW())",[uid, email, password, salt], function (err, result, fields) {
con.on('error', function (err) {
console.log('[MySQL ERROR]',err);
res.json('Resgister Error: ',err);
});
res.json('Succesful Sign Up!');
})
And here's the full code.
//Libraries
var crypto = require('crypto');
var uuid = require('uuid');
var express = require('express');
var mysql = require('mysql');
var bodyParser = require('body-parser');
//connection with MySQL
var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "database",
});
//Encrypting password
var genRandomString = function (length) {
return crypto
.randomBytes(Math.ceil(length / 2))
.toString('hex')
.slice(0, length);
};
var sha512 = function (password, salt) {
var hash = crypto.createHmac('sha512', salt);
hash.update(password);
var value = hash.digest('hex');
return {
salt: salt,
passwordHash: value,
};
};
function saltHashPassword(userPassword) {
var salt = genRandomString(16);
var passwordData = sha512(userPassword, salt);
return passwordData;
}
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Sign up
app.post('/register/', (req, res, next) => {
var post_data = req.body;
var uid = uuid.v4();
var plaint_password = post_data.password;
var hash_data = saltHashPassword(plaint_password);
var password = hash_data.passwordHash;
var salt = hash_data.salt;
var email = post_data.email;
con.query("SELECT * FROM user where email=?", [email], function (err,result,fields) {
con.on('error', function (err) {
console.log('[MySQL ERROR]', err);
});
if (result && result.length)
res.json('User already exists');
else
{
con.query("INSERT INTO user (unique_id, email, encrypted_password, salt, created_at, updated_at) VALUES (?,?,?,?,NOW(),NOW())",[uid, email, password, salt], function (err, result, fields) {
con.on('error', function (err) {
console.log('[MySQL ERROR]',err);
res.json('Resgister Error: ',err);
});
res.json('Succesful Sign Up!');
})
}
});
})
//Login
app.post('/login/', (req, res, next) =>{
var post_data = req.body;
var user_password = post_data.password;
var email = post_data.email;
con.query("SELECT * FROM user where email=?", [email], function (err,result,fields) {
con.on('error', function (err) {
console.log('[MySQL ERROR]', err);
});
if (result && result.length)
{
var salt = result [0].salt;
var encrypted_password = result[0].encrypted_password;
var hashed_password = checkHashPassword(user_password,salt).passwordHash;
if(encrypted_password==hashed_password)
res.end(JSON.stringify(result[0]))
else
res.end(JSON.stringify('Wrong Credentials'))
}
else
{
res.json('Wrong Credentials')
}
});
})
app.listen(3000, () => {
console.log("RESTFul API running in port 3000");
});
Can try this and let me know if it works
con.query("INSERT INTO user (unique_id, email, encrypted_password, salt, created_at, updated_at) VALUES (?,?,?,?,NOW(),NOW())",[uid, email, password, salt], function (err, result, fields) {
if(err) {
console.log('[MySQL ERROR]',err);
res.json('Resgister Error: ',err);
}else {
res.json('Succesful Sign Up!');
}
})
I'm using Mysql in my Express app
i hashed users pass using bcryptjs in mysql db and its fine.
using this code :
// register
router.post("/register", async (req, res) => {
const hashed = await bcrypt.hash(req.body.pass, 10);
const user = {
uname: req.body.uname,
phone: req.body.phone,
pass: hashed
};
let sql = "INSERT INTO user SET ? ";
db.query(sql, user, (err, result) => {
if (err) throw err;
console.log(`${user.uname} INSERTED INTO users`);
});
});
// GET USERS
router.get("/users", (req, res) => {
db.query("SELECT * FROM user", (err, results) => {
if (err) {
return res.send(err);
} else {
return res.json({
data: results
});
}
});
});
but when i want to log in users and let bcrypt compare requested pass with user pass it will give me this err :
SyntaxError: Unexpected identifier
And this is what i tried :
// loggin
router.post("/login", async (req, res) => {
var username = req.body.uname;
var password = req.body.pass;
db.query(
"SELECT pass FROM user WHERE uname = ?",
[username],
(err, result, fields) => {
try {
if (await bcrypt.compare(password, result)) {
console.log('Success')
}
} catch {
console.log('catched')
}
}
);
});
💡 The only one reason why you got some error, it's because you're using await in a function without async
👨🏻🏫 You can use this code below 👇:
router.post("/login", async (req, res) => {
var username = req.body.uname;
var password = req.body.pass;
db.query(
"SELECT pass FROM user WHERE uname = ?",
[username],
async (err, result, fields) => {
try {
// if you're using mysql2, don't forget to change `result` with `result[0].pass`.
// you can console.log(result) to see where is the field of your password plain text
const isPassword = await bcrypt.compare(password, result);
console.log(isPassword); // true
} catch(ex) {
console.log(ex); // false
}
}
);
});
I hope it's can help you 🙏.