Search code examples
expressfeathersjs

FeatherJS - Get user information with hook?


So im trying out FeatherJS and i was able to register a new user, request a token and also request protected data (using Authorization in the header).

Very important: I am using HTTP Rest API only. The docs seem to point often times to the client feathers module, which i don't use.

So currently i have a super simple setup, i have a message service with a text. One before hook to process the message. Here i want to get back the user information:

module.exports = function (options = {}) {
  return async context => {

    const text = context.data.text
    const user = context.params.user;

    context.data = {

      text,
      userId: user._id

    }
    return context;
  };
};

this doesn't work. In my mdb i only get back:

{
    "_id": "5c35ce18523501803f6a8d8d",
    "text": "123",
    "createdAt": "2019-01-09T10:34:00.774Z",
    "updatedAt": "2019-01-09T10:34:00.774Z",
    "__v": 0
}

i've tried to add the token, that i always submit when i post a message via Authorization, like so:

module.exports = function (options = {}) { return async context => {

    const text = context.data.text
    const user = context.params.user;
    const token = context.params.accessToken


    context.data = {

      text,
      userId: user._id,
      tokId: token

    }
    return context;
  };
};

but it seems like i always just get the same result back like shown above.

Any ideas how i can get the user information back of the current user by using the accessToken?

Never used FeathersJS before, so just trying to understand the ecosystem and how to approach this in FeathersJS.

Any advice is appreciated! Thanks in advance everyone!


Solution

  • Not quite sure what exactly went wrong, but i got it now working by just creating a new project.

    Now i did recreate this project actually before and got the issue as above , but this time it somehow worked.

    For anyone who wants to know the steps i did to 'fix' it:

    1.Create a new folder 2. feathers generate app 3. feathers generate authentication 4. feathers generate service (name for the service: messages) 5. feathers generate hook (name: process-msg, before hook, model: messages) 6. Add this to the hook process-msg:

    module.exports = function (options = {}) {
      return async context => {
    
    
        const user = context.params.user;
        const text = context.data.text;
    
        context.data = {
    
          userId: user.email,
          text,
          dateTime: new Date().getTime()
        }
        return context;
      };
    };
    

    Use postman, register a new account then authenticate to get the token. Save token and add it as Authoriztation Header inside Postman. You should then get also back the user email from the user that is registered, simply because of the token that was added to the Authorization Header.

    Greetings!