Loopback 4: How to inject user in endpoint

Viewed 592

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?

1 Answers

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

Related