beNerd
beNerd

Reputation: 3374

accessing current logged in user id in custom route in loopback

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!

Upvotes: 1

Views: 588

Answers (1)

user8120138
user8120138

Reputation:

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...
}

`

Upvotes: 2

Related Questions