【问题标题】:Mongoose: Move User Authorized functionality from controller to modelMongoose:将用户授权功能从控制器移动到模型
【发布时间】:2016-01-07 03:23:36
【问题描述】:

我有一个关于最佳实践以及如何添加用户授权功能的问题。它应该在模型、控制器还是其他地方。

目前,

我一直在我的 Mongoose 模型中构建验证函数

我一直在使用中间件构建身份验证/授权检查,并从我的路由中调用。

我当前的挑战是,当经过身份验证和授权的用户尝试更新他们不是所有者的模型时。

我的经过身份验证的用户已附加到我的请求中,但该数据不会在 Mongoose 模型中可用,所以我想我应该在模型上创建某种验证函数,可以从我的控制器,这样我的逻辑就可以很好地适应模型,但可以从控制器中调用。

控制器

exports.create = function (req, res) {

  try {

    if (!_.isEmpty(req.body.entity.ordererAccountId) && !_.isEqual(req.user.accountId.toString(), req.body.entity.ordererAccountId)) {
      var err = mong.formatError({ message: 'Invalid Account Access' });

      return res.status(403).json(err);
    }

    OrderSchema.create(req.body.entity, function (err, entity) {

      if (err) {
        return mong.handleError(res, err);
      }

      return res.status(201).json(mong.formatSuccess(entity));
    });

  } catch (e) {
    console.log(e);
  }
};

型号

'use strict';

// ------------------------------------------------------------
// Order Model
// ------------------------------------------------------------

var mongoose = require('mongoose');
var findOneOrCreate = require('mongoose-find-one-or-create');

var Schema = mongoose.Schema;

var OrderSchema = new Schema({
  created_at: { type: Date },
  updated_at: { type: Date },

  ordererAccountId:
    {
      type: Schema.ObjectId, ref: 'Account',
      required: true
    },
  supplierAccountId:
    {
      type: Schema.ObjectId, ref: 'Account'
    },
  userId:
    {
      type: Schema.ObjectId, ref: 'User',
      required: true
    },
  status: {
    type: String,
    enum: ['Open', 'Sent'],
    default: 'Open'
  },
  notes: String,
  supplierCompanyName: String,
  supplierEmail: String,
  supplierContactName: String,
  supplierPhone1: String,
  supplierPhone2: String,
  deliveryCompanyName: String,
  deliveryEmail: String,
  deliveryFirstName: String,
  deliveryLastName: String,
  deliveryAddress1: String,
  deliveryAddress2: String,
  deliveryCity: String,
  deliveryState: String,
  deliveryPostCode: String,
  deliveryCountry: String,
  deliveryPhone1: String,
  deliveryPhone2: String,
});

OrderSchema.plugin(findOneOrCreate);

// ------------------------------------------------------------
// Validations
// ------------------------------------------------------------

// Validate only one open order at a time per user
OrderSchema
  .path('status')
  .validate(function (status, respond) {

    var Order = mongoose.model('Order');

    // Excluding this Order, make sure there are NO other orders for this user with the status of 'Open'
    var condition = {
      userId: this.userId,
      status: 'Open',
      _id: { $ne: this._id }
    };

    Order.count(condition, function (err, count) {

      if (err) {
        console.log(err);
      }
      else {
        respond(count === 0);
      }

    });

  }, 'There can be only one open order at a time.');

// ------------------------------------------------------------
// Pre-Save Hook
// ------------------------------------------------------------

OrderSchema.pre('save', function (next) {
  var now = new Date().getTime();

  this.updated_at = now;
  if (!this.created_at) {
    this.created_at = now;
  }

  next();
});

module.exports = mongoose.model('Order', OrderSchema);

【问题讨论】:

    标签: node.js mongoose angular-fullstack


    【解决方案1】:

    您可以使用“创建”功能作为路由器中的验证中间件,方法如下:

          app.post('/yourRoute', create, function(req, res) {
                //if validation success
                //do somthing
            });
    

    不要忘记将“下一个”函数作为第三个参数传递给您的 create 函数

    【讨论】:

      猜你喜欢
      • 2014-08-05
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多