2016-09-16 87 views
1

我在尝试恢复模型的remoteMethods内的令牌用户标识时遇到问题。我用下面的代码:loopback在标头中使用令牌

User.beforeRemote('**', function(ctx, user, next) { 
    //...some custom token decoding 
    ctx.req.body.user_id = token.user_id; 
    console.log('token : ', token); 
    next(); 
}); 

然后,我的模型里,我用:

User.check = function (user_id, cb) { 
    // Do stuff.. 
}; 


User.remoteMethod(
    'check', 
    { 
     http: {path: '/check', verb: 'post'}, 
     returns: {arg: 'rate', type: 'object'}, 
     accepts: [ 
     { 
      arg: 'user_id', 
      type: 'number', 
      required: true, 
      description: "id of the user to check", 
      http: function getUserid(ctx) { 
      console.log('User.check http body : ', ctx.req.body); 
      return ctx.req.body.user_id; 
      } 
     } 
     ], 
     description: '' 

    } 
); 

的问题是,我ARG的功能“getUserid”被触发的“User.beforeRemote”呼叫前。

这是一个错误吗?你有什么想法我可以做这个工作? 我不想使用

arg : {http : {source : 'body'}}, 

,因为我只希望在远程方法user_ID的阿根廷,因为我必须这样做,在约20〜30的现有方法

感谢名单!

回答

0

我终于找到了这样做的一个简单的方法: 我已经添加了我的令牌解码中间件,它工作得很好,采用了经典的ARG型号,没有http功能:

//middleware dir : 
module.exports = function (app) { 
    "use strict"; 

    return function (req, res, next) { 
    //Custom token decoding code .... 
    //used req.body to show example with post requests : 
    req.body.user_id = parseInt(token.user_id); 

    console.log('token : ', token); 
    next(); 
    }; 
}; 

//remote Method declaration, without need to add a beforeRemote method : 
User.remoteMethod(
    'check', 
    { 
     http: {path: '/check', verb: 'post'}, 
     returns: {arg: 'rate', type: 'object'}, 
     accepts: [ 
     { 
      arg: 'user_id', 
      type: 'number', 
      required: true, 
      description: "id of the user to check" 
     } 
     ], 
     description: '' 
    } 
);