Loopback 4: How to inject user in endpoint
Asked Answered
A

1

8

I have an endpoint where both users and guests (not authenticated) can post data to:

 async create(
    @requestBody({
      content: {
        'application/json': {
          schema: {
            type: 'object',
            properties: {
              create_account: {type: 'boolean'},
              password: {type: 'string'},
              password_repeat: {type: 'string'},
              currency: {type: 'string'},
              payment_method: {type: 'string'},
              products: {type: 'array'},
              voucher: {type: 'string'},
              customer: {type: 'object'},
              news_letter: {type: 'boolean'},
            },
          },
        },
      },
    })
    @inject(SecurityBindings.USER) currentUserProfile: UserProfile,
    order: Omit<Order, 'id'>,
  ): Promise<{url: string}> {
       const userId = currentUserProfile[securityId];
  }

However, I am unsure how to get the logged-in user from the session as I am getting the following error:

The key 'security.user' is not bound to any value in context

How do I get the user id in this situation?

Ampere answered 9/6, 2020 at 19:8 Comment(4)
This most likely means that authentication wasn't set up properly for the endpoint. Please see loopback.io/doc/en/lb4/Decorators_authenticate.html on how to use the authentication decorators.Heliogravure
To inject user, you need to decorate endpoint with @secured. Then the authentication service will set security.user which found from the token. The cause for the error is you have not decorated endpoint with @secured so no user bound for security.user. I suggest you to remove @inject from parameters and use request object to find either guest or user.Willhite
there doesn't seem to be an @secured decorator in lb4Ampere
Yes there is none. You need to create one. Loopback documentation or this tutorial may help you. BTW, you cannot inject user unless you decorated the class or endpoint with authentication decorator as mentioned by @rifa-achrinzaWillhite
H
3

The controller endpoint needs to be decorated with the @authenticate() and @authorize() decorator and the authentication system must be set up beforehand.

The authentication and authorization documentation has been recently overhauled. Please refer to them as a definitive guide.

For example,

  @post('/users/{userId}/orders', {
    responses: {
      '200': {
        description: 'User.Order model instance',
        content: {'application/json': {schema: {'x-ts-type': Order}}},
      },
    },
  })
  @authenticate('jwt')
  @authorize({resource: 'order', scopes: ['create']})
  async createOrder(
    @param.path.string('userId') userId: string,
    @requestBody() order: Order,
  ): Promise<Order> {
    await this.userRepo.orders(userId).create(order);
  }

Unfortunately without more info (e.g. authentication strategy and authorization provider), it is not possible to give a definitive solution, as different UAA implementations will have different solutions.

Further reading

Heliogravure answered 30/8, 2020 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.