I'm trying to use the routes.js
to define a route to '/account'
.
I want whoever is trying to access that path to go through the UserController
and the checkLogin
action and if the security check passes, then the user should be rendered with the defined view which is home/account
Here is my code:
routes.js:
'/account': {
controller: 'UserController',
action: 'checkLogin',
view: 'home/account'
}
policies.js:
UserController: {
'*': 'isAuthenticated',
'login': true,
'checkLogin': true
}
It let's me view /account
without going through the isAuthenticated
policy check for some reason.
There looks to be a little confusion here as to how policies, controllers and views work. As @bredikhin notes above, your controller will never be called because the route is being bound to a view. It's also important to note that policies cannot be bound to views, only to controllers. The correct setup should be something like:
In config/routes.js
:
'/account': 'UserController.account'
In config/policies.js
:
UserController: {
'*': 'isAuthenticated' // will run on all UserController actions
// or
'account': 'isAuthenticated' // will run just on account action
}
In api/policies/isAuthenticated.js
:
module.exports = function(req, res, next) {
// Your auth code here, returning next() if auth passes, otherwise
// res.forbidden(), or throw error, or redirect, etc.
}
In api/controllers/UserController.js
:
module.exports = {
account: function(req, res) {
res.view('home/account');
}
}
To put it short: either controller/action-style or view-style routing should be used within the same route in routes.js
, not both simultaneously.
According to the router's source code, once there is a view
property in a route object, binding stops, so basically Sails never knows to which controller your /account
path should be routed, which means that your UserController
-specific policy config never fires.
So, just remove the view
property from the route, you can always specify the view path (if you want a non-standard one) with explicit rendering from within your action.
For statics work with policies, you can set your route with controller and action:
'GET /login': 'AuthController.index',
And set view/layout in your controller:
index: function (req, res) {
res.view('auth/login', { layout: 'path/layout' } );
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With