简体   繁体   中英

Getting current logged in user - NestJS

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

Rents table entry example在此处输入图片说明

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?

cancelRent()缺少@ApiBearerAuth()

我忘记在我的 Rents Controller 中包含 AuthGuard()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM