I've got a single page which is an account settings page. In it, I allow my users to update their avatar (if they've attached an image), change their email (if it has been changed from the original), and change their name and password.
Right now, I'm using async's waterfall method, but am swapping out async for Q since I prefer the syntax (and api). I'm wondering if this is the way that I should be using Q in replacement of async's waterfall.
I'm doing something like this:
exports.settingsAccountPOST = function(req, res) {
var doesEmailExist = function() {
var deferred = Q.defer();
User.findByEmail({
email: req.body.email
}, function(err, user) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(user);
}
});
return deferred.promise;
};
var updateEmail = function(email) {
var deferred = Q.defer();
User.updateEmail({
userId : req.session.user.id,
email : req.body.email
}, function(err, updated) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(updated);
}
});
return deferred.promise;
};
var updateName = function() {
var deferred = Q.defer();
if (req.body.name) {
User.updateName({
userId: req.session.user.id,
name: req.body.name
}, function(err, updated) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(updated);
}
});
return deferred.promise;
}
};
doesEmailExist().then(function(email) {
if (!email) {
return(updateEmail(email));
}
}).then(function() {
return(updateName())
}).then(function() {
res.redirect('/account')
});
};
Say that there is an error with the email address being used. Is there a way to "pass" it to the final call? Use case: Updated password properly, but email update didn't work, so I want to show a session flash to the user telling them they updated their password properly, but there was an issue with updating their email.
I was looking in the docs and it seems I may need to use:
.fin(function () {
});
Is this correct? If so, what should I be passing into that? Just push to an object the error that occurred within the chain and then loop through all errors and display them to the user? Or just return immediately and display the error?
If you are using Q.defer you are generally doing something wrong.
var findByEmail = Q.nbind(User.findByEmail, User);
var updateEmail = Q.nbind(User.updateEmail, User);
var updateName = Q.nbind(User.updateName, User);
//later on...
exports.settingsAccountPOST = function (req, res) {
findByEmail({
email: req.body.email
})
.then(function (user) {
if (!user) {
return updateEmail({
userId: req.session.user.id,
email: req.body.email
});
}
})
.then(function () {
return updateName({
userId: req.session.user.id,
name: req.body.name
})
})
.then(function () {
res.redirect("/account");
})
.catch(function(e){
//Handle any error
});
};
Related
I have a register function on my site to basically create a new document with the users credentials. Here is my implementation, with data being literally the input fields of username / password stored in an object:
let users = db.collection('users');
let query = sanitize(data);
users.findOne({username: query.username}).then(res=>{
if (res){
socket.emit('usercreated', {
msg: `User: ${query.username} already exists.`
});
return;
}
const h = query.username + query.password;
bcrypt.hash(h, 13, (err, hash)=>{
users.insert({username: query.username, password: hash}, (err, user)=>{
if (err){
socket.emit('usercreated', {
msg: `DB is having issues. Please contact admin.`
});
return;
}
socket.emit('usercreated', {
msg: `User ${query.username} has been created.`
});
});
});
})
The problem is that if the user spams submit for username / password, the res isn't seeing that the user already exists yet because the bcrypt.hash function literally takes a second to resolve.
I have tried also this method too to check res after bcrypt has done its work, but this isn't working either:
let users = db.collection('users');
let query = sanitize(data);
users.findOne({username: query.username}).then(res=>{
const h = query.username + query.password;
bcrypt.hash(h, 13, (err, hash)=>{
if (res){
socket.emit('usercreated', {
msg: `User: ${query.username} already exists.`
});
return;
}
users.insert({username: query.username, password: hash}, (err, user)=>{
if (err){
socket.emit('usercreated', {
msg: `DB is having issues. Please contact admin.`
});
return;
}
socket.emit('usercreated', {
msg: `User ${query.username} has been created.`
});
});
});
})
What is a good way to check if the user already exists properly before making the insertion occur?
The issue is not that bcrypt.hash takes 1 sec to resolve but the way you are handling things.
In case of spamming, this is a classic readers-writters problem, though there are many ways but IMHO simple modification of mutex locks will work just fine.
class NamedLocks {
constructor() {
this._pid = {};
}
acquire(pid) {
if (this._pid[pid]) {
// process is locked
// handle it
return Promise.reject();
}
this._pid[pid] = true;
return Promise.resolve();
}
release(pid) {
this._pid[pid] = false;
}
}
let users = db.collection('users');
let query = sanitize(data);
const userLocks = new NamedLocks();
userLocks.acquire(query.username).then(() => {
users.findOne({
username: query.username
}).then(res => {
const h = query.username + query.password;
bcrypt.hash(h, 13, (err, hash) => {
if (res) {
socket.emit('usercreated', {
msg: `User: ${query.username} already exists.`
});
return;
}
users.insert({
username: query.username,
password: hash
}, (err, user) => {
if (err) {
socket.emit('usercreated', {
msg: `DB is having issues. Please contact admin.`
});
return;
}
socket.emit('usercreated', {
msg: `User ${query.username} has been created.`
});
userLocks.release(query.username);
});
});
})
}).catch((e) => {
// handle spamming
})
Sounds like you need to have throttling on the function that gets called from hitting submit on the page. Function throttling makes it so the function can only be called once in a set time period. So, say you specify a timeout of 1 second, if a user spams the button only the first call will go through and all subsequent calls for the next second will be ignored. Underscore.js has a _.throttle function you can use or you can look at their implementation and make a version for yourself.
I found answer. I must encrypt the password first, then check after that if the user exists.
let users = db.collection('users');
let query = sanitize(data);
const h = query.username + query.password;
bcrypt.hash(h, 13, (err, hash)=>{
users.findOne({username: query.username}).then(res=>{
if (res){
socket.emit('usercreated', {
msg: `User: ${query.username} already exists.`
});
return;
}
users.insert({username: query.username, password: hash}, (err, user)=>{
if (err){
socket.emit('usercreated', {
msg: `DB is having issues. Please contact admin.`
});
return;
}
socket.emit('usercreated', {
msg: `User ${query.username} has been created.`
});
});
});
});
I want to create API that allow other app to insert(create) new data. But so far I tried, this not work with error message "User id is required", I know that happen because no login user found when insert new data. Is it possible to insert new data without login or any possible way to login from server side if using accounts-password's package or any possible way to make this work?
code on server
Picker.route('/createFood/:title', function(params, req, res, next) {
console.log('-> params : ',params);
let username = (new Date()).getTime().toString();
function createFood() {
Fiber(function() {
console.log("-> username : ",username);
let acc = Accounts.createUser({
username: username,
email: username +'#foodie.com',
password: username
});
if (acc) {
console.log("-> acc : ",acc);
// Meteor.call("setUserId", acc);
Menus.insert({
title: params.title,
}, function(err, foodId) {
console.log("-> abs : ",Meteor.absoluteUrl());
console.log("-> err : ",err.message);
console.log("-> foodId : ",foodId);
let code, result;
if (err) {
code = 500;
result = {
error: err.message
}
} else {
code = 200;
result = {
foodId: foodId,
}
}
res.setHeader( 'Content-Type', 'application/json' );
res.statusCode = code;
res.end( JSON.stringify( result ) );
})
}
}).run();
}
if (params.title)
createFood();
});
code food model, there is userId owner here
if (Meteor.isServer) {
Menus.allow({
insert: function() {
return true;
},
update: function() {
return true;
},
remove: function() {
return true;
},
fetch: ['foodId'],
});
Menus.after.insert((userId, doc) => {
....
})
}
There is no reason why you can't insert to the database without logging in. You don't even have to include the accounts package if you don't want to .
Your current code doesn't insert unless a user is present, you can simplify it to this...
function createFood() {
Menus.insert({
title: params.title,
I have a route that allows a user to reset their password by sending them an email. Standard procedure for most websites. In this route, I import the async npm module and use the waterfall method so that I can handle the asynchronous nature of multiple functions. I'm still having a bit of trouble understanding promises, but I'm trying to replace waterfall with a promise or promise chain.
How could I refactor this route with a promise? Here are the steps contained in this route that is currently split up into 4 functions with waterfall.
First the route creates a reset token
Search for user based on email
2.5. If user is found, save user, otherwise return 404
Send email to user containing a reset url
Return a status of 200.
app.post('/forgotPassword', function(req, res, next) {
waterfall([
// generate reset token
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
// search for user with the given email
User.findOne({ email: req.body.email }, function(err, user) {
// check to see if the user exists
if (!user) {
// user doesn't exist in database
return res.status(404).send();
}
// user exists, assign token with expiration date
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour from now
// save the user model with the newly added
// token and expiration date
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'SendGrid',
auth: {
user: config.sendgridUser,
pass: config.sendgridPassword
}
});
var mailOptions = {
to: user.email,
from: 'email#school.edu',
subject: 'Password Reset',
text: `Hello etc etc`,
smtpTransport.sendMail(mailOptions, function(err) {
done(err, 'done');
});
}],
function(err) {
// handle error
if (err) return next(err);
res.status(200).send();
});
}); // end POST route '/forgotPassword'
Promise is a very powerful tool. It can be hard to understand it at the beginning, but totally worth the effort! Please let me know if you have any doubts :)
app.post('/forgotPassword', function(req, res, next)
{
new Promise((resolve, reject) =>
{
// generate reset token
crypto.randomBytes(20, (err, buf) =>
{
if(err)
return reject(err);
const token = buf.toString('hex');
resolve(token);
});
})
.then((token) =>
{
return new Promise((resolve, reject) => {
// search for user with the given email
User.findOne({ email: req.body.email }, (err, user) =>
{
if (!user)
return reject(404);
// user exists, assign token with expiration date
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour from now
// save the user model with the newly added
// token and expiration date
user.save(function(err) {
if(err)
return reject(err);
resolve(user);
});
});
});
})
.then((user) =>
{
return new Promise((resolve, reject) =>
{
const smtpTransport = nodemailer.createTransport('SMTP',
{
service: 'SendGrid',
auth: {
user: config.sendgridUser,
pass: config.sendgridPassword
}
});
const mailOptions = {
to: user.email,
from: 'email#school.edu',
subject: 'Password Reset',
text: `Hello etc etc`
};
smtpTransport.sendMail(mailOptions, (err) =>
{
if(err)
return reject(err);
resolve();
});
});
})
.then(() => res.sendStatus(200))
.catch((err) =>
{
//check if the error is the one from the DB where the user was not found
if(err == 404) {
return res.sendStatus(404);
}
return res.status(500).send(err);
});
});
bluebird is one of the most popular promise library.
and it offers promisify function to convert callback hell to promise.
please read this document and play with it.
http://bluebirdjs.com/docs/working-with-callbacks.html
This answer presumes 4 completely sequential steps:
(Function () {
Return Promise (function (resolve, promise) {
// try to do some stuff
if (success) {
Resolve ("pass this value on to next link in the chain");
}
Reject();
})()
.then (function (value) {
// do next step
Return "pass this value on to next link in the chain";
.then (function (value) {
// do next step
Return "pass this value on to next link in the chain";
.catch (function (error) {
// handle any reject or any error in the chain
}
You could in relation to the individual .then also choose to return a Promise. Beware: any errors in the .catch block will be swallowed.
This is just an example with ES6 promise but working code. You can refactor it further to have a clear reusable code. You can replace ES5 functions with ES6 arrow functions.
app.post('/forgotPassword', function(req, res, next) {
var catch = function(err){
return next(err);
}:
var error404 = function(){
return res.status(404).send();
};
var success = function(){
return res.status(200).send();
};
var step1 = new Promise(function(resolve, reject){
crypto.randomBytes(20, function(err, buf) {
if(err){
reject(err);
} else {
var token = buf.toString('hex');
resolve(token);
}
});
});
var step2 = function(token) {
// search for user with the given email
User.findOne({ email: req.body.email }, function(err, user) {
// check to see if the user exists
if (!user) {
// user doesn't exist in database
return {error404: true};
}
// user exists, assign token with expiration date
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour from now
// save the user model with the newly added
// token and expiration date
user.save(function(err) {
return { error: err, token: token, user: user });
});
});
};
var step3 = function(obj) {
if(obj.error){
return catch(obj.error);
} else if(obj.error404) {
return error404();
} else {
var token = obj.token, user = obj.user;
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'SendGrid',
auth: {
user: config.sendgridUser,
pass: config.sendgridPassword
}
});
var mailOptions = {
to: user.email,
from: 'email#school.edu',
subject: 'Password Reset',
text: `Hello etc etc`,
smtpTransport.sendMail(mailOptions, function(err) {
if(err){
return catch(err);
} else {
return success();
}
});
}
};
step1.then(step2, catch).then(step3);
}); // end POST route '/forgotPassword'
Promises work best when you're dealing with a library where methods already return them, or a library like bluebird that lets you promisify existing callback APIs, otherwise it's a lot of conversions.
If you're still set on refactoring with plain es6, put your promise-wrappers at the lowest possible level, for best effect and cleanest error handling, basically promisify manually:
let convert = (resolve, reject) => (err, res) => err ? reject(err) : resolve(res);
crypto.randomBytesAsync = n=>new Promise((y,n)=>crypto.randomBytes(n,convert(y,n)));
User.findOneAsync = u => new Promise((y, n) => User.findOne(u, convert(y, n)));
User.prototype.saveAsync = () => new Promise((y, n) => this.save(convert(y, n)));
Then use them like this:
app.post('/forgotPassword', function(req, res, next) {
crypto.randomBytesAsync(20).then(buf => {
var token = buf.toString('hex');
// search for user with the given email
return User.findOneAsync({ email: req.body.email }).then(user => {
// check to see if the user exists
if (!user) {
// user doesn't exist in database
res.status(404).send();
throw;
}
// user exists, assign token with expiration date
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour from now
// save the user model with the newly added
// token and expiration date
return user.saveAsync().then(() => {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'SendGrid',
auth: { user: config.sendgridUser, pass: config.sendgridPassword }
});
smtpTransport.sendMailAsync =
o => new Promise((y, n) => smtpTransport.sendMail(o, convert(y, n)));
return smtpTransport.sendMailAsync({
to: user.email,
from: 'email#school.edu',
subject: 'Password Reset',
text: `Hello etc etc`,
});
});
})
})
.then(() => res.status(200).send())
.catch(err => next(err));
}); // end POST route '/forgotPassword'
I have a module User - like this:
module.exports = User = (function() {
function User(params) {
this.id = params.id;
this.first_name = params.first_name || '';
this.last_name = params.last_name || '';
this.username = params.username;
this.email = params.email;
this.password = params.password;
};
User.findByUsername = function(username, callback) {
if (!_.isEmpty(username)) {
var opts = {table: TABLE, where: {sql: "username='"+username+"'"}};
QueryDispatcher.findWhere(opts, function(err, result) {
if(!_.isEmpty(err)) { return callback(err, null)}
callback(null, result.rows[0]);
});
};
};
return User;
};
The function that uses the class method:
module.exports = AuthStrategies = (function() {
AuthStrategies.localStrategy = function(username, password, done) {
async.waterfall([
function(callback) {
User.findByUsername(username, function(err, user){
if (err) { callback(err) };
if (_.isEmpty(user)) {
callback(null, false, { message: 'Incorrect username.' });
};
callback(null, user, null)
});
},
function(user, opts, callback) {
"do something here and call the next callback"
}]
, function(err, user, opts) {
if(err) { return done(err)}
if(!user) { return done(null, false, opts.message)}
done(null, user)
});
};
return AuthStrategies;
})();
I have my jasmine test -
var Auth = require('path to AuthStrategies module')
describe('Auth', function() {
describe('#AuthStrategies.localStrategy', function() {
describe('when user creds are valid', function() {
var test_user;
beforeEach(function(){
test_user = new User({
username: 'test996'
, password: 'password123'
, email: 'testemamil#email.com'
, first_name: ''
, last_name: ''
});
spyOn(User, "findByUsername").and.callFake(function(usrename, cb) {
cb(null, test_user);
});
});
it('returns user object', function(done) {
Auth.localStrategy('test996', 'password123', function(err, user, opts) {
expect(err).toEqual(null);
expect(user).toEqual(test_user);
done()
})
});
});
});
});
Essentially I want to stub out the User Class method findByUsername and fake the callback with my own results i.e nul error and a user(as if the find was successfully).
I have Spy on many "class" methods in my app and don't have this problem. This is baffling me a bit. The error only shows when I add .and.callThrough or .and.callFake to the spy.. the moment I remove this the test just times out ...which makes sense as the spy works and doesn't call the callback needed for the async waterfall to continue.
The error I am getting is -
So I figured it out -
The error you see above happens anyway. The reason I was getting the above "extra info" which was throwing me off btw - Was because I was running the test separately.
./node_modules/.bin/jasmine ./tests_to_run_spec.js
What would normal happen - is I would get a timeout failure due to a missing callback. as in my case above I wasn't calling the callback in the faked function I sup[plied properly.
actually even more interestingly - running jasmine-node from my PATH doesn't like the .and.... being called on this particular spy. Really have no idea. but that how I got the spyOn(User, 'findByUsername').and.callFake ... to work
I'm using NodeJS, with bcrypt-nodejs (https://github.com/shaneGirish/bcrypt-nodejs) and Bluebird for promises. Came up with this code and been wondering if there is better way to do the same thing. I have module with:
var Promise = require("bluebird"),
bcrypt = Promise.promisifyAll(require('bcrypt-nodejs'));
// ....[some othe code here]
Users.prototype.setPassword = function(user) {
return bcrypt.genSaltAsync(10).then(function(result) {
return bcrypt.hashAsync(user.password, result);
});
};
then from another module I call users.setPassword as below:
app.post('/api/v1/users/set-password', function(req, res, next) {
users.setPassword(req.body).then(function(result) {
// Store hash in your password DB.
console.log(result[1]);
res.json({
success: true
})
})
.catch(function(err) {
console.log(err);
});
});
It always ends up with "[Error: No callback function was given.]" message as bcrypt.hashAsync seems to require 4 parameters. Original, non-promisified hash method requires 3 only though. When I add empty callback to hashAsync, it works fine:
Users.prototype.setPassword = function(user) {
return bcrypt.genSaltAsync(10).then(function(result) {
return bcrypt.hashAsync(user.password, result,function() {});
});
};
Is there any better way to do this, without providing empty callback as above?
EDIT:
In response to Bergi's comment.. the function will set password eventually, I just didn't get that far when posted the question. Now got this far, please let me know if something is not quite right though:
Users.prototype.setPassword = function(user) {
return bcrypt.genSaltAsync(10).then(function(result) {
return bcrypt.hashAsync(user.password, result, null);
})
.then(function(result) {
// store in database
console.log("stored in database!");
return result;
});
};
bcrypt.hashAsync seems to require 4 parameters. Original, non-promisified hash method requires 3 only though.
It's the other way round rather. From the docs:
hash(data, salt, progress, cb)
data - [REQUIRED] - the data to be encrypted.
salt - [REQUIRED] - the salt to be used to hash the password.
progress - a callback to be called during the hash calculation to signify progress
callback - [REQUIRED] - a callback to be fired once the data has been encrypted.
The original method took 4 arguments, hashAsync will take 3 and return a promise.
However, in your code you were only passing two. You don't need to pass an empty function though, that the parameter is not [REQUIRED] means you can pass null (or any other falsy value) for it. bcrypt will create such an empty function itself. So use
function (data) {
return bcrypt.genSaltAsync(10).then(function(result) {
return bcrypt.hashAsync(data.password, result, null);
});
}
This is my promisified bcrypt from a project I did a while back. Bluebird isn't really necessary for such a small, simple library.
module.exports = {
makeUser: function(username, password){
return new Promise(function(resolve, reject) {
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(password, salt, null, function(err, hash) {
if (err) {
console.log("hashing the password failed, see user.js " + err);
reject(err);
}
else {
console.log("hash was successful.");
resolve(hash);
}
})
})
})
.then(function(hash){
return db.createUser(username, hash)
})
},
login: function(username, password){
return db.userFind(username)
.then(function(userObj){
if(!userObj){
console.log("did not find " + username + " in database.");
return new Promise(function(resolve, reject){
resolve({login:false, message:"Your username and/or password are incorrect."})
}
}
else {
console.log("found user: " + userObj._id, userObj);
return new Promise(function(resolve, reject){
bcrypt.compare(password, userObj.hashword, function(err, bool) {
resolve({bool:bool,
user:userObj._id,
mindSeal: userObj
})
})
})
}
})
}
}
Example Usage:
app.post('/signup', function(req, res) {
var username = req.body.username;
var password = req.body.password;
var user = handler.userExists(username)
.then(function(answer){
if (answer !== null){
console.log(req.body.username + " was taken")
res.send({login: false, message: req.body.username + " is taken"});
return null;
} else if (answer === null) {
console.log("username not taken")
return handler.makeUser(username, password);
}
})
.catch(function(err){
console.log("error during user lookup:", err);
res.status(404).send({message:"database error:", error:err});
})
if (user !== null){
user
.then(function(x){
console.log("this is returned from handler.makeUser: ", x)
console.log(x.ops[0]._id)
req.session.user = x.ops[0]._id;
var mindSeal = {
userSettings: {
username: x.ops[0]._id,
newCardLimit: null,
tValDefault: 128000000,
lastEdit: req.body.time,
todayCounter: 0,
allTimeCounter: 0,
cScaleDefault: {0: 0.9, 1: 1.2, 2: 1.8, 3: 2.5},
accountMade: req.body.time
},
decks: {}
};
handler.setMindSeal(req.session.user, mindSeal, req.body.time);
res.send({
login: true,
mindSeal: mindSeal
});
})
.catch(function(error){
console.log("make user error: " + error);
res.status(401).send({message:"failed.",error:error,login:false});
})
}
});
app.post('/login', function(req, res) {
var username = req.body.username;
var password = req.body.password;
handler.login(username, password)
.then(function(obj){
if (obj.bool){
console.log("username and password are valid. login granted.");
req.session.user = obj.user;
console.log("obj is:", obj)
var mindSeal = {decks:obj.mindSeal.decks, userSettings:obj.mindSeal.userSettings};
console.log("mindSeal sending:", mindSeal);
res.status(200).send({
login: true,
message:"Login Successful",
mindSeal: obj.mindSeal
});
}
else {
console.log("password invalid")
res.status(401).send({login: false, message:"Your username and/or password are incorrect."})
}
})
.catch(function(error){
console.log(error);
res.status(404).send({message:"database error:", error:err});
})
});
conceptual example only; borrowed and slightly modified some old code of mine on the fly. Working code (I see things I'd like to improve in it now, but it works) here: https://github.com/finetype/mindseal/blob/master/server.js
Maybe you could use another bcrypt library, with a better API which removes the need for promises.
Users.prototype.setPassword = function(user) {
return TwinBcrypt.hashSync(user.password, 10);
};
Or, with progress tracking :
Users.prototype.setPassword = function(user) {
function progress(p) {
console.log( Math.floor(p*100) + '%' );
}
TwinBcrypt.hash(user.password, 10, progress, function(result) {
// store in database
console.log("stored in database!");
return result;
});
};