Reputation: 710
I'm new to SailsJS and I would like to ask for expert opinions whether my implementation is ok. With the help of the passport authentication package for SailsJS, I was able to get some kind of authentication going.
/controller/members.js:
module.exports = {
//deny all non authenticated users from accessing this controller
'*':function(req,res,next){
if(!req.user){
res.view(403);
}else{
next();
}
},
//once user is authenticated through passport, it is redirected here
'welcome':function(req,res){
res.view();
},
//when user clicks logout
'logout':function(req,res){
req.logout();
res.redirect("/login");
},
};
However, as you can see from this, the enter policy is coded within the controller itself. I am not using policies at all. So with the help of the package, the policy layer in SailsJS is completely useless? Is this the correct way of implementing passportJS? Correct me if I'm wrong, and I think I most definitely am.
Upvotes: 1
Views: 331
Reputation: 10122
You should be able to implement the above using a policy instead. If you create a policy called, say, isAuthenticated.js, you can move your rule from the controller into it:
module.exports = function(req, res, next) {
if(!req.user){
res.view(403);
} else {
next();
}
};
(And delete the '*' method from your controller). You can then specify "isAuthenticated" as a policy in your config/policies.js file, and control access from there instead:
module.exports.policies = {
members: {
'*': 'isAuthenticated',
'welcome': true,
'logout': true
}
}
Upvotes: 2
Reputation: 350
To make use of policies when implementing authentication using passport, you have to configure them as express middleware (in config/express.js) instead of adding them as controllers.
Take a look at this project to see how it is done:
Upvotes: 0