node.js - 从策略范围获取 sails 请求目标

标签 node.js model-view-controller sails.js

我目前尝试为 sails 设置一个简单的授权系统(身份验证已经到位) (v0.10) 应用基于sails提供的策略系统。为此,我需要从我的策略中获取 Controller 并操作当前请求目标。

我会在政策中大致执行以下操作:

 module.exports = function (req, res, next) {
     // Get target controller and action
     var target = req.target; // How to do this?
     var action = req.action; // and this?

     // Lookup in database, let through if matches or render error
     User.findOne...
  };

我记得目标信息曾在某个时候嵌入到请求对象中,但现在在那里找不到(提交 5d98ec8)。

我知道可以通过模仿 sails 路由器来解析 req.route 并获取所需的信息,但我宁愿避免为了策略的唯一目的而复制路由逻辑。

编辑:

可以像这样从请求对象中检索 Controller 身份:

var controller = req.options.controller || req.options.model;

请求选项示例:

{ detectedVerb: { verb: '', original: '/user/:id?', path: '/user/:id?' },
  associations: 
    [ { alias: 'auth', type: 'model', model: 'key' },
      { alias: 'group', type: 'model', model: 'group' },
      { alias: 'role', type: 'model', model: 'role' } ],
  actions: true,
  rest: true,
  shortcuts: true,
  prefix: '',
  pluralize: false,
  index: true,
  model: 'user' }

仍在寻找一种理智的方法来获得目标 Controller 的 Action 。

最佳答案

基于对 Github issue about this 的反馈我决定编写一个目标操作/目标蓝图查找作为依赖于 sails.hooks.blueprints 中找到的路由绑定(bind)的自定义服务。

用法:

var action = Utility.getRequestAction(req);

服务定义:

/**
 * api/services/Utitlity.js
 *
 * @module        Service
 * @name          Utility
 * @memberOf      global
 * @description   Utilities for various common tiny tasks
 * @docs          http://sailsjs.org/#!documentation/services
 * @api           public
 **/

/**
 * Module dependencies
 */
  var util = require('util'),
      _ = require('lodash');

module.exports = {

  getRequestAction: function (req) {
    if (req.options.action) return req.options.action;

    var controller = req.options.controller || req.options.model;

    var baseRoute = sails.config.blueprints.prefix + controller;
    var requestRoute = req.route.method + ' ' + req.route.path;

    var Model = sails.models[controller];

    if (req.options.shortcuts && Model) {
      var shortcutRoutes = {
        '/%s/find/:id?': 'find',
        '/%s/create': 'create',
        '/%s/update/:id?': 'update',
        '/%s/destroy/:id?': 'destroy'
      };

      var shortcutAction = _.findWhere(shortcutRoutes, function(blueprint, pattern){
        var shortcutRoute = util.format(pattern, baseRoute);
        return req.route.path === shortcutRoute;
      });

      if (shortcutAction) return shortcutAction;
    }

    if (req.options.rest && Model) {
      var restRoutes = {
        'get /%s/:id?': 'find',
        'post /%s': 'create',
        'put /%s/:id?': 'update',
        'delete /%s/:id?': 'destroy'
      };

      var restAction =_.findWhere(restRoutes, function(blueprint, pattern){
        var restRoute = util.format(pattern, baseRoute);
        return requestRoute === restRoute;
      });

      if (restAction) return restAction;

      var associationActions = _.compact(_.map(req.options.associations, function(association){
        var alias = association.alias;

        var associationRoutes = {
          'get /%s/:parentid/%s/:id?': 'populate',
          'post /%s/:parentid/%s': 'add',
          'delete /%s/:parentid/%s': 'remove'
        };

        return _.findWhere(associationRoutes, function(blueprint, pattern){
          var associationRoute = util.format(pattern, baseRoute, alias);
          return requestRoute === associationRoute;
        });
      }));

      if (associationActions.length > 0) return associationActions[0];
    }
  }
};

关于node.js - 从策略范围获取 sails 请求目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21514822/

相关文章:

model-view-controller - Controller 和门面有什么区别?

javascript - Action方法执行顺序

node.js - 配对 sails、passport 和 mongo : error: A hook (`session` ) failed to load! 对象 .... 没有方法 'assign'

validation - Waterline UUID 类型和验证

node.js - NodeJS Express 站点

javascript - 错误时出现错误 : ENOENT: no such file or directory, stat '/public/main.html'( native )

javascript - 使用 post 方法的 Facebook Graph API BATCH 请求

node.js - Actor 错误: Cast to undefined_method error failed while trying to save in mongoose

javascript - Kendo UI 网格模板错误 - 模板无效

sails.js - 在sails.js 中处理生产/开发/测试配置