Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loopback 4: How to inject user in endpoint

Tags:

loopback4

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?

like image 476
apfz Avatar asked Jun 09 '20 19:06

apfz


People also ask

What is inject in LoopBack?

@inject is a decorator to annotate class properties or constructor arguments for automatic injection by LoopBack's IoC container. The injected values are applied to a constructed instance, so it can only be used on non-static properties or constructor parameters of a Class.

Which loop is best for user authentication process?

Many who are familiar with LoopBack first discovered it as a way to build RESTful APIs, but LoopBack offers more than just the tools API developers need to build the API itself.

What is a repository in LoopBack?

In LoopBack 4, the layer responsible for this has been separated from the definition of the model itself, into the repository layer. A Repository represents a specialized Service interface that provides strong-typed data access (for example, CRUD) operations of a domain model against the underlying database or service.


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

  • https://loopback.io/doc/en/lb4/Authentication-overview.html
  • https://loopback.io/doc/en/lb4/Loopback-component-authorization.html
like image 175
Rifa Achrinza Avatar answered Oct 01 '22 18:10

Rifa Achrinza