I am new to node.js and i am trying to create the reset password module for my app. I got stuck on a problem where I wanted to access the result outside of a query.
router.post('/forgot',(req,res)=>{
const db = require('../db.js');
if (req.body.email !== undefined) {
var emailAddress = req.body.email;
// TODO: Using email, find user from your database.
db.query('SELECT * FROM users WHERE email = ?',[emailAddress],(err,results,fields)=>{
if(err){
console.log('Error in pulling the information of the user from the database');
}
var userid = results[0].id;
console.log(userid);
});
var payload = {
id: userid, // User ID from database
email: emailAddress
};
console.log(payload);
} else {
res.send('Email address is missing.');
}
});
I want to get the value of userid which i got from my database and pass it to my outside variable payload and store it in the
id: userid
I did my research on other similar question but was not clear on this topic so any help will be highly appreciated. Thankyou
You're using a callback function here to get the result of your query, what this means is after the query is run it will go ahead and go through the function in the parameter the (err, results, fields) => { ... }, so you could either build your payload inside that callback function, where you would already have the userid on results[0].id or call another function inside that callback with the userid as a parameter.
Something like this
router.post('/forgot', (req, res) => {
const db = require('../db.js');
if (req.body.email !== undefined) {
var emailAddress = req.body.email;
// TODO: Using email, find user from your database.
db.query('SELECT * FROM users WHERE email = ?', [emailAddress], (err, results, fields) => {
if (err) {
console.log('Error in pulling the information of the user from the database');
}
var userid = results[0].id;
console.log(userid);
buildPayload(userid, emailAddress)
});
} else {
res.send('Email address is missing.');
}
});
buildPayload(userId, emailAddress) {
var payload = {
id: userId, // User ID from database
email: emailAddress
};
console.log(payload);
// whatever else you need to do
}
Related
I'm entering a password from front end inside MySQL for registered user. Now when im signing in I wish to compare the entered password with original stored password in database using bcrypt-nodejs. But unable to do so. Im a beginner at Node.js, please help !!
this code is in my server.js file which is the main node server file.
app.post('/signin', (req,res)=>{
const {email} = req.body;
let post= {email: email};
let sql= 'SELECT password FROM users WHERE email= ?';
let query= db.query(sql, post,(error,result)=>{
if(error)
{
throw error;
}
else if(!error)
{
bcrypt.hash(result, null,null, function(err,res){
});
bcrypt.compare(req.body.password, hash, (err,res)=>{
if(err)
{
throw error;
}
else if(res)
{
res.send('signin successful');
}
}
else {
res.status(400).json('error logging in');
}
//res.json('signin');
});
})
})
as you can see, Im trying to hash the result which is the password from the database and compare it with req.body.password which user enters from front end, but Im getting error in my console
Let's rewrite a little with async/await to make it more readable
app.post('/signin', async (req, res) => {
const { email } = req.body;
let post = { email: email };
let sql = 'SELECT password FROM users WHERE email= ?';
const queryResult = await new Promise(resolve => db.query(sql, post, (error, result) => resolve(result)));
// I assume you should access here your hash with something like this queryResult.password`
const hashStoredInDb = queryResult.password;
const compareResult = await new Promise(resolve => bcrypt.compare(req.body.password, hashStoredInDb, (err, res) => resolve(res)));
// Your other verification logic based on compare result.
})
So, the main logic is to compare hashed password already stored in db with provided from user.
Also, you could add some verifications in provided code, I've missed some try/catch for simplicity and readability.
I created a function to create a profile document, based on a schema, into mongoDB, which works so far:
const createUpdateProfile = (req, res) => {
let uuid = req.user.identities[0].id;
let provider = req.user.identities[0].provider;
let email = req.user.email;
let firstName = req.user.name.split(' ').slice(0, -1).join(' ');
let lastName = req.user.name.split(' ').slice(-1).join(' ');
let pictureUrl = req.user.picture;
let profileToSafe = new Profile({
uuid: uuid,
provider: provider,
email: email,
firstName: firstName,
lastName: lastName
});
const profile = Profile.findOne({ uuid });
if (profile !== null) {
profileToSafe.save();
}
res.status(200).send('successful operation');
}
I checked the DB and the document has been stored there.
But I cannot read it.
const getProfile = (req, res) => {
let uuid = req.user.identities[0].id;
Profile.findOne({ uuid: uuid }), function (obj) { console.log(obj) }, function (err) { console.log(err) };
res.status(200).send('successful operation');
}
There is simply no console log output. Not even a null or an error.
I did as mentioned here also I tried to console log findOne function but it returns kind of the whole database, including the authentication data.
You have close the parameter list to the findOne method too early in your second snippet.
Profile.findOne({ uuid: uuid }), function (obj) { console.log(obj) }, function (err) { console.log(err) };
should be
Profile.findOne({ uuid: uuid }, function (obj) { console.log(obj) }, function (err) { console.log(err) });
I am having trouble making the #PUT method for my application. So far, I managed to make the #GET, #POST and #DELETE. So after doing some research, it turns out that the #PUT is a mixture of my #GET and #POST.
My #GET (by cuid) method
export function getUser(req, res) {
// just get the user information
User.findOne({ cuid: req.params.cuid }).exec((err, user) => {
if (err) {
return res.status(500).send(err);
}
return res.json({ user });
});
}
My #POST method
export function addUser(req, res) {
// Check for empty fields
if (!req.body.user.firstName || !req.body.user.lastName ||
!req.body.user.email || !req.body.user.password ||
!req.body.user.studentId) {
return res.status(403).end();
}
const newUser = new User(req.body.user);
// Let's sanitize inputs
newUser.firstName = sanitizeHtml(newUser.firstName);
newUser.lastName = sanitizeHtml(newUser.lastName);
newUser.studentId = sanitizeHtml(newUser.studentId);
newUser.email = sanitizeHtml(newUser.email);
newUser.password = sha512(newUser.password).toString('hex');
newUser.cuid = cuid();
newUser.save((err, saved) => {
if (err) {
return res.status(500).send(err);
}
return res.json({ user: saved });
});
}
The req.body.user will be the same in the #PUT method as in the addUser function on the #POST. In other words, the req.body.user will be something like { firstname: 'assa', lastName: 'nen', email: 'ed#aid.com', password: 'ddee', student: 112 }
My question is how would you modify the specific user (by cuid) information and save it to the db? In other words, how would you write the #PUT method
Try findOneAndUpdate
export function updateUser(req, res) {
var userId = req.body.userId;
var conditions = {
_id : userId
}
var update = {
firstName = sanitizeHtml(req.body.firstName );
lastName = sanitizeHtml(req.body.lastName);
studentId = sanitizeHtml(req.body.studentId);
email = sanitizeHtml(req.body.email);
password = sha512(req.body.password).toString('hex');
}
model.findOneAndUpdate(conditions,update,function(error,result){
if(error){
// handle error
}else{
console.log(result);
}
});
}
I'm still very new to Node.js, and i'm trying to understand how callbacks work.
So, here is my problem :
I should've put more code :
POST :
app.post('/register', function(req, res) {
//get data from the request
var data = {
username: req.body.username,
email: req.body.email,
password: req.body.password
};
function fetchID(callback) {
connection.query('SELECT id_user FROM USERS WHERE username = ?', data.username, function(err, rows) {
if (err) {
callback(err, null);
} else
callback(null, rows[0].id_user);
});
}
var user_id;
fetchID(function(err, content) {
if (err) {
console.log(err);
return next("Mysql error, check your query");
} else {
user_id = content;
console.log(user_id); //undefined
}
});
console.log(user_id); //undefined
var payload = {
iss: req.hostname,
sub: user_id
}
console.log(payload.sub); //correct id
})
GET :
app.get('/todos', function(req, res) {
if (!req.headers.authorization) {
return res.status(401).send({
message: 'You are not authorized !'
});
}
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, "shhh..");
//additional level of security
console.log('sub id is : ' + payload.sub); //undefined
if (!payload.sub) {
return res.status(401).send({
message: 'Authentication failed !'
});
}
})
I commented each console.log to be more clear. I need to get the correct id when i check for if (!payload.sub) in app.get()
Your two functions should be something like -
function fetchID(data, callback) {
connection.query('SELECT id_user FROM USERS WHERE username = ?', data.username, function(err, rows) {
if (err) {
callback(err, null);
} else
callback(null, rows[0].id_user);
});
}
and then
var user_id;
fetchID(data, function(err, content) {
if (err) {
console.log(err);
// Do something with your error...
} else {
user_id = content;
}
});
Here in the callback function, the returned variable content will hold the value for user_id.
EDIT
I have not solved the exact problem as you had described above.
But in following example, I have shown that, the callback mechanism is working -
First (Table creation and insert some dummy data)-
use test;
create table users (id int(11) primary key,username varchar(100));
insert into users values(1, "John");
insert into users values(2, "Sham");
Now I have made your post method as get and tested in browser.
Following is the full class tested in my localhost -
var application_root = __dirname,
express = require("express"),
mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'admin',
database: "test"
});
app.get('/getuser', function(req, res) {
//get data from the request
var data = {
username: req.query.username
};
function fetchID(data, callback) {
connection.query('SELECT id FROM users WHERE username = ?',
data.username, function(err, rows) {
if (err) {
callback(err, null);
} else
callback(null, rows[0].id);
});
}
var user_id;
fetchID(data, function(err, content) {
if (err) {
console.log(err);
res.send(err);
// Do something with your error...
} else {
user_id = content;
console.log(user_id);
res.send("user id is -" + user_id);
}
});
})
app.listen(1212);
Now these requests will produce this output -
http://127.0.0.1:1212/getuser?username=john => user id is -1 and
http://127.0.0.1:1212/getuser?username=sham => user id is -2
Hope this code example will help you to understand the callback in node.js.
Thanks
1st post. I'm a student studying js and came across this problem with a callback that I'm not sure how to structure properly.
var bcrypt = require('bcrypt-nodejs');
var users = db.collection("users");
this.addUser = function(username, password, email, callback) {
"use strict";
// Generate password hash
var salt = bcrypt.genSaltSync();
var password_hash = bcrypt.hashSync(password, salt);
// Create user document
var user = {'_id': username, 'password': password_hash};
// Add email if set
if (email != "") {
user['email'] = email;
}
// NOT SURE What to write here
callback(Error("addUser Not Yet Implemented!"), null);
}
First of all: do not use sync methods if possible, use callbacks instead.
var bcrypt = require('bcrypt-nodejs');
var users = db.collection("users");
this.addUser = function(username, password, email, callback) {
"use strict";
// Generate password hash
bcrypt.genSalt(function(err, salt) {
if (err) {
callback(err);
return;
}
bcrypt.hash(password, salt, function(err, password_hash) {
if (err) {
callback(err);
return;
}
// Create user document
var user = {
'_id': username,
'password': password_hash
};
// Add email if set
if (email != "") {
user['email'] = email;
}
// NOT SURE What to write here
callback(null);
});
});
}
and please ask precise questions.
If I understand propperly, you dont know how to handle a callback?
you simply pass the function that will be called after all work in your function is done as the parameter callback. when your done, you call the callback with the wanted parameters.
here it's the err object in case of an error or null if there is no error.
If you want to pass your created user to the callback, just replace
callback(null); with callback(null, user);