Nest.js 守卫

Docs: https://docs.nestjs.com/guards

当调用者具有足够的权限时,特定路由才可用

// app.guard.ts

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import * as _ from 'lodash'

const l = console.log
@Injectable()
export class AppGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) { }

  canActivate(
    ctx: ExecutionContext,
  ): boolean | Promise | Observable {

    let roles = this.reflector.get('roles', ctx.getHandler())
    // 没有设置守卫 直接通过
    if(!roles) return false;

    const { query: { name } } = ctx.switchToHttp().getRequest();
    l(roles, name)
    return roles && roles.length > 0 && _.includes(roles, name) ? true : false
  }
}
export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles);

@Controller()
@UseGuards(AppGuard)  // 总路由上使用

@Get('a')
@Roles('admin')  // 为接口绑定元数据

转载于:https://www.cnblogs.com/ajanuw/p/9704427.html

你可能感兴趣的:(Nest.js 守卫)