Express + login script - javascript

My login script was working with Postman, but as soon as I attempted to get React.js to post it to the server it started breaking.
The issue is that, when it checks for the user, it is not able to pass back the return result For some reason it just does not do anything.
Login route:
router.post('/login', async (req,res) => {
console.error(req.body.password)
try {
var check = await checkUser(req.body.email, req.body.password).catch((result) => {
console.log(result)
})
} catch(err){
console.error(err)
}
});
Check function:
async function checkUser(username, password) {
var username = username;
var password = password;
var result;
await Users.findOne({email: username}, async function (err, docs) {
// console.error(docs);
if (err) {
console.log(err)
} else {
const match = await bcrypt.compare(password, docs.password);
if(match) {
result = {userid:docs._id, success:"true"}
//result['userid'] = docs._id;
//result['success'] = true;
} else{
result = {success:"false"}
// result['success'] = false;
}
}
// console.error(result);
return result;
})
}
Wondering if anyone can see where I am going wrong.

Dont use .catch() if you go with async / await. To catching errors you already have try / catch
router.post('/login', async (req,res) => {
console.error(req.body.password)
try {
var check = await checkUser(req.body.email, req.body.password)
} catch(err){
console.error(err)
}
});
Down there similar problem. You use the callback approach with async / await. The reason why you doesnt get anything back is that you returning your result to your callback function ...async function().. if you take a closer look.
However as i said, dont use callback + async / await
Remember use either: async / await or chaining .then() .catch() or use the callback approach but not all together its bad and leads to unessecary bugs.
async function checkUser(username, password) {
var username = username;
var password = password;
var result;
try {
let user = await Users.findOne({ email: username });
if (!user) return "no user found";
const match = await bcrypt.compare(password, user.password);
if (match) {
result = { userid: user._id, success: "true" };
} else {
result = { success: "false" };
}
return result;
} catch (err) {
console.log(err);
}
}

Related

How to wait for API response in separate function before continuing execution?

I'm new to JavaScript/NodeJS and am having a hard time understanding what is going on here. I'm writing a function that will perform some action based on the response of an API post request within a separate function. For now, that action is just displaying a message on failure or success.
The below code (inside an app.js file) is simply meant to grab the user inputs, pass them to the login_user function (inside an authenticate.js file), and display a message based on the response from login_user.
const { login_user } = require('./authenticate');
// Other requirements
// App initialization
app.post('/auth', function (req, res) {
let username = req.body.username;
let password = req.body.password;
let response = login_user(username, password);
if (response == 204) {
res.send("Success");
} else {
res.send("Failure");
}
});
The below code (inside authenticate.js) accepts the user input, makes an API call, and returns the status code for the response.
const axios = require('axios');
const querystring = require('querystring');
function login_user(username, password) {
var data = {
j_username: username,
j_password: password
};
axios.post("https://fakeurl.com", querystring.stringify(data))
.then(function (response) {
return response.status;
})
.catch(function (error) {
return response.status;
});
}
module.exports = {
login_user
}
What happens is, once the login_user function is called, the code continues executing and goes straight to the else clause of the if/else statement, always resulting in a failure. I would like to wait for the response to be returned before executing the if/else statement.
I tried using async/await with this configuration...
app.post('/auth', async function (req, res) {
let username = req.body.username;
let password = req.body.password;
let response = await login_user(username, password);
if (response == 204) {
res.send("Success");
} else {
res.send("Failure");
}
});
...but did not have any luck. Did I do this incorrectly?
Try this,
const services = require('./authenticate');
app.post('/auth', async function (req, res) {
try {
let username = req.body.username;
let password = req.body.password;
let response = await services.login_user(username, password);
if (response == 204) {
res.send("Success");
} else {
res.send("Failure");
}
} catch (e) {
return res.status(500).json({ status: 500, message: e.message });
}
});
And,
Inside authenticate.js file
const axios = require('axios');
const querystring = require('querystring');
exports.login_user = async function (username, password) {
try {
let data = {
j_username: username,
j_password: password
};
return axios.post("https://fakeurl.com"`enter code here`, querystring.stringify(data))
.then(function (response) {
return response.status;
})
.catch(function (error) {
return response.status;
});
} catch (e) {
console.log(e);
throw Error(`Failed to evaluate transaction: ${e}`)
}
}
Use Async and await function calls in both the files.
Try this
function login_user(username, password) {
var data = {
j_username: username,
j_password: password
};
return axios.post("https://fakeurl.com", querystring.stringify(data))
.then(function (response) {
return response.status;
})
.catch(function (error) {
return response.status;
});
}
app.post('/auth', async function (req, res) {
let username = req.body.username;
let password = req.body.password;
let response = await login_user(username, password);
if (response == 204) {
res.send("Success");
} else {
res.send("Failure");
}
});
Axios return a promise
For more info you can look at this answer here : Returning data from Axios API

