accessing current logged in user id in custom route in loopback

蹲街弑〆低调 提交于 2019-12-14 02:35:20

问题


I am trying to access the currently logged in user in a custom route using context.options but find it blank. Trying to access in a operational hook 'before save' like this:

'use strict';
module.exports = function (logs) {
  logs.observe('before save', async (ctx, next) => {
    console.log(ctx.options) //this is empty i.e {} 
});

Here is my custom route (boot script - routes.js):

app.get('/logs/dl',(req,res)=>{
logs.create(logs,(err,obj)=>{
          if(!err)
          {
            res.status(200);
            res.send(obj);
          }
          else
          {
            res.status(500);
            res.send('Some problem occurred. Please try again later')
          }
        });
});

I need the access token and eventually currently logged in user. I believe that the problem is because of the custom route as with rest ctx.options is filled. In this case it is empty!


回答1:


The operation hook context accepts what values you submit to it, as well as a few defaults related to the model, it would never have the userId by default. https://loopback.io/doc/en/lb3/Operation-hooks.html#operation-hook-context-object

Loopback doesn't use its middleware on custom routes, so you'll need to call it manually (or use it on every route). Here is how you would do it by calling the middleware on a per-request basis

app.start = function() {

    var AccessToken = app.registry.getModelByType('AccessToken');

    app.get('/logs/dl', (req, res) => {

        // loopback.token will get your accessToken from the request
        // It takes an options object, and a callback function
        loopback.token({model: AccessToken, app: app}) (req, res, () => {
            // Once we're here the request's accessToken has been read
            const userId = req.accessToken && req.accessToken.userId;

            //  If you want to give context to a operation hook you use the second parameter
            logs.create({color: 'red'}, {contextValue: 'contextValue', userId: userId}, (err, obj) => {

                if (!err) {
                    res.status(200);
                    res.send(obj);
                }
                else {
                    res.status(500);
                    res.send('Some problem occurred. Please try again later')
                }
            });
        })
    });



    // the rest of app.start...
}

`



来源:https://stackoverflow.com/questions/49489531/accessing-current-logged-in-user-id-in-custom-route-in-loopback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!