为了解决上一章,全局配置guard导致的注册和登录失败问题,我们可以给这两个方法加上装饰器。
1.创建装饰器
执行命令nest g decorator auth/decorator/public --flat
创建了模板代码
import { SetMetadata } from '@nestjs/common';
export const Public = (...args: string[]) => SetMetadata('public', args);
2.编写装饰器代码
import { SetMetadata } from '@nestjs/common';
export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata('IS_PUBLIC_KEY', true);
SetMetadata 是 NestJS 提供的函数,用来给类或方法添加元数据。
这里定义了一个元数据的 key,名字叫 'isPublic'。
它相当于一个标记名称。后面 Guard 可以通过这个 key 判断当前接口是否是公开接口。
它的作用是:给被装饰的 Controller 或路由方法添加一条元数据:
isPublic: true
3.在controller中的登录和注册端点,添加Public装饰器
@Public()
@Post('register')
signUp(@Body() signUpDto: SignUpDto) {
return this.authService.signUp(signUpDto.email, signUpDto.password);
}
@Public()
@Post('login')
SignIn(@Body() signInDto: SignInDto) {
return this.authService.signIn(signInDto.email, signInDto.password);
}
4.修改guard逻辑
在获取token前加入,判断IS_PUBLIC_KEY是否为true的判断
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
]);
if (isPublic) {
return true;
}