Reputation: 195
I'm newish to NodeJS and ExpressJS and am trying to get the session management flow in main.js worked out.
What I currently have that's working:
app.get('*', function(req, res){
var page = getPage();
session_.initSession( req, res, function( ){
loggedIn = false;
if( req.session && typeof req.session.username !== "undefined" ){
loggedIn = true;
userFName = req.session.first_name;
userLName = req.session.last_name;
}
if( !loggedIn ){
res.render('pages/login', { message: "<div class='notice centered' style='width: 40%;'>Please login</div>" });
returnFlag = true;
return;
} else {
if (page.length < 1){
// render index page here ...
returnFlag = true;
return;
}
// render 'test' page
if( page == 'test' ){
// do test functions here...
returnFlag = true;
return;
}
}
});
if( returnFlag == true ){
return;
}
res.render('partials/home', { message: "404 not found (unknown page GET request)" });
return;
});
app.post('*', files, function(req, res){
var page = getPage();
if( page == 'test' ){
// do test functions here...
returnFlag = true;
return;
}
if( returnFlag == true ){
return;
}
res.render('partials/home', { message: "404 not found (unknown page POST request)" });
return;
});
The problem with this is that POST requests are being processed even when no session is in place. I've tried adding app.all/use blocks above the app.get and app.post code blocks to set up a session, but then the app.get/post blocks were not getting processed. What is the optimal way to architect this so all requests get filtered through session management and then on to page request blocks if a proper session is in place?
Upvotes: 0
Views: 237
Reputation: 89
A Middleware function in Express is what you're looking for.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Learn more from Express's Documentation - here
A Middleware can be connected like a chain and is processed in the sequence you write it in. As long as you're executing the 'Next' function, you can link as many as you would like.
So before the POST requests are actually processed, you can exit out and redirect the user, otherwise execute the next function to continue processing.
Here is an example of how you could simplify your code.
function _sessionAuthorization(req, res, next) {
if(typeof req.session.username == "undefined") {
return res.redirect("/login");
} else {
next();
}
}
app.get('*', function(req, res){
res.render('partials/home', { message: "404 not found (unknown page GET request)" });
});
app.post('*', files, _sessionAuthorization, function(req, res){
res.render('partials/home', { message: "404 not found (unknown page POST request)" });
});
Upvotes: 1