So. I set up a DELETE
method for deleting Rents (a Rent
happens when a User
rents out an Item
in my database).
I would like to make sure to check that the only user that can cancel the rent is the one that actually rented the item. I already implemented a check that prevents the user to rent an item from himself.
So basically before executing the delete query on that row in Rents
table, i want to check that the ID of the current logged in user matches with the userID of that specific row in Rents
table, only then will the query be executed
userId is the ID of the User
that rented an Item
(itemId).
I set up a custom GetUser()
decorator
import { User } from './../entities/user.entity';
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const GetUser = createParamDecorator(
(data, ctx: ExecutionContext): User => {
const req = ctx.switchToHttp().getRequest();
return req.user;
},
);
Now, when i call my getMyItems
method to get all the items that the current user owns, the GetUser()
decorator works fine as i can access the user on the request object.
GetMyItems controller
@Get('/my')
@ApiBearerAuth()
async getMyItems(@GetUser() user: User): Promise<Item[]> {
return this.itemsService.getMyItems(user);
}
When I try to do the same for the mentioned cancelRent
method it doesn't seem to work even though everything is setup the same way.
cancelRent controller
@Delete('/:id/cancel')
async cancelRent(
@Param('id') id: number,
@GetUser() user: User,
): Promise<void> {
return this.rentsService.cancelRent(id, user);
}
When i run console.log(user)
in the cancelRent controller i get undefined
, but when I run it in the getMyItems method it returns the current user normally. Is it because its a DELETE
request and not a GET
request?
I forgot to include AuthGuard() in my Rents Controller.