nestjs 每个接口查询数据库数据时 怎么用登录的用户ID过滤

170 阅读2分钟

在 NestJS 中,可以使用中间件、守卫(Guards)和装饰器(Decorators)来获取登录用户的信息,并在查询数据库时根据用户 ID 进行过滤。通常,NestJS 使用 PassportJWT 来实现用户认证,从而能够在每个请求中获取当前登录用户的信息。

以下是一个基本的实现步骤:

  1. 设置用户认证:确保你的应用已经配置了 JWT 认证。在你的 AuthModule 中,需要设置 JWT 策略,并确保它能解析 JWT 并提取用户信息。

  2. 使用守卫(Guards)进行用户认证: 使用 AuthGuard 来保护需要获取用户信息的路由或控制器。例如:

    // 在 controller 中导入所需模块
    import { Controller, Get, UseGuards, Request } from '@nestjs/common';
    import { JwtAuthGuard } from '../auth/jwt-auth.guard';
    
    @Controller('example')
    export class ExampleController {
      constructor(private readonly exampleService: ExampleService) {}
    
      @UseGuards(JwtAuthGuard)
      @Get('data')
      async getData(@Request() req) {
        const userId = req.user.id; // 从请求中获取用户ID
        return this.exampleService.getDataByUserId(userId); // 使用用户ID过滤查询数据
      }
    }
    
  3. 在服务中实现数据查询: 在你的服务中,编写方法来根据用户 ID 查询数据。例如:

    import { Injectable } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import { DataEntity } from './data.entity';
    
    @Injectable()
    export class ExampleService {
      constructor(
        @InjectRepository(DataEntity)
        private readonly dataRepository: Repository<DataEntity>,
      ) {}
    
      async getDataByUserId(userId: string): Promise<DataEntity[]> {
        return this.dataRepository.find({ where: { userId } }); // 根据用户ID查询数据
      }
    }
    
  4. 在 JWT 策略中设置用户信息: 确保你的 JWT 策略能够正确解析 JWT 并设置 req.user。以下是一个简单的 JWT 策略示例:

    import { Injectable } from '@nestjs/common';
    import { PassportStrategy } from '@nestjs/passport';
    import { Strategy, ExtractJwt } from 'passport-jwt';
    
    @Injectable()
    export class JwtStrategy extends PassportStrategy(Strategy) {
      constructor() {
        super({
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          ignoreExpiration: false,
          secretOrKey: 'your_jwt_secret_key',
        });
      }
    
      async validate(payload: any) {
        return { id: payload.sub, username: payload.username }; // 返回用户信息
      }
    }
    

通过上述步骤,你可以在每个接口中获取到当前登录用户的 ID,并在查询数据库数据时使用该 ID 进行过滤。