我在理解如何使用貓鼬模塊使用Node ACL時遇到了一些麻煩。只要一切都在一個文件中,我就可以很好地運行。但是,如果我想將路由分解成單獨的文件,如何訪問其他模塊中的acl實例?如何跨多個模塊訪問節點acl?
我可以用下面的代碼獲得acl,就好了。它初始化,在數據庫中創建集合,並向用戶添加權限。
// App.js
const mongoose = require('mongoose');
const node_acl = require('acl');
const User = require('./models/User');
mongoose.connect(/* connection string */);
acl = new node_acl(new node_acl.mongodbBackend(mongoose.connection.db, '_acl'));
acl.allow([
{
roles: ['guest'],
allows: [{ resources: 'login', permissions: 'get' }],
},
{
roles: ['admin'],
allows: [{ resources: '/users', permissions: '*' }]
}
]);
var user = User.findOne({username: 'coffee'}, (err, user) => {
console.error(user.id);
acl.addUserRoles(user.id, 'admin');
});
我無法弄清楚如何正確訪問另一個模塊中的acl實例。
// routes/foo.js
const acl = require('acl');
const router = require('express').Router();
// initialize acl ?
router.route('/', acl.middleware(/* rules */), (req, res) => {
// route logic
});
module.exports = router;
此代碼產生以下錯誤:TypeError: acl.middleware is not a function
。
我是否需要在每個路由模塊中使用數據庫連接創建一個新的acl實例?如果是的話,再次從Mongoose獲得連接的最佳方式是什麼?如果沒有,還是有辦法將它傳遞給每條路線?
謝謝!
app.js:
acl = new node_acl(new node_acl.mongodbBackend(mongoose.connection.db, '_acl'));
// add this before routers:
app.use(function(req, res, next) {
req.acl = acl;
next();
});
路線/ foo.js:
router.route('/', (req, res) => {
console.log(req.acl);
// route logic
});
謝謝!這樣做更有意義。 – JeremyC