当前位置: 首页 > 工具软件 > core-nestjs > 使用案例 >

nestjs - 03

董和风
2023-12-01

Nestjs 守卫(guard)

一、局部守卫

1、controller级守卫

生成guard.ts

nest g gu role
// role.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class RoleGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    console.log('经过了守卫');
    return true;
  }
}

配置controller

// guard.controller.ts
import { Controller, UseGuards, Get } from '@nestjs/common'
import { RoleGuard } from './role.guard'

@Controller()
@UseGuards(RoleGuard)
export class GuardController {
  @Get()
  guardTest() {
    return 'guard test'
  }
}

2、智能守卫

// controller
import { Controller, UseGuards, Get, SetMetadata } from '@nestjs/common'
import { RoleGuard } from './role.guard'

@Controller()
@UseGuards(RoleGuard)
export class GuardController {
  @Get()
  @SetMetadata('role', ['admin']) //  两个参数可自定义,(key, value), 可以用key, value 做后期的判断逻辑
  metaGuardTest() {
    return 'meta guard test'
  }
}
// guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core'
import type { Request } from 'express'

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector)
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const admin = this.reflector.get<string[]>('role'/* 此key 值为SetMetadata中定义的key值 */, contest.getHandler())
		const req = context.switchToHttp().getRequest<Request>()
    console.log('经过了守卫', admin, req);
    // 做权限验证,如果有就过
    if (admin.includes(req.query.role as string)) {
      return true
    } else {
      return false
    }
  }
}

三、全局守卫

import { RoleGuard } from './role.guard'

app.useGlobalGuards(new RoleGuard())
 类似资料: