I have been designing a web app in node.js with express and mongoDB, and it just occurred to me that any variables that I declare within the script will be accessible to all users because node runs as a single thread. For example, I am using a server-side form validator, here is a piece of it:
app.post('/purchase', requireLogin, function(req, res) {
var b = req.body;
var ee;
for (i in b) {
if (!validatePresenceOf(b[i])) {
var ee="Please fill out all fields.<br />\n";
}
}
var exp = b.exp_mm+"/"+b.exp_yy;
var d = /^(0[1-9]|1[012])[- /.]\d\d$/
if (!d.test(expiration)) {
ee+="Expiration date is invalid.<br />\n"
}
if (!isValidCreditCard(b.card_type, b.card_num)) {
ee+="Credit card number is invalid.<br />\n";
}
});
I am wondering if another user makes a purchase at almost the same time, could variable b be redefined by a second request before the validator finishes? If it can, then what would be the best way around this, and will this happen every time I declare a variable? It seems like this could cause some security issues in case a variable is changed before a process is completed.
Thanks!
No, that variable won’t be shared because it will still have lexical scope only to the process operating because of function closure.
The fact that you’re declaring it with
var bwithin the function defines it to have that lexical scoping.