TopGrd
TopGrd

Reputation: 1

sails policies not working

When I write a policy, it's not working. What's wrong with my code?

policies.js

'UserController': {
    'create': ['canCreate']
}  

routes.js

'post /register': {
    controller: 'UserController',
    action: 'create'
}  

policies/canCreate.js

module.exports = function (req, res, next) {
    if (req.session.canCreate) {
        return next();
    }
    else {
        res.send('no auth')
    }
};

UserController.js

module.exports = {
    create: function (req, res) {
        req.session.canCreate = true;
        User.create({
            name: req.param('name'),
            password: req.param('password')
        }, function onSuccess(err, newUser) {
            if (err) {
                return res.negotiate(err);
            }
            res.json({
                id: newUser.id
            })
        })
    }
};

Upvotes: 0

Views: 160

Answers (1)

Ron Smith
Ron Smith

Reputation: 56

The policy is looking for req.session.canCreate, however from your code that is only set within UserController.create which can't be accessed because the policy is run before the controller method. If you really want to have that kind of policy, you'll need to add another endpoint which will initialize and set req.session.canCreate = true;

Depending on overall structure, I'd probably change the policy to something like:

if (!req.session.authenticated) {
    return next();
}
else {
    res.forbidden('already authenticated')
}

And I would set req.session.authenticated upon user creation and logging in. In other words, anyone* can create a user account provided they aren't currently logged in; if they're logged in already, then the user creation will be rejected by the policy. (This isn't the right solution for all use-cases, of course, so it's more of a starting point. Adapt it to your own needs.)

*User creation can still be restricted through a captcha or a shared/private secret, or some other means, which would be checked in either the controller, or possibly a policy.

Upvotes: 1

Related Questions