I used this at the beginning :
var app = express.createServer(
express.cookieParser(),
express.session({ secret: 'somesecretword' })
);
Below code is a sample code to get user details with uname as the key.
I call this code from backbone model's url, by calling model.fetch().
app.get('/user/:uname/', function (req, res) {
var uname=req.params.uname;
if(!req.session.user) // check if logged in
res.send("Not Logged In");
return UserModel.find({uname : uname},function(err, user) {
if (!err) {
return res.send(user);
} else {
return res.send(err);
}
});
});
So, here I wrote the code for validating session directly in the above get method.
What if I have many such methods? Do I have to write the same thing in every method, or is there any controller in Node that does this work?
For example, show me a controller that validates for the paths "/user" , means "/user/anythinghere/" should be validated automatically or show me some other better way.
What you are needing is some sort of middleware to pass with the app.get method. I can't exactly re-write your code block as I myself am still learning Node.js how ever this from the Express documentation (modified a bit to try and suit your needs)
function requireAuth(req, res, next) {
if(req.session.user) {
next();
} else {
next(new Error('Failed to load user ' + req.params.id));
}
}
app.get('/user/edit/:id', requireAuth, function(req, res){
res.send('you can see this because you are authed');
});
app.get('/', function(req, res){
res.send('Not requiring auth on homepage');
});
The documentation here explains it better then I can:
http://expressjs.com/guide.html#route-middleware
I hope this can be of some help. :) If anything, I myself just learnt something new answering this, so thanks :D
You could use middleware and put it in a route like this:
app.get('/user/edit/:id', requireAuth, function(req, res){
res.send('you can see this because you are authed');
});
or what I do is something like this using a wildcard:
app.all("/api/private*", ensureAuthenticated);
You can read up more on this here: https://fabianosoriani.wordpress.com/2011/08/15/express-api-on-node-js-with-mysql-auth/