My app is accessed exclusively through a link on a site that sends it the username of the current logged in user via POST data. The app then checks if either a. The username is present in the POST data (meaning they accessed it properly) or b. The URL is localhost (meaning I’m testing it in my local environment), as detailed in the code below:
var userName;
WebApp.connectHandlers.use(bodyParser.urlencoded({extended: false}));
WebApp.connectHandlers.use("/", async (req, res, next) => {
userName = req.body.user;
if (userName === undefined && (req.headers.host != "localhost:3000")) {
res.writeHead(403);
res.end();
return;
}
next();
});
This is done on my server-side .js file
Then on the same file I have this method declaration for returning the name of the user accessing the app, received above:
Meteor.methods({
getUser() {
if (userName === undefined) {
userName = 'Test User';
return userName;
}
return userName;
}
});
The ‘Test User’ should only be returned if I’m testing it, as otherwise the first code I listed would return a 403, correct?
In the client-side .js script, I have this at the beginning:
Meteor.call("getUser", function(error, result){
if(error){
console.log(error.reason);
return;
}
Session.set("username", result);
console.log(Session.get("username"));
});
This simply calls the getUser function defined on the server-side script, which I then use for the app.
However, once in a while (seemingly at random) I notice that when accessing the app properly (I even checked the POST field it’s sending from and my username is set correctly) it logs the username as ‘Test User’ but still lets me use the app. Shouldn’t the server code either log my name or deny me access, again referencing the first piece of code? Since ‘Test User’ means the username retrieved was undefined but the site is not localhost and thus returns a 403?
Any ideas on why this is the case? The only thing I can think of is perhaps the getUser method is being called before the POST data can be retrieved, but shouldn’t the async call with a callback ensure it to wait?