以任何方式获取Express'用户?

我使用Sequelize和钩子(请参阅: https : //github.com/sequelize/sequelize/pull/894 )。 我试图实现一种日志logging系统,宁愿login钩子,而不是在我的控制器。 任何人有任何想法,我将能够从req.user我的用户到我的钩子函数?

db.define('vehicle', { ... }, { hooks: { beforeUpdate: function(values, cb){ // Want to get my user in here. } } }); 

即使它是一个老问题,这是我的答案。 问题是从请求中获取当前用户进入钩子。 这些步骤可能使你得到:

  1. 使用自定义查询function创build中间件
     req.context.findById = function(model){
       //从参数中删除模型
       Array.prototype.shift.apply(参数);
       //应用原始function
      返回model.findById.apply(model,arguments).then(function(result){
         result.context = {
          用户:req.user
         }
        返回结果;
       });
     };
    
  2. 使用req.findById(model, id)来代替User.findById(id)
     app.put(“/ api / user /:id”,app.isAuthenticated,function(req,res,next){
        //这里是重要的部分,用户req.context.findById(model,id)而不是model.findById(id)
        req.context.findById(User,req.params.id).then(function(item){
           // item.context.user现在是req.user
          如果(!用户){
             返回next(new Error(“User with id”+ id +“not found”));
           }
           user.updateAttributes(req.body).then(function(user){
              res.json(用户);
           })赶上(下);
        })赶上(下);
     });
    
  3. 使用你的钩子, instance.context.user将可用
     User.addHook(“afterUpdate”,函数(实例){
        if(instance.context && instance.context.user){
           console.log(“用户被更改了”+ instance.context.user.id);
        }
     });
    

你可以在https://github.com/bkniffler/express-sequelize-user (我是创build者)find这个程序提取到一个快速中间件。

如果用户和车辆之间存在一对多关系,并且Vehicle的实例已经与用户关联,则可以使用vehicle.getUser()。

 ... beforeUpdate: function(vehicle,cb){ vehicle.getUser() .then(function(user){ console.log(user) }) } 

如果车辆的属性之一是一个用户。

 beforeUpdate: function(vehicle,cb){ User.find(vehicle.uid) .then(function(user){ console.log(user) }) } 

否则这将不得不在控制器中完成。 有没有在控制器中处理这个问题的好理由? 在Vehicle上创build一个名为logUser()的类方法,它接受req.user似乎是阻力最小的path。