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?
@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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With