我目前正尝试根据策略系统sails提供的sails(v0.10)应用程序设置一个简单的授权系统(已经到位的身份验证)。为此,我需要从我的策略中获取控制器和操作当前请求目标。
我会在政策中粗略地做以下事情:
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...
};
我记得目标信息在某个时刻嵌入了请求对象中,但现在却找不到(commit 5d98ec8)。
我知道有可能通过模仿sails路由器来解析req.route并获取所需的信息,但我宁愿避免为了策略的唯一目的而重复路由逻辑。
修改
可以从请求对象中检索控制器标识,如下所示:
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' }
仍在寻找一种理智的方式来获得目标控制器的动作。
答案 0 :(得分:6)
根据对Github issue about this的反馈,我决定将目标操作/目标蓝图查找编写为依赖于sails.hooks.blueprints
中找到的路径绑定的自定义服务。
<强>用法:强>
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];
}
}
};