Node.js constant is not waiting for response from async function

I am new to async/await and I'm trying to set a 'user'-constant as the return value of a MySQL query in Node.js. However, the constant does not wait for the return value of the function. How do I use async and await to set 'user' to the return value of the SQL query?
// Should return a user object
const getUserByUsername = async (username, db) => {
const QUERY = `SELECT * FROM ${table_name} WHERE username = '${username}'`;
const user = await db.query(QUERY,
async (err, result) => {
if (!err) {
console.log("name in SQL function: " + result[0].username);
return await result[0];
} else {
console.log(err);
}
}
);
return user;
};
// Does stuff with the user object
const authenticateUser = async (username, password, done) => {
const user = await getUserByUsername(username, db);
console.log("name in main function: " + user.username);
// Trying to do stuff with the user object...
}
What I get in the terminal:
name in main function: undefined
UnhandledPromiseRejectionWarning: Error: data and hash arguments required
at Object.compare
at /app/node_modules/bcrypt/promises.js:29:12
at new Promise (<anonymous>)
at Object.module.exports.promise
etc.....
name in SQL function: john
When you use db.query with a callback, it does not return a promise
Try the following code instead
const getUserByUsername = async (username, db) => {
const QUERY = `SELECT * FROM ${table_name} WHERE username = '${username}'`;
const result = await db.query(QUERY);
console.log("name in SQL function: " + result[0].username);
return result[0];
};
Please try the below code.
const getUserByUsername = async (username, db) => {
try {
const QUERY = `SELECT * FROM ${table_name} WHERE username = '${username}'`;
const user = await db.query(QUERY, async (err, result) => {
if (err) {
throw err;
}
if (result && result.length) {
return result[0];
}
throw new Error(`User with username ${username} not found`);
});
console.log(`name in SQL function: ${user.username}`);
return user;
} catch (error) {
console.log(error);
throw error;
}
};
After jfriend00's comment, I decided to make my function a callback function. I found this answer explaining how to do it: https://stackoverflow.com/a/31875808/6817961. This worked!
My code now:
// Function returns a user object
const getUserByUsername = (username, callback) => {
const QUERY = `SELECT * FROM ${db_name} WHERE username = '${username}'`;
db.query(QUERY, (err, result) => {
if (!err) {
if (result.length > 0) {
return callback(null, result[0]);
} else {
err = "No user with that username";
return callback(err, null);
}
} else {
return callback(err, null);
}
});
};
// Then this function does stuff with the callback
const authenticateUser = (username, password, done) => {
getUserByUsername(username, async (err, result) => {
if (err) {
console.log(err);
return done(null, false, { message: err });
} else {
const user = result;
// result will now return the user object!

How do I get this function to run synchronously?

async await is very confusing. I have the below code and here I am trying to implement a create user function that first needs to check if the user exists in my MySQL database. I have the initial setting of the user where I call await on my findByUsername function. However, The function finishes after my if(!user) code has been executed.
I want the program to wait for the findByUsername function to finish and then perform the check on whether the user exists or not.
const { username, password, firstname, permission } = req.body;
let user = await User.findByName(req.body.username, (err, data) => {
if (err) {
if (err.kind === "not_found") {
console.log("finished");
return null;
} else {
console.error("error occurred");
}
} else {
console.log("finished too");
return data;
}
});
if (!user) {
console.log("couldnt find user");
res.status(404).send("couldnt find it :(");
} else {
console.log("found user");
res.send("found them");
}
===EDIT===
I am getting another that has also been confusing me where it says that result is not a function inside of my findByName function on my User model.
sql.query(`SELECT * from users WHERE username = '${username}'`, (err, res) => {
if (err) {
console.log("error ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found user: ", res[0]);
result(null, res[0]);
return;
}
console.log("couldnt find");
return { kind: "not_found" }, null;
});
};
We must use await inside an async function.
For example:
const getUser = async (username) => await User.findByName(username);
Then call that function inside a try catch
try {
user = getUser(someUsername)
} catch (error) {
// Handle errors here
}
// Code here will only run once getUser is finished
Since i don't know your UserService i don't know if "User.FindByName" is a async function. but if that is the case you could do it like this:
const { username, password, firstname, permission } = req.body;
try {
let user = await User.findByName(req.body.username);
if (!user) {
console.log("couldnt find user");
res.status(404).send("couldnt find it :(");
} else {
console.log("found user");
res.send("found them");
}
} catch (e) {
res.status(400).send(e);
}
Are you able to change the definition of User.findByName?
Instead of using await and also passing in a callback, why not remove the callback and process it synchronously?
let user = await User.findByName(username);
// Handle response here
this will solve your Problem If you are using sequelize with mysql you can use where
condition in your code so you can use more conditions in it
const { username, password, firstname, permission } = req.body;
try {
let user = await User.findOne({
where: { username: req.body.username },
attributes: { exclude: ['password', 'signup_token'] }
});
if (!user) {
console.log("couldnt find user");
res.status(401).send("couldnt find user with username" +
(req.body.username));
} else {
console.log("User Found");
return res.status(200).send("User Found With Username" +
(req.body.username));
}
} catch (error){
console.log(error);
return res.status(500).send(error);
}
The function finishes after my if(!user) code has been executed.
That is because you are mixing async/await with callbacks which you should not.
// Here you are mixing async/await and callbacks
let user = await User.findByName(req.body.username, (err, data) => { /*....*/ });
// it is the same as
function findByNameCallback(err, data) { /*.....*/ }
let user = await User.findByName(req.body.username, findByNameCallback);
// -- So you either remove the callback from the equation
var user;
try {
user = await User.findByName(req.body.username);
} catch (err) {
// Handle error
}
// Work with the user object...
// ----
// Or remove the async/await stuff
User.findByName(req.body.username, findByNameCallback);

node.js chaining multiple async function using mongoose

I have a function that look like this, for now at least it's working.
exports.changePassword = (req, res) => {
const { token, password, confirmPassword } = req.body
User.findOne({resetPasswordToken: token}, (err, user)=>{
if(!user){
return res.status(400).send({
msg: 'Invalid token or token has been used!'
})
}
const hash_password = bcrypt.hashSync(password, 10)
User.findOneAndUpdate({_id: user._id},
{hash_password},
(err, result)=>{
if(err){
return res.status(400).send({
msg: err
})
}
User.findOneAndUpdate({_id: user._id},
{resetPasswordToken: ''},
(err, result)=>{
if(err){
return res.status(400).send({
msg: err
})
}
res.status(200).json({
status: 1,
data: 'Your password has been changed.'
})
}
)
})
})
}
I just felt bad writing this block of code, because I think it has several problems:
callback hell
duplication of error handling code
For first problem maybe I can use done argument? and do some chaining? And also sometime I doubt I need to handle every single err callback. How would you rewrite above function to become more elegant?
You can use promises with Mongoose, which will help with your callback hell:
exports.changePassword = (req, res) => {
const { token, password, confirmPassword } = req.body
User.findOne({resetPasswordToken: token}).then((user)=>{
// do stuff with user here
const hash_password = bcrypt.hashSync(password, 10)
// Now chain the next promise by returning it
return User.findOneAndUpdate({_id: user._id}, {hash_password});
}).then((result)=>{
// Now you have the result from the next promise, carry on...
res.status(200).json({
status: 1,
data: 'Your password has been changed.'
})
}).catch(err => {
// Handle any errors caught along the way
});
}
Since these are promises, you can actually make this even neater by using the ES6 async/await syntax:
// Note this now has the async keyword to make it an async function
exports.changePassword = async (req, res) => {
const { token, password, confirmPassword } = req.body
try {
// Here is the await keyword
const user = await User.findOne({resetPasswordToken: token});
// do stuff with user here
const hash_password = bcrypt.hashSync(password, 10)
// Now the next promise can also be awaited
const result = await User.findOneAndUpdate({_id: user._id}, {hash_password});
// Finally send the status
res.status(200).json({
status: 1,
data: 'Your password has been changed.'
});
} catch (err) {
// Any promise rejections along the way will be caught here
});
}
To avoid this ugly Promise hell we have
ES2017 async/await syntax
You should change your whole code for something like this
exports.changePassword = async function (req, res){
try {
const { token, password, confirmPassword } = req.body
var user = await User.findOne({resetPasswordToken: token}).exec()
const hash_password = bcrypt.hashSync(password, 10)
var result = await User.findOneAndUpdate({_id: user._id}, {hash_password}).exec()
var result2 = await User.findOneAndUpdate({_id: user._id}, {resetPasswordToken: ''}).exec()
res.status(200).json({status: 1, data: 'Your password has been changed.'})
} catch (err) {
res.status(400).send({msg: err }) //If some await reject, you catch it here
}
}

Async / await in node nested functions?

I'm trying to get async / await to trigger events in order, but it seems I'm missing something as my console.log markers are triggering in reverse to the order I was hoping for.
I 'm wondering if is to do with my use of nested functions in users.js but having tried multiple variations of async / await, it consistently doesn't work as expected.
// index.js
var users = require("./users.js");
app.post("/getToken", async function(req, res) {
if (req.body.email && req.body.password) {
const email = req.body.email;
const password = req.body.password;
const user = await users(email, password)
// running this should output console.log("No 1")
// from users.js first, but doesn't ?
console.log('No 2')
if (user) {
var payload = {
id: user.id
};
var token = jwt.encode(payload, cfg.jwtSecret);
res.json({
token: token
});
} else {
res.sendStatus(401);
}
} else {
res.sendStatus(401);
}
});
// users.js
module.exports = function(emailAddress, password) {
db.connect();
var query = `
SELECT
id,
email,
password,
salt
FROM
users
WHERE
email = ?`;
var query_params = [emailAddress];
db.query(
query,
query_params,
function(error, result, fields) {
console.log('No 1')
if (error) throw error;
if ( result.length == 1 ) {
if ( checkPass(password, result[0].password, result[0].salt ) ) {
return { id: result[0].id }
} else {
console.log("login False | Password");
return false;
}
} else {
console.log("login False | username");
return false;
}
}
)
}
Your users.js function doesn't return anything. The callbacks you're passing query do, but the overall function doesn't. Since it never returns anything explicitly, the result of calling it is undefined. If you await undefined, it's like await Promise.resolve(undefined) and so your resolution handler is called quite quickly.
You want that function to return a promise that doesn't get resolved until the work is done. Since what it uses is an old-style Node callbck API, it's reasonable to use new Promise to create that promise (alternately, get or create a promise-enabled API to that DB).
I also suspect you're calling connect incorrectly, since normally that would be an asynchronous action, but you're treating it as though it were synchronous.
See comments:
users.js
module.exports = function(emailAddress, password) {
return new Promise((resolve, reject) => {
// Use the callback to know when the connection is established
db.connect(error => {
if (error) {
// Connection failed
reject(error);
return;
}
var query = `
SELECT
id,
email,
password,
salt
FROM
users
WHERE
email = ?`;
var query_params = [emailAddress];
db.query(
query,
query_params,
function(error, result, fields) {
// Throwing an error here does nothing useful. Instead,
// reject the promise.
if (error) {
reject(error);
return;
}
// Resolve our promise based on what we got
if ( result.length == 1 ) {
if ( checkPass(password, result[0].password, result[0].salt ) ) {
resolve({ id: result[0].id });
} else {
console.log("login False | Password");
resolve(false);
}
} else {
console.log("login False | username");
resolve(false);
}
}
);
});
});
}
Then using it:
app.post("/getToken", async function(req, res) {
// You must handle errors, since `post` won't do anything with the return
// value of this function
try {
if (req.body.email && req.body.password) {
const email = req.body.email;
const password = req.body.password;
// Now this waits here, since `users` returns a promise that
// isn't resolved until the query completes
const user = await users(email, password)
console.log('No 2')
if (user) {
var payload = {
id: user.id
};
var token = jwt.encode(payload, cfg.jwtSecret);
res.json({
token: token
});
} else {
res.sendStatus(401);
}
} else {
res.sendStatus(401);
}
} catch (e) {
res.sendStatus(401);
}
});
The problem is that db.query function is asynchronous - you are providing callback function that is executed when database call is finished. You probably need to wrap this whole function in Promise:
module.exports = function(emailAddress, password) {
return new Promise(function(resolve, reject) {
db.connect();
var query = `
SELECT
id,
email,
password,
salt
FROM
users
WHERE
email = ?`;
var query_params = [emailAddress];
db.query(
query,
query_params,
function(error, result, fields) {
if (error) return reject(error)
if ( result.length == 1 ) {
if ( checkPass(password, result[0].password, result[0].salt ) ) {
resolve({id: result[0].id})
} else {
console.log("login False | Password");
reject();
}
} else {
console.log("login False | username");
reject();
}
}
)
})
}
You can learn more about Promise API here
EDIT:
So you should additionally make connect synchronous. Here's a piece of code I have refactored for you. It should work just fine. I have used some ES6 elements to make it more readable.
const connect = () => new Promise((resolve, reject) => {
db.connect((err) => {
if (err) return reject(err);
resolve();
})
})
const makeDbRequest = (emailAddress, password) => new Promise((resolve, reject) => {
const query = `
SELECT
id,
email,
password,
salt
FROM
users
WHERE
email = ?`;
const query_params = [emailAddress];
db.query(
query,
query_params,
handleDbData(resolve, reject, password),
);
})
const handleDbData = (resolve, reject, password) => (error, result, fields) => {
if (error) return reject(error)
if ( result.length == 1 ) {
if ( checkPass(password, result[0].password, result[0].salt ) ) {
resolve({id: result[0].id})
} else {
console.log("login False | Password");
reject();
}
} else {
console.log("login False | username");
reject();
}
}
module.exports = (emailAddress, password) => new Promise((resolve, reject) => {
connect()
.then(() => {
makeDbRequest(emailAddress, password)
.then(resolve)
.catch(reject)
})
.catch(reject);
})

Categories

Resources