模型操作的Sails.js身份验证

Loe*_*oed 6 authentication mongodb node.js sails.js

我正在制作一个具有不同访问级别的API,"客户端"可能只能阅读.但'admin'必须具有写访问权限.每次将不同的角色作为Sails.js中的策略进行检查,并在req.session中设置权限.

我只需要让'client'无权访问创建,更新和删除操作,因此我创建了一个具有这些CRUD操作的控制器,并检查用户是否具有正确的角色.所有限制访问的操作都会通过routes.js重定向到此控制器.

现在我的问题是,当我删除类似的条目:Category.destroy(req.param('id')); 给我未定义,没有做过方法.与文档提到的不同,我设法通过创建这个来解决问题:

   var deleted = Category.destroy(req.param('id'), function(err, status) { 
    if (status == 1){
      res.json({message: 'Category is deleted'});
    } else {
      res.json({message: 'Oops, something went wrong'});
    }
  });
Run Code Online (Sandbox Code Playgroud)

但必须有另一种方法将身份验证应用于这些基本操作.因为现在我要编写所有动作.

我写的删除函数的代码有什么问题吗?是否可以应用策略并重定向到默认模型操作,就好像根本没有身份验证一样?

Den*_*ngo 12

您可以在ModelsControllers级别定义策略.这是一个例子/config/policies.js.

module.exports.policies = {
    // Default policy (allow public access)
    '*': true,
    'events': 'eventsPolicy', // Policy for a Model

    someController: { // Policy for a Controller
        // Apply the "authenticated" policy to all actions
        '*': 'authenticated',

        // For someAction, apply 'somePolicy' instead
        someAction: 'somePolicy'
    }
};
Run Code Online (Sandbox Code Playgroud)

api/policies您可以定义访问级别的位置.

module.exports = function (req, res, next) {
    if (req.session.user) {
        var action = req.param('action');
        if (action == "create") {
            req.body.userId = req.session.user.id;
            req.body.username = req.session.user.username;
        }
        next();
    } else {
        res.send("You're not authenticated.", 403);
    }
};
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Loe*_*oed 2

刚刚修改了所有策略并重命名了控制器,如 CLI 中所述:“sails generated model example”给出了有关控制器被命名为单数的通知。所以我不需要将所有模型操作重定向到复数控制器(示例)。现在所有基本的 CRUD 操作都可以正常工作。

sails.js 视频教程对我帮助很大:http://www.youtube.com/watch? feature=player_embedded&v=GK-​​tFvpIR7c