node.js - 使用 mongodb 和 nodejs 在 passportjs 中授权多个本地策略

标签 node.js mongodb authorization passport.js passport-local

我正在 nodejs 中使用 passportjs 和 mongodb 实现多种本地身份验证策略。为了实现身份验证,我在 deserializeUser 中使用了中间件。像这样的东西。我有两种类型的用户,一种是User,另一种是Vendor。供应商将销售产品,用户将购买产品。 我为具有不同本地策略名称的供应商和用户创建了不同的架构。身份验证对我来说很好。

module.exports = function(passport){

// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {

    console.log('user id is: ' + user._id);
    done(null, user._id);
});

passport.deserializeUser(function(id, done) {


    User.findById(id, function (err, user) {
        if(err)
            done(err);
        if(user) {
            done(null, user);
        }
        else {
            Vendor.findById(id, function (err, user) {
                if(err)
                    done(err);
                done(null, user);
            });
        }
    });
});

我想做的是,“用户”帐户不应该能够访问供供应商使用的页面,而供应商也不应该能够访问供用户使用的页面。通过这种方式,我想提供对这两种类型的用户帐户共享的数据的访问控制。 我认为 Passport 是不可能的,但我们需要为它写一些中间件。我们可以通过一些中间件来实现它吗,或者 npm 中是否有任何我们可以用于此目的的包。如果有人能举出一些简单的中间件的例子,那对我来说真的很有帮助。

最佳答案

我解决了这个问题,方法是在“用户”模式中引入一个字段“isUser”,在“供应商”模式中引入“isVendor”,并将其类型保留为 bool 值。现在,当用户注册为“User”时,它将“isUser”存储为 true,当“Vendor”注册时,它将“isVendor”存储为 true。我们将 vendor 和 User 存储在两个不同的模式中。 现在在路由处理程序中,我写了一个中间件,它是这样的。

var isVendor = function (req, res, next) {
if (req.user.isVendor === true) {
return next();
}
res.redirect('/vendorlogin');
};

var isUser = function (req, res, next) {

if(req.user.isUser === true) {
return next();
}
res.redirect('/login');
};

现在我将它添加到我的路由处理程序中,就像这样。

/**
* Testing the authorization policy using two different local strategy
*/

router.get('/productsvendor', isAuthenticated, isVendor, function      (req, res) {

res.send('this is product vendor page, which should be seen only by vendors');
});

router.get('/itemuser', isAuthenticated, isUser , function (req, res) {

res.send('this is item user page, which should be seen only by users');

});

关于node.js - 使用 mongodb 和 nodejs 在 passportjs 中授权多个本地策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40411236/

相关文章:

javascript - "ESLint no-loop-func rule"回调中需要循环变量怎么办

mongodb - "Error: couldn' t 在 Windows 上使用 secret 文件在 MongoDB docker 堆栈中添加用户

mongodb - 为什么在尝试连接到运行简单 mongo 容器的 OKD pod 时出现 "message len 1347703880 is invalid. Min 16 Max: 48000000"错误?

mongodb - 如何在 golang 中获取 mongodb 的转储并恢复它

php - 无法在 Laravel 5.3 中使用策略

node.js - 如何在重定向 Express 4 之前找到原始请求路径

authorization - Keycloak 将组设置为资源的所有者

node.js - 如何设置 Mongoose 查询的超时时间?

javascript - POST 请求中缺少字段是否会引发错误?

javascript - MongoDB/Mongoose/nodejs 中的引用资料 - 并行化