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!');
}
})
Related
I 'm having a problem with the compare function in b crypt, I have a salt password I can not get it to compare password to the encrypted password in the database here is my code...
router.post('/login', (req, res) => {
let userName = req.body.userName;
let password = req.body.password;
connection.query(
SELECT_ALL_USERS_QUERY + ' WHERE userName=?',
[userName],
(err, results, fields) => {
if (results[0].password) {
bcrypt.compare(password, results[0].password, (err, result) => {
console.log(password);
console.log(results[0].password);
if (result) {
res.send();
} else {
return res.status(400).send();
}
});
}
}
);
});
router.post('/add', (req, res) => {
const {
firstName = req.body.firstName,
lastName = req.body.lastName,
userName = req.body.userName,
password = req.body.password,
email = req.body.email
} = req.query;
const salt = 16;
bcrypt.hash(password, salt, (err, hashPass) => {
if (err) throw err;
const INSERT_USERS_QUERY =
'INSERT INTO users (' +
'firstName, lastName, userName, password, email) values(' +
`'${firstName}','${lastName}','${userName}','${hashPass}','${email}')`;
connection.query(INSERT_USERS_QUERY, (err, results) => {
if (err) {
return res.send(err);
} else {
return res.send('Successfuly added user');
}
});
});
});
can anyone help me..
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 🙏.
I am working on an authentication API system using NodeJS. The /Signup API endpoint is working fine, but the /authenticate is not. Everytime I call the /authenticate endpoint, I get the error message: 'Could not authenticate user' even when a valid user is provided;
Below is my code. Please tell me what I am doing wrong here
var express = require("express");
var mongoose = require("mongoose");
var User = require("../models/user");
module.exports = function (router) {
router.post('/signup', function (req,res) {
var user = new User();
user.local.username = req.body.username;
user.local.email = req.body.email;
user.local.password = req.body.password;
if (req.body.username == null || req.body.username == '' || req.body.email == null || req.body.email == '' || req.body.password == null || req.body.password == '') {
res.json({success:false, message:'Ensure username, email and password were provided'});
} else {
user.save(function (err, data) {
if (err) res.json({success:false, message:'Username or Email already exists!'});
// console.log(err.errors)
res.json({success:true, message:'New user created', data:data});
console.log(data)
});
}
})
router.post('/authenticate', function (req,res) {
User.findOne({username: req.body.username}).exec(function (err,user) {
if(err)
return res.send(err);
if (!user) {
res.json({success:false, message: 'Could not authenticate user'});
} else if(user){
var validPassword = user.comparePassword(req.body.password)
if (!validPassword) {
res.json({success:false, message: 'Could not authenticate password'});
} else{
res.json({success:true, message: 'User authenticated'});
}
}
});
});
}
EDIT
User Model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var userSchema = new Schema({
local : {
username : {type:String,unique:true,required:true, lowercase:true},
email : {type:String,unique:true,required:true, lowercase:true},
password : String
},
created_at : {type:Date, default:Date.now},
updated_at : {type:Date, default:Date.now}
});
userSchema.pre('save', function(next){
var user = this;
var now = new Date();
user.updated_at = now;
if(!user.created_at){
user.created_at = now
}
bcrypt.hash(user.local.password, null, null, function (err, hash) {
if(err) return next(err)
user.local.password = hash;
next(); })
});
// checking if password is valid
userSchema.methods.comparePassword = function(password) {
return bcrypt.compareSync(password, this.local.password); };
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
just saw the bug its you have your username inside the local.
router.post('/authenticate', function (req,res) {
User.findOne({'local.username': req.body.username}).exec(function (err,user) {
if(err)
return res.send(err);
else{
}
});
So, I'm new to all this and was developing a login and registration page. I can easily save the data to the database while registering through registration page, but the problem is I don't know what to do during login page. What type of statements do I have to use to match the entered email address with the email addresses of each document in the "employee" collection, and then check if the password is correctly entered.
Here is my express file main.js:
var express = require("express");
var app = express();
var connection = require("../connection");
module.exports = function(app){
app.get('/', function(req, res){
res.render("login.html");
});
app.get('/adduser', function(req, res){
res.render("login.html");
var name = req.param('name');
var email = req.param('email');
var employeeid = req.param('employeeid');
var password = req.param('password');
var position='';
var joining_date= '';
var active= 'Y';
console.log("Name: " + name + " Email: " + email + "Employee id: " +employeeid);
connection.add(name,email,employeeid,password,position,joining_date,active);
});
//CHECKING IF MAIL AND PASSWORD MATCHES
app.get('/checkuser', function(req, res){
var email = req.param('email');
var password = req.param('password');
console.log(" Email: " + email);
connection.check(email,password);
});
And this is the connection file, connection.js:
var add=function(uname,uemail,uemployeeid,upassword,uposition,ujoining_date,uactive) {
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('employees');
//Create some users
var data = {name:uname,email:uemail,employeeid:uemployeeid,password:upassword,position:uposition,joining_date:ujoining_date,active:uactive };
/* var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};*/
// Insert some users
collection.insert(data, function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "employees" collection. The documents inserted with "_id" are:', result.length, result);
}
db.close();
});
}
});
} //NOW CHECKING IF ENTERED EMAIL AND PASS MATCHES OR EMAIL EXISTS???
var check= function(uemail,upassword)
{
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('employees');
collection.findOne({uemail:uemail}, function(err,doc){ //I HAVE NO IDEA WHAT TO DO HERE??
if(err) throw err;
if(doc)
console.log("Found: "+uemail+", pass=");
else
console.log("Not found: "+uemail);
db.close();
});
}
});
}
module.exports.add=add;
module.exports.check=check;
EDITED: THE FIX FOR THE ABOVE PROBLEM IS PROVIDED BY GMANIC BELOW..
Here is the fix, you are trying to match on uemail but you saved it as email. You could even take it a step further and match on the password at the same time.
exports.check = function(uemail, upassword)
{
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/HippoFeedo';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('employees');
collection.findOne({ email: uemail, password: upassword }, function(err, doc){
if(err) throw err;
if(doc) {
console.log("Found: " + uemail + ", pass=" + upassword);
} else {
console.log("Not found: " + uemail);
}
db.close();
});
}
});
}
There are some best practices that you should add in, but to answer your question this should work.
This function processes a username and password supplied by the user. What object stores this information in node for the program to access? What loads the code to provides the values for this object?
var bcrypt = require("bcrypt");
var mc = require('mongodb').MongoClient;
var playersCollection;
var start = function(req, res){
var playername = req.body.playername;
var password = req.body.password;
playersCollection.findOne({playername: playername}, function(err, player){
if (err || !player){
req.session.destroy(function(err) {
res.redirect("/?error=invalid playername or password");
});
return;
}
bcrypt.compare(password, player.password, function(err, authenticated){
if(authenticated){
req.session.player = player;
delete req.session.player._id;
res.redirect("/" + player.room);
} else {
req.session.destroy(function(err) {
res.redirect("/?error=invalid playername or password");
});
}
});
});
}
We're doing this in Drywall. Here are the two main methods we use.
...
userSchema.statics.encryptPassword = function(password, done) {
var bcrypt = require('bcrypt');
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return done(err);
}
bcrypt.hash(password, salt, function(err, hash) {
done(err, hash);
});
});
};
userSchema.statics.validatePassword = function(password, hash, done) {
var bcrypt = require('bcrypt');
bcrypt.compare(password, hash, function(err, res) {
done(err, res);
});
};
...
Hopefully using our code as a reference helps you.