确定如何使用NodeJS /猫鼬授权

时间:2018-11-28 02:10:25

标签: node.js express authentication mongoose passport.js

我正在使用ElephantJS进行NodeJS / express应用程序的登录/注册。我已经为所有用户定义了一个用户模型,但是只希望管理中的某些用户有权编辑某些模型。我当时正在考虑添加一个布尔字段(例如isAdmin)来确定这一点,但我不知道如何验证管理员用户。具体来说,如何确定何时需要为管理员用户生成令牌?我该如何区分管理中的用户和普通用户?我当时在考虑建立一个单独的本地托管网站,该网站可以连接到同一数据库,而我只能使用该数据库来管理计算机上的模型。那行得通吗?

任何帮助将不胜感激!

谢谢!

1 个答案:

答案 0 :(得分:0)

有很多可用的选项。我可以向你解释其中的一些。

1)如您所说,您可以将布尔字段定义为admin true或false。

->(如果您正在使用此选项并且正在使用护照)。您必须在请求对象中获取用户。在点击api或特定端点之前,您可以设置中间件以验证所请求的用户是admin还是user。 文件

文件名:../ services / auth.service.js

            exports.isAdmin = async (req, res, next) => {
                        // req.user is object that you will get after successfull login. change accordingly
                        // Or you can check from db also. Get object logged in user from db by their email id.
                        // And check condition
                        // Check Role if admin or not
                        if(req.user.isAdmin) {
                            next(); // If verify it will redirect to next process
                        } else {
                            return res.status(401).json({
                                Error: true,
                                message: 'You are not authorized to perform this action.',
                            })              
                        }

            };

您可以将此功能用作中间件。

            const auth = require('../services/auth.service.js')

            router.get('/*', auth.isAdmin, (req, res) => {
                res.status(200).json({ message: "Hello from Admin side."})
            });

访问:https://github.com/mihir-kanzariya/Nodejs-CRUD