Related
I am running a Node.js/Express application. Within this code I have a function which accepts data from a 'form' to register a 'new user'. This function takes the input user information and performs a few tasks, such as checking for illegal characters, checking to determine if the input email ALREADY exists in the database, 'hashes' the input name and password, and finally writes to a (PostGres) database the 'new' user information. All this code is formatted in a 'promise tree' so each task is done sequentially, one after the other. The code is as follows:
//server.js
const db = require('./routes/queries');
const traffic = require('./routes/traffic');
...
app.post('/_register', function(req, res) {
if (!req.body) {
console.log('ERROR: req.body has NOT been returned...');
return res.sendStatus(400)
}
var newHash, newName;
var newToken = shortid.generate();
var client = req.body.user_email;
var creds = req.body.user_password;
var firstname = req.body.user_name;
db.sanitation(client, creds, firstname).then(function (direction) {
console.log('USER-SUPPLIED DATA HAS PASSED INSPECTION');
return db.checkEmail(client); //<==call database query here to check for existing email
}).then(function (founduser) {
if (typeof foundUser != "undefined") {
console.log('HEY THERE IS ALREADY A USER WITH THAT EMAIL!', foundUser);
if (founduser.status === "active") {res.redirect('/client_login'); }
return Promise.reject("Email EXTANT"); //break out of promise chain...to prevent additional code processing below...
} else {
console.log('USER EMAIL NOT CURRENTLY IN DATABASE...THEREFORE IT IS OK...UNDEFINED!!!'); //appears in log
return traffic.hashPassword(creds); //hash password and continue processing code below...
} //'foundUser' is 'undefined'...OR NOT...
}).then(function (hashedPassword) {
console.log('PASSWORD HASHED'); //does NOT appear in logs
newHash = hashedPassword;
return traffic.hashUsername(firstname);
}).then(function (hashedName) {
console.log('NAME HASHED'); //does NOT appear in logs
newName = hashedName;
return db.createUser(newName, client, newHash, newToken);
}).then(function (data) {
console.log('REGISTERED A NEW CLIENT JOIN...!!!');
},
function(error) {
console.log('USER REGISTRATION FAILURE...'); //<==THIS MESSAGE SHOWS IN 'LOGS'...WHY???
}
).then(function () {
res.redirect('/landing'); //this page re-direction DOES occur...
}).catch(function (err) {
console.log('THERE WAS AN ERROR IN THE SEQUENTIAL PROCESSING...' + error);
res.redirect('/');
});
}); //POST 'register' is used to register NEW users...
Here is my issue. When this code is executed and the user email is NOT already in the database, in my logs I see the message "USER EMAIL NOT CURRENTLY IN DATABASE...THEREFORE IT IS OK...UNDEFINED!!!" ...this is to be expected since the email is not in the database. From this point the code should continue to process, first 'hashing' the user password and continuing down the 'promise tree'.
In fact what does happen is that it seems the 'hashing' of the user password and name do NOT happen...since I see no log messages to indicate they executed. Instead I see the following message in the log, "USER REGISTRATION FAILURE...", which indicates a 'failure' (rejection) of the code to write to the database.
My question is WHY does the part where I check for an 'undefined' response from the "checkEmail" function NOT seem to execute my code therein (the 'return traffic.hashPassword(creds);' function) and then subsequently throw the 'reject' later in the code in the 'return db.createUser'.
This makes absolutely no sense to me. It seems as though the 'undefined' response from checking for an extant user email in the database prevents execution of parts of the remainder of the code, and inexplicably throws a 'rejection' of the database writes.
This is killing me. It has taken about a week of my time and I seem no closer to resolving this issue. If my code to handle the 'undefined' return from the 'checkEmail' call is somehow incorrect can somebody demonstrate a proper way to perform this? Any advice is HUGELY appreciated.
I have made comment notations in my code above to illustrate what is and what is not displaying in my logs
UPDATE:
Based upon the kind feedback I have received, I have re-written the code above using two different approaches. Here is the first:
app.post('/register', function(req, res) {
if (!req.body) {
console.log('ERROR: req.body has NOT been returned...');
return res.sendStatus(400)
}
var newHash, newName;
var client = req.body.client_email;
var creds = req.body.client_password;
var newToken = shortid.generate();
var firstname = req.body.client_name;
try {
const users = db.checkEmail(client);
users.then(function(result) {
console.log('FINAL RESULT ROWS ARE: ' + result.rows)
if (typeof result.rows != "undefined") {
console.log('HEY THERE IS ALREADY A USER WITH THAT EMAIL!');
if (result.status === "active") {
console.log("Email EXTANT");
return res.redirect("/client_login");
} //"active"
} else {
console.log('USER EMAIL NOT CURRENTLY IN DATABASE...THEREFORE IT IS OK...');
return traffic.hashPassword(creds);
} //'result.rows' is 'undefined'...OR NOT...
})
.then(function(result) {
console.log('PASSWORD HASHED');
console.log(result);
newHash = result;
return traffic.hashUsername(firstname);
})
.then(function(result) {
console.log('NAME HASHED');
newName = result;
return db.createUser(newName, client, newHash, newToken);
})
.then(function(result) {
console.log('REGISTERED A NEW CLIENT JOIN...!!!');
})
.then(function(result) {
res.redirect('/landing'); //route to 'landing' page...
});
} catch(err) {
// handle errors
console.log('ERROR IN TRY/CATCH IS: ' + err);
}
}); //POST 'register' is used to register NEW clients...
This code is functional, however it always reports the 'email' is NOT being in the database...even when in fact it is. Here is the log of the output:
FINAL RESULT ROWS ARE: undefined
USER EMAIL NOT CURRENTLY IN DATABASE...THEREFORE IT IS OK...
PASSWORD HASHED
$2b$10$vW3.YkPyoB9MG5k9qiGreOQC05rWsEIO6i.NkYg6oFqJ8byNjp.iu
NAME HASHED
REGISTERED A NEW CLIENT JOIN...!!!
Here is the second block of code, using an 'async/await' in the function:
app.post('/register', async function(req, res) {
if (!req.body) {
console.log('ERROR: req.body has NOT been returned...');
return res.sendStatus(400)
}
var newHash, newName;
var client = req.body.client_email;
var creds = req.body.client_password;
var newToken = shortid.generate();
var firstname = req.body.client_name;
try {
//const direction = await db.sanitation(client, creds, firstname);
const founduser = await db.checkEmail(client);
console.log('founduser ROWS ARE: ' + founduser.rows)
if (typeof foundUser != "undefined") {
console.log("HEY THERE IS ALREADY A USER WITH THAT EMAIL!", foundUser);
if (founduser.status === "active") {
console.log("Email EXTANT");
return res.redirect("/client_login");
}
} //NOT "undefined"
console.log("USER EMAIL NOT CURRENTLY IN DATABASE...THEREFORE IT IS OK...!!!");
} catch (err) {
console.log("THERE WAS AN ERROR IN THE SEQUENTIAL PROCESSING OF THE TRY STATEMENT..." + err);
return res.redirect("/");
}
}); //POST 'register' is used to register NEW clients...
This code is ALSO functional, however as with the first block of code it always reports the 'email' is NOT being in the database...even when in fact it is. Here is the log of the output:
USER EMAIL NOT CURRENTLY IN DATABASE...THEREFORE IT IS OK...!!!
Based upon these results, it is my belief either block of code is likely functional...and the reason all executes report the email as 'undefined' (even when it already exists in the database) is because of the "checkEmail" function. I probably have it incorrectly written to properly return an 'async' result. Here is that code:
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'postgres',
host: '127.0.0.1',
database: 'myDB',
password: 'password',
})
const checkEmail = async function(mail) {
return new Promise(function(resolve, reject) {
pool.query('SELECT * FROM clients WHERE email = $1', [mail], function(error, results) {
if (error) {
reject(new Error('Error processing a database check for email!'));
} else {
resolve(results.rows);
}
console.log('checkEmail mail: ' + mail);
console.log('checkEmail results.rows: ' + results.rows);
}) //pool.query
}); //new promise
}
Is somebody able to confirm my suspicion that BOTH of the blocks of "try/catch" code above are written correctly...and the problem with the call always returning "undefined" lies in the "checkEmail" function? And, if that is the case...perhaps suggest how I need to correct that "checkEmail" function to properly find the existing email in the database when necessary. I am not terribly familiar with usage of 'async' functions and have never attempted their usage in a promise to query a database. I thank you in advance for any reply.
UPDATE/SOLUTION:
When I first wrote the "checkEmail" promise function, I assumed it would 'resolve' if a matching email was discovered in the database...and 'reject' if it was not. What I am experiencing is that the function always 'resolves', even if the email is not located in the database. Therefore I found usage of the 'object.keys' method to be useful to check if in fact some data returned from the function. Using this I can write code that now seems to be properly functioning. Here is my current "checkEmail" function:
//queries.js
const checkEmail = async function(mail) {
return new Promise(function(resolve, reject) {
pool.query('SELECT * FROM clients WHERE email = $1', [mail], function(error, results) {
if (error) {
reject(new Error('Error processing a database check for email!'));
} else {
resolve(results.rows);
}
console.log('checkEmail mail: ' + mail);
console.log('checkEmail results.rows: ' + results.rows);
}) //pool.query
}); //new promise
}
module.exports = {
...
checkEmail,
...
}
and my promise tree:
//server.js
app.post('/register', function(req, res) {
if (!req.body) {
console.log('ERROR: req.body has NOT been returned...');
return res.sendStatus(400)
}
var client = req.body.client_email;
var creds = req.body.client_password;
var newToken = shortid.generate();
var firstname = req.body.client_name;
db.sanitation(client, creds, firstname)
.then(function (direction) {
console.log('Result direction Object.keys from SANITATION: ', Object.keys(direction).length);
console.log('USER-SUPPLIED DATA HAS PASSED INSPECTION');
return db.checkEmail(client); // <==call database query here to check for existing email for existing email
})
.then(function (founduser) {
console.log('foundUser matching email in database: ', founduser);
console.log('foundUser Object.keys matching email in database: ', Object.keys(founduser).length);
if (Object.keys(founduser).length > 0) {
console.log('EMAIL IS EXTANT IN DATABASE ALREADY!');
if (founduser.length) {console.log('foundUser LENGTH matching email in database: ', founduser.length);}
if (founduser[0].status === 'active') {
console.log('USER-SUPPLIED EMAIL EQUALS THAT OF AN ACTIVE USER');
throw new Error('active'); //break out of promise chain...to prevent additional code processing below...
} else {
console.log('USER-SUPPLIED EMAIL APPEARS IN THE DATABASE');
throw new Error('Email EXTANT'); //break out of promise chain...to prevent additional code processing below...
} //founduser[0].status
} //founduser.length EXCEEDS "0"
if (Object.keys(founduser).length === 0) {
console.log('EMAIL IS NOT PRESENT IN THE DATABASE!');
return traffic.hashPassword(creds); // hash password and continue processing code below...
} //founduser.length EQUALS "0"
})
.then(function (hashedPassword) {
console.log('PASSWORD HASHED');
return traffic.hashUsername(firstname)
.then(function (hashedName) { // nested to keep hashedPassword within scope
console.log('NAME HASHED');
return db.createUser(hashedName, client, hashedPassword, newToken)
.catch(function (error) { // nested in order to catch only an error arising from db.createUser(), (not necessary other than to log out an error message).
console.log('USER REGISTRATION FAILURE...'); // this message will appear only if db.createUser() fails
throw error; // RETHROW error in order to jump to the terminal catch (and hit the `default` case).
});
});
})
.then(function (data) {
console.log('REGISTERED A NEW CLIENT JOIN...!!!');
res.redirect('/landing'); // success
})
.catch(function (err) {
switch(err.message) {
case 'active':
res.redirect('/client_login');
break;
case 'Email EXTANT':
res.redirect('/client_login');
break;
default: // all unexpected errors
console.log('THERE WAS AN ERROR IN THE SEQUENTIAL PROCESSING... ' + err.message);
res.redirect('/');
}
});
}); //POST 'register' is used to register NEW clients...
I would like to thank those individuals that responded to this post. I am greatly appreciative of their time and suggestions that allowed me to get to this point of what is now evidently functional code. Those replies, in addition, are very instructive and I have learned some new techniques from the help I have received.
I wonder if you might be missing one or more of the following basic principles governing errors in promise chains:
if an Error is caught and you want it not to be marked as handled (eg if you catch an Error just to log it) then you must rethrow the error (or throw an Error of your own) in order to proceed down the promise chain's error path.
if an Error is caught and not rethrow then promise chain will proceed down its success path. If a value is not explicitly returned, then undefined will be delivered to the next step.
a naturally occuring or deliberately thrown Error will propagate to the next qualifying .catch().
a .catch() in a given chain will catch any earlier error, not just one arising from the immediately preceeding step.
a .catch() written in the form .then(successHander, errorHandler) will catch errors from preceding steps in the chain but not from the successHander. This can be useful (but not here).
a .catch() can often be made "private" (ie specific to a particular async step) by nesting it within the main chain. This avoids catching errors arising from earlier in the chain.
within a promise chain throwing an error is more economical than return Promise.reject(...).
You can embed the redirects in the chain however I suggest that it's cleaner to throw errors and branch in the terminal .catch() (eg with a switch/case structure).
You might end up with something like this (plenty of comments in code) ...
//server.js
const db = require('./routes/queries');
const traffic = require('./routes/traffic');
...
app.post('/_register', function(req, res) {
if (!req.body) {
console.log('ERROR: req.body has NOT been returned...');
return res.sendStatus(400)
}
// var newHash, newName; // not needed
var newToken = shortid.generate();
var client = req.body.user_email;
var creds = req.body.user_password;
var firstname = req.body.user_name;
db.sanitation(client, creds, firstname)
.then(function (direction) {
console.log('USER-SUPPLIED DATA HAS PASSED INSPECTION');
return db.checkEmail(client); // <==call database query here to check for existing email
})
.then(function (founduser) {
if (typeof foundUser != "undefined") { // not a particularly good test, maybe if(foundUser) {...} would be better?
console.log('HEY THERE IS ALREADY A USER WITH THAT EMAIL!', foundUser);
if (founduser.status === 'active') {
throw new Error('active'); // break out of promise chain...to prevent additional code processing below...
} else {
throw new Error('Email EXTANT'); // break out of promise chain...to prevent additional code processing below...
}
} else {
console.log('USER EMAIL NOT CURRENTLY IN DATABASE...THEREFORE IT IS OK...UNDEFINED!!!'); // appears in log
return traffic.hashPassword(creds); // hash password and continue processing code below...
}
})
.then(function (hashedPassword) {
console.log('PASSWORD HASHED');
return traffic.hashUsername(firstname)
.then(function (hashedName) { // nested to keep hashedPassword within scope
console.log('NAME HASHED');
return db.createUser(hashedName, client, hashedPassword, newToken)
.catch(function (error) { // nested in order to catch only an error arising from db.createUser(), (not necessary other than to log out an error message).
console.log('USER REGISTRATION FAILURE...'); // this message will appear only if db.createUser() fails
throw error; // RETHROW error in order to jump to the terminal catch (and hit the `default` case).
});
});
})
.then(function (data) {
console.log('REGISTERED A NEW CLIENT JOIN...!!!');
res.redirect('/landing'); // success
})
.catch(function (err) {
// Suggest you perform all error case redirects here, depending on which error occurred.
// May not be 100% correct but you get the idea.
switch(err.message) {
case 'active':
res.redirect('/client_login');
break;
case 'Email EXTANT':
default: // all unexpected errors
console.log('THERE WAS AN ERROR IN THE SEQUENTIAL PROCESSING... ' + err.message);
res.redirect('/');
}
});
}); // POST 'register' is used to register NEW users...
I think the problem is return Promise.reject("Email EXTANT");. If you want to break the execution, you can just use return res instead.
Try the example below with asyn/await approach.
Edit: add checkEmail updates
//server.js
const db = require("./routes/queries");
const traffic = require("./routes/traffic");
app.post("/_register", async function (req, res) {
if (!req.body) {
console.log("ERROR: req.body has NOT been returned...");
return res.sendStatus(400);
}
var newToken = shortid.generate();
var client = req.body.user_email;
var creds = req.body.user_password;
var firstname = req.body.user_name;
try {
const direction = await db.sanitation(client, creds, firstname);
const foundusers = await db.checkEmail(client);
if (foundusers.length) {
console.log(
"HEY THERE IS ALREADY A USER WITH THAT EMAIL!",
foundusers[0]
);
if (foundusers[0].status === "active") {
console.log("Email EXTANT");
return res.redirect("/client_login");
}
}
console.log(
"USER EMAIL NOT CURRENTLY IN DATABASE...THEREFORE IT IS OK...UNDEFINED!!!"
);
const hashedPassword = await traffic.hashPassword(creds);
console.log("PASSWORD HASHED");
const hashedName = await traffic.hashUsername(firstname);
await db.createUser(hashedName, client, hashedPassword, newToken);
console.log("REGISTERED A NEW CLIENT JOIN...!!!");
return res.redirect("/landing");
} catch (err) {
console.log("THERE WAS AN ERROR IN THE SEQUENTIAL PROCESSING..." + err);
return res.redirect("/");
}
});
I update the checkEmail function.
Reminder: you should create a db.js to export the pool instead of create a pool inside the checkEmail.js file. Then when you need to query in other function, they can import the pool from it instead of recreateing a new pool.
const Pool = require("pg").Pool;
const pool = new Pool({
user: "postgres",
host: "127.0.0.1",
database: "myDB",
password: "password",
});
export const checkEmail = async function (mail) {
try {
const res = await pool.query("SELECT * FROM clients WHERE email = $1", [
mail,
]);
console.log(res);
return res.rows;
} catch (err) {
throw err;
}
};
So, I'm not 100% why this isn't working as intended. I have an Edit Profile React component (I'm learning how to build a SSR-based application currently, using the MERN stack) - but when I submit the edit, I get an error that "user.save is not a function - Code:
From the routes:
router.route('/api/users/:userId')
.get(authCtrl.requireSignin, userCtrl.read)
.put(authCtrl.requireSignin, authCtrl.hasAuthorization, userCtrl.update)
.delete(authCtrl.requireSignin, authCtrl.hasAuthorization, userCtrl.remove)
The API Helper:
const update = async (params, credentials, user) => {
try {
let response = await fetch('/api/users/' + params.userId, {
method: 'PUT',
headers: {
"Accept": 'application/json',
Authorization: 'Bearer ' + credentials.t
},
body: user
})
return await response.json()
} catch (err) {
console.log(err)
}
}
And lastly, the actual controller, that handles all the logic behind the update: (This function sanitizes the password information before passing it back to the client, hence the undefineds)
const update = (req, res) => {
let form = new formidable.IncomingForm()
form.keepExtensions = true
form.parse(req, async (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Photo could not be uploaded"
})
}
let user = req.profile
user = extend(user, fields)
user.updated = Date.now()
if(files.photo){
user.photo.data = fs.readFileSync(files.photo.path)
user.photo.contentType = files.photo.type
}
try {
await user.save()
user.hashed_password = undefined
user.salt = undefined
res.json(user)
} catch (err) {
console.log(err)
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
})
}
This isn't a production level application, just for me learning how to do this from scratch (without CRA, and all contained in one project using SSR)
EDIT: After some digging, console.logs and console.dirs, I discovered that the updates passed from the component aren't even being passed to the controller. The stale data (from the database) are logging, but req.profile is completely empty. I may re-visit this code completely and make some major changes to it.. All part of learning, right?
Here are the auth methods that were requested (I'm using Session Storage for now, but that may change to localStorage):
import User from '../models/user.model'
import jwt from 'jsonwebtoken'
import expressJwt from 'express-jwt'
import config from './../../config/config'
const signin = async (req, res) => {
try {
let user = await User.findOne({email: req.body.email})
if (!user) {
return res.status(401).json({error: "User not found"})
}
if (!user.authenticate(req.body.password)) {
return res.status(401).send({error: "Email and Password do not match"})
}
const token = jwt.sign({_id: user._id}, config.jwtSecret)
res.cookie('t', token, {expire: new Date() + 9999})
return res.json({
token,
user: {
_id: user._id,
name: user.name,
email: user.email
}
})
} catch (err) {
return res.status(401).json({error: "Could not sign in"})
}
}
const signout = (req, res) => {
res.clearCookie('t')
return res.status(200).json({message: "Signed out"})
}
const requireSignin = expressJwt({
secret: config.jwtSecret,
algorithms: ['sha1', 'RS256', 'HS256'],
userProperty: 'auth'
})
const hasAuthorization = (req, res, next) => {
const authorized = req.profile && req.auth
&& req.profile._id == req.auth._id
if (!(authorized)) {
return res.status(403).json ({error: "User is not authorized"})
}
next()
}
export default {
signin,
signout,
requireSignin,
hasAuthorization
}
Possible places where you could have a mistake: (code is not shown)
If your req.profile isn't a mongoose object, this won't work
let user = req.profile
From your other posts, I think you're probably getting req.profile from your jwt. That means this is not a mongoose object. What you'll need to do is either:
As you mentioned, use findByIdAndUpdate passing the id and the object to be updated. Note that if you have a mongoose middleware for save it won't run here
Do a user = await User.findById(id), update the user as you see fit, then use user.save. This gives you a bit more control over it, but runs 2 operations.
This has been solved.. My issue was apparently with the form not passing the request body properly to the API, which was caused by a faulty install of a dependency. Once I got that solved, the rest fell into place, and I can now do what I need to do with ease..
Thank you all who attempted to troubleshoot this with me.
i am working on api with express js, in my api call i called 2 functions, first is login() and other function is get_organizations(), but get_organization() called without complete of login() function, i have used async await but it is not working properly, can anyone please help me to resolve this issue ? I have added my whole code here ,
router.get('/', async (req, res) => {
let token = await login();
await get_organizations(token);
});
const get_organizations = async function (api_token) {
try {
console.log('Get List Of Organizations');
console.log('Verifying token');
let verify_token_data = await jwt.verify(api_token, config['token-secret']);
console.log(verify_token_data);
return false;
} catch (error) {
console.log(error);
}
}
const login = async function () {
try {
console.log('Login process started');
const newToken = await jwt.sign({login:'login'},config['token-secret'],{ expiresIn: config['token-expires']});
let username = 'root_admin'
let password = 'Admin123';
let token = String(cryptojs.lib.WordArray.random(20));
console.log("token : "+token);
await connection.query('SELECT * FROM users where username = ? ',[username], async function(err, rows) {
if (err) {
console.log("Looged out failed");
} else {
const user = rows[0];
console.log("psdsdsd");
if(bcrypt.compareSync(password,user.passwordHash)) {
await connection.query('SELECT * FROM organizations where id = ? ',[user.organizationId], async function(err, org_data) {
if (err) {
console.log("Looged out failed");
} else {
console.log("sdsd");
//console.log(org_data);
if(typeof org_data.name!='undefined') {
organization = org_data.name;
} else {
organization = 'VeriCurious';
}
//console.log(organization);
// create a token
const token = await jwt.sign({ id: user.id, username: user.username, organizationId: user.organizationId, organization: organization}, config['token-secret'], {
expiresIn: config['token-expires'] // expires in 30 minutes
});
console.log("Successfull loggedin");
console.log("New generated token : "+token);
return token;
}
});
}
}
});
} catch (error) {
console.log(error);
}
}
When you use await when invoking a function, you're basically waiting for a promise inside that function to resolve. The invoked function is intended to return that promise.
In your code, the login function does invoke connection.query, but there isn't any promise that waits for the query to resolve.
In order to get await to really wait for connection.query, you need to return a Promise which resolves whenever the user finally logs in - i.e. you have the token:
const login = async function () {
try {
console.log('Login process started');
const newToken = await jwt.sign({login:'login'},config['token-secret'],{ expiresIn: config['token-expires']});
let username = 'root_admin'
let password = 'Admin123';
let token = String(cryptojs.lib.WordArray.random(20));
console.log("token : "+token);
return new Promise(function(resolve, reject){
connection.query('SELECT * FROM users where username = ? ',[username], async function(err, rows) { // await won't do anything here,
// you should only use await with functions that return promises.
if (err) {
console.log("Looged out failed");
throw new Error(err);
} else {
const user = rows[0];
console.log("psdsdsd");
if(bcrypt.compareSync(password,user.passwordHash)) {
await connection.query('SELECT * FROM organizations where id = ? ',[user.organizationId], async function(err, org_data) {
if (err) {
console.log("Looged out failed");
throw new Error(err);
} else {
console.log("sdsd");
//console.log(org_data);
if(typeof org_data.name!='undefined') {
organization = org_data.name;
} else {
organization = 'VeriCurious';
}
//console.log(organization);
// create a token
const token = await jwt.sign({ id: user.id, username: user.username, organizationId: user.organizationId, organization: organization}, config['token-secret'], {
expiresIn: config['token-expires'] // expires in 30 minutes
});
console.log("Successfull loggedin");
console.log("New generated token : "+token);
resolve(token); // this signals the Promise to resolve.
// return token;
}
});
}
}
});
});
} catch (error) {
console.log(error);
}
}
Some things to note:
Await is intended to work with promises. Asynchronous functions in javascript, either accept a callback or return a promise. connection.query takes a callback, so await is useless there.
Chances are that the module your using to talk to your database -mongoose?- has a promisified API. Check it out, because if you're willing to use async/await it is better to work directly with Promises rather than wrapping code in a new Promise.
For instance, if connection.query returned a Promise, you could do something like:
const login = async function () {
// skipped a lot of code and logic since this is an example
const rows = await connection.query('SELECT * FROM users where username = ? ',[username]);
const user = rows[0];
const org_data = await connection.query('SELECT * FROM organizations where id = ? ',[user.organizationId]);
const organization = org_data.name;
return await jwt.sign({ id: user.id, username: user.username, organizationId: user.organizationId, organization: organization}, config['token-secret'], {
expiresIn: config['token-expires'] // expires in 30 minutes
});
}
And handling errors is really simple.
When you get an error un a callback inside an async function, and you're returning a new Promise -like in my example- I don't really know if is better to reject or to throw the error. I think both will do the same but I'm not sure.
I try the response model after create data but it doesn't work. It shows data on "console.log" and it didn't respond when I use "resolve({})".
In the routers.js:
const register = require('./functions/register');
module.exports = router => {
router.get('/', (req, res) => res.end('Welcome to Idol Fan With your Idol !'));
//======REGISTER & LOGIN WITH SOCIAL =====
router.post('/socialuser', (req, res) => {
const social_id = req.body.social_id;
const token = req.body.token;
const name = req.body.name;
const email = req.body.email;
const photoprofile = req.body.photoprofile;
const tokenfirebase = req.body.tokenfirebase;
if (!social_id) {
res.status(400).json({message: 'Invalid Request !'});
} else {
register.registerUser(social_id, name, email, photoprofile, token, tokenfirebase)
.then(result => {
res.status(result.status).json({status: result.status, message: result.message, user: result.user})
})
.catch(err => res.status(err.status).json({message: err.message}));
}
});
}
Function Register.js:
const userfan = require('../models/user');
exports.registerUser = (social_id, name, email, photoprofile, token,
tokenfirebase) =>
new Promise((resolve, reject) => {
const d = new Date();
const timeStamp = d.getTime();
userfan.find({social_id: social_id})
.then(users => {
if (users.length == 0) {
let newUser = new userfan({
social_id: social_id,
name: name,
email: email,
photoprofile: photoprofile,
token: token,
tokenfirebase: tokenfirebase,
created_at: timeStamp
});
newUser.save()
.then(doc => {
console.log("run... " + doc);
resolve({
status: 200,
message: 'User Register Sucessfully !',
user: doc
});
})
.catch(err => {
console.error(err)
if (err.code == 11000) {
reject({status: 409, message: 'User Already Registered !'});
} else {
reject({status: 500, message: 'Internal Server Error !'});
}
});
} else {
return users[0];
}
})
.then(usertemp => resolve({status: 200, message: "Login Successfully !", user: usertemp}))
.catch(err => {
console.log(err.message);
reject({status: 500, message: err.message});
});
});
This is my result after run on server:
As a result and code above. I have a question Why "user: doc" no response?. Thank you so much!
userfan.find.then.then (synchronous since nothing requires waiting) is called before newUser.save.then (asynchronous since under the hood it waits for the DB to answer).
So both resolve are called, but only the first call is considered, and the first one to be called is the one using usertemp. And this one receives undefined as argument, because of the implicit return undefined at the end of userfan.find.then.
Your flow should be:
userfan.find().then(users => {
if (!users.length) {
let newUser = ...
// explicitly return the promise, which will give the created user
return newUser.save().then(doc => {
// format and return the value you want
return {user: doc, message: 'registered'};
});
} else {
// another explicitly returned value, but you already have this
return {user: users[0], message: 'login'};
}
// it's not possible here because we returned before it, but your code reached this point
// and, implicitly, any function ending with no return does:
return undefined;
// this .then receives *either* the promise from newUser.save *or* the object from the else block
}).then(structure => {
structure.status = 200;
return structure; // here structure is {status: 200, message: 'registered'|'login', user: document}
});
Also, note that using the syntax shortcut (without curly braces around the function body) for arrow functions implies the one-line body is returned:
singleArgument => doSomething();
// is actually *strictly* equivalent to
(singleArgument) => { return doSomething(); }
With these ways of writing, it's easy to lose the reflex of writing return when it's needed.
I am creating a results object to return a boolean and a string. it is not being reassigned within the if statement. The rest of the code is working correctly and the password gets updated or the right error message is output to the console
i've tried leaving result undefined before the try catch.
async function passwordUpdate(password, currentPassword, newPwd, email) {
let hashedPassword = await bcrypt.hash(newPwd, 10);
let result = { success: false , message: ' '};
try {
bcrypt.compare(currentPassword, password, async function (err, res) {
if (res) {
let updateResult = await updatePwd(hashedPassword, email);
if (updateResult) {
result = { success: true , message: 'Password was updated successfully.'};
}
else {
logger.info('Password was not updated successfully.');
}
} else {
logger.error('Passwords do not match');
result= { success: false , message: 'Your current password was entered incorrectly'};
logger.error(result.message);
}
});
} catch (error) {
result= { success: false , message: 'Failed to compare passwords'}
}
logger.error('result ', result.message);
return result;
}
code is being called by this method
app.post('/passwordUpdate', async (req, res) => {
let pwd = req.body.password;
let cpwd = req.body.currentPwd;
let newPwd = req.body.newPwd;
let email = req.body.email;
try {
let result = await usersModel.passwordUpdate(pwd, cpwd, newPwd, email);
console.log(result, result.success, result.message);
if (result.success) {
res.status(200).json({error: result.message});
}
else {
res.status(404).json({error: result.message});
}
} catch (error) {
console.log(error);
}
});
logger.error(result.message); this line within the else statement is outputting the message as expected but
logger.error('result ', result.message); after the try/catch is outputting a blank message for result.message
When you're doing this:
let result = await usersModel.passwordUpdate(pwd, cpwd, newPwd, email);
The passwordUpdate function is resolving the promise based on what is in that function's "top level". This means that the callback function of bcrypt.compare doesn't affect the return of passwordUpdate which is why you're not seeing the result you're looking for.
What you can do is wrap the entire thing in a promise and call the resolve/reject inside the bcrypt.compare function.
async function passwordUpdate(password, currentPassword, newPwd, email) {
return new Promise(async function(resolve, reject) {
let hashedPassword = await bcrypt.hash(newPwd, 10)
try {
bcrypt.compare(currentPassword, password, async function(err, res) {
if (res) {
let updateResult = await updatePwd(hashedPassword, email)
if (updateResult) {
resolve({
success: true,
message: 'Password was updated successfully.',
})
} else {
reject({
success: false,
message: 'Password was not updated successfully.',
})
}
} else {
reject({
success: false,
message: 'Your current password was entered incorrectly',
})
}
})
} catch (error) {
reject({ success: false, message: 'Failed to compare passwords' })
}
})
}
You'll also notice I removed the logging, you can put these back if you wish but since this is a promise you can log your errors more centrally from the caller in the .then and .catch or try/catch if you're using async/await.
Also may I suggest that since you'll be able to determine whether it's an error or not based on the resolve and reject, that you can remove the success from the result and only return a string, it'll make the code cleaner:
async function passwordUpdate(password, currentPassword, newPwd, email) {
return new Promise(async function(resolve, reject) {
const hashedPassword = await bcrypt.hash(newPwd, 10)
try {
bcrypt.compare(currentPassword, password, async function(err, res) {
if (res) {
const updateResult = await updatePwd(hashedPassword, email)
if (updateResult) {
resolve('Password was updated successfully.')
} else {
reject('Password was not updated successfully.')
}
} else {
reject('Your current password was entered incorrectly')
}
})
} catch (error) {
reject('Failed to compare passwords')
}
})
}
PS: I didn't test the code pasted above, I only modified your code to better explain it.