0
votes

I'm trying to use the before Remote hook in loopback to check an user token before the call of my remote method, but the thing is that I can only return a javascript Error, like these.

    "error": {
        "statusCode": 401,
        "name": "Error",
        "message": ""
    }

This is the code that i'm using in the before remote.

Model.beforeRemote('method', function (context, unused, next) {

let token = Model.app.models.Token;
let id = context.args.Id;

let date = moment();
Rx.Observable.fromPromise(token.find({
    where: {
        and: [
            { id: id, },
            { expiration: { gt: date } }
        ]
    }
})).subscribe((token => {
    if (token.length > 0) {
        next();
    } else {
        let err = new Error();
        err.status = 401;
        delete err.stack;
        return next()
    }
}))
});

And I need a "custom" response that isn't an error, something like these.

    {
      "success": false,
      "data": {
        "service": "self",
        "operation": "rest",
        "code": "unauthorized"
      },
      "message": "Invalid token"
    }

I tried with the after Remote hook and I can change the response to get something like that, but I want to get a quicker response in the case that the token is invalid.

Is there any way to achieve this with the before hook? or I had to use after hook?

Thanks

1
I am assuming you have used Loopback's ACL, would you mind telling us the reason why the default error response is not enough for your requirements? - Mark Ryan Orosa
and please show us the existing code you have, using the beforeRemote method. - Mark Ryan Orosa
I'm not using Loopback's ACL. I have to replicate a rest service to make an app work, the user's token comes from another service. The app needs an specific response with an specific status code to trigger an event and logout the user when the token is outdated. - Tom
Added the code with the beforeRemote hook. - Tom

1 Answers

0
votes

You may want to pass the error to the next function:

return next(err)