I working on a login/register system with Node based on the RethinkDB Chat example when I found that it doesn't check if the user exists with email or username something that's a problem. When I was looking to solve this I was not able to find out why because of running a database check would require a callback with a function something that makes it really hard to achieve.
if (typeof req.user !== 'undefined') {
res.redirect('/account');
return;
}
if (!validateEmail(req.param('email'))) {
req.flash('error', 'Not a valid email address!')
res.redirect('/register');
return;
}
// Add a check for EMAIL/USERNAME here.
if (req.param('password') !== req.param('password2')) {
req.flash('error', 'Passwords does not match!')
res.redirect('/register');
return;
}
What I need help with it to if a user exists with a username or mail that's equal with the one in the form it will send a:
if (alreadyExists) {
req.flash('error', 'That username/email is already in use.')
res.redirect('/register');
return;
}
So the main problem is I have to get to know if it exists in the same functions as the other ones and not in a callback. Any help is appreciated!
To check if a user with the given email address exists, you will have to do a check in your RethinkDB-database, which is asynchronous. This can not be achieved without a callback, but it's not that bad!
var r = require('rethinkdbdash')();
function getUserByEmailAddress(emailAddress) {
return r.db('test').table('user')
.getAll(emailAddress, {index: 'emailAddress'}).run();
}
app.post('/register', function(req, res) {
// User already has a session. Not allowed to log in.
if(req.user) {
return res.redirect('/account');
} else if(!validateEmail(req.body.emailAddress)) {
return res.status(500).send('Not a valid email address');
} else if(req.body.password !== req.body.password2) {
return res.status(500).send('Passwords do not match');
}
getUserByEmailAddress(req.body.emailAddress).then(function(user) {
if(user) {
res.status(500).send('User with given email address already exists');
} else {
// New email address! Encrypt password, add to db, etc.
}
})
}
Note that you will have to create a secondary index for this.
You should probably also consider posting the form with a POST-request instead of a GET-request.