简体   繁体   English

使用MEAN.JS用户授权

[英]Working with MEAN.JS users authorization

I have started using the MEAN.js full stack solution to learn how to create a web application. 我已经开始使用MEAN.js全栈解决方案来学习如何创建Web应用程序。

I have used the generators to create several CRUD models and it has generated all the express routes etc... 我已经使用生成器创建了多个CRUD模型,并且生成了所有快速路线等。

It has also created a User model as a template with some roles and some authenticated and authorized middleware. 它还创建了一个用户模型作为模板,其中包含一些角色以及一些经过身份验证和授权的中间件。

I want to tweak the middleware slightly but I am not aware of the best way to do this. 我想稍微调整中间件,但是我不知道这样做的最佳方法。

For one of my models (Called Themeparks) I want to make sure Users are not only logged in but also have authorization based on their role to perform the post action. 对于我的一个模型(称为主题公园),我想确保用户不仅已登录,而且根据其角色具有执行发布操作的授权。

The code below is the code I currently have from the generators and as you can see the '/themeparks/:themeparkId' route has the themeparks.hasAuthorization middleware function call. 下面的代码是我目前从生成器中获得的代码,并且您可以看到“ / themeparks /:themeparkId”路由具有themeparks.hasAuthorization中间件函数调用。 However this doesn't work on the '/themeparks' route nor does the users.hasAuthorization middleware function. 但是,这在'/ themeparks'路由上无效,users.hasAuthorization中间件功能也无效。

So I am wondering what is the best way to add user authorization to the post method of the '/themeparks' route? 因此,我想知道将用户授权添加到“ / themeparks”路线的post方法的最佳方法是什么? And maybe some resources that have tutorials or cover the user model in the MEAN.js stack? 也许某些资源具有教程或涵盖了MEAN.js堆栈中的用户模型?

//Routes //路线

'use strict';

module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var themeparks = require('../../app/controllers/themeparks.server.controller');

// Themeparks Routes
app.route('/themeparks')
    .get(themeparks.list)
    .post(users.requiresLogin, themeparks.create); //<----How do I add authorization based on a role here??

app.route('/themeparks/:themeparkId')
    .get(themeparks.read)
    .put(users.requiresLogin, themeparks.hasAuthorization, themeparks.update)
    .delete(users.requiresLogin, themeparks.hasAuthorization, themeparks.delete);

// Finish by binding the Themepark middleware
app.param('themeparkId', themeparks.themeparkByID);
};

//User middleware //用户中间件

/**
 * Require login routing middleware
 */
exports.requiresLogin = function(req, res, next) {
    if (!req.isAuthenticated()) {
        return res.status(401).send({
            message: 'User is not logged in'
        });
    }

    next();
};

/**
 * User authorizations routing middleware
 */
exports.hasAuthorization = function(roles) {
    var _this = this;

    return function(req, res, next) {
        _this.requiresLogin(req, res, function() {
            if (_.intersection(req.user.roles, roles).length) {
                return next();
            } else {
                return res.status(403).send({
                    message: 'User is not authorized'
                });
            }
        });
    };
};

//Themeparks middleware // Themeparks中间件

/**
 * Themepark middleware
 */
exports.themeparkByID = function(req, res, next, id) { //TODO: This is probably what is pulling the user in through the middleware.
    Themepark.findById(id).populate('user', 'displayName').exec(function(err, themepark) {
        if (err) return next(err);
        if (! themepark) return next(new Error('Failed to load Themepark ' + id));
        req.themepark = themepark ;
        next();
    });
};

/**
 * Themepark authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
    if (req.themepark.user.id !== req.user.id) {
        return res.status(403).send('User is not authorized');
    }
    next();
};

You add the middleware in the same manner: 您以相同的方式添加中间件:

app.route('/themeparks')
.get(themeparks.list)
.post(users.requiresLogin, themeparks.userRoleHasAuthorization, themeparks.create);

In the themeparks module, you add this function, just like the hasAuthorization function and also include a check for user to be in role. 在主题公园模块中,您可以添加此功能,就像hasAuthorization功能一样,还包括检查用户是否在角色中的功能。 You already have the user id from the request.Use it to query the roles that the user has access to from the database. 您已经从请求中获得了用户ID,使用它来查询用户可以从数据库访问的角色。

(Ideally, if the roles are in the database, I would retrieve that when the user object itself is retrieved, so that the front end can also use the role info when they need to and you don't have to query within the authorization module.) (理想情况下,如果角色在数据库中,我将在检索到用户对象本身时进行检索,以便前端也可以在需要时使用角色信息,而不必在授权模块中查询)

Based on the user id, and the roles information determine if the user is in the role that allows for update to this module. 根据用户标识和角色信息,确定用户是否在允许更新此模块的角色中。 Return a 401 Not Authorized otherwise. 否则返回401未经授权。 Below is how you can structure the code. 下面是如何构造代码。 The canUpdate function needs to be implemented based on how you want to store the roles and info about the modules that should have access to the roles. 需要根据您想要存储角色的方式以及有关应该有权访问角色的模块的信息来实现canUpdate函数。

exports.userRoleHasAuthorization = function(req, res, next) {
if (req.themepark.user.id !== req.user.id || !canUpdate(req.user.id, 'themeparks') {
    return res.status(403).send('User is not authorized');
}
next();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM