44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
|
|
import { Injectable, ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
|||
|
|
import { AuthGuard } from '@nestjs/passport';
|
|||
|
|
import { Reflector } from '@nestjs/core';
|
|||
|
|
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
|||
|
|
import { ErrorCode, ErrorMessage } from '../interfaces/response.interface';
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* JWT 认证守卫
|
|||
|
|
* 默认所有接口都需要认证,除非使用 @Public() 装饰器
|
|||
|
|
*/
|
|||
|
|
@Injectable()
|
|||
|
|
export class JwtAuthGuard extends AuthGuard('jwt') {
|
|||
|
|
constructor(private reflector: Reflector) {
|
|||
|
|
super();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
canActivate(context: ExecutionContext) {
|
|||
|
|
// 检查是否是公开接口
|
|||
|
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
|||
|
|
context.getHandler(),
|
|||
|
|
context.getClass(),
|
|||
|
|
]);
|
|||
|
|
|
|||
|
|
if (isPublic) {
|
|||
|
|
return true;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return super.canActivate(context);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
handleRequest(err: any, user: any, info: any) {
|
|||
|
|
if (err || !user) {
|
|||
|
|
throw (
|
|||
|
|
err ||
|
|||
|
|
new UnauthorizedException({
|
|||
|
|
code: ErrorCode.UNAUTHORIZED,
|
|||
|
|
message: ErrorMessage[ErrorCode.UNAUTHORIZED],
|
|||
|
|
})
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
return user;
|
|||
|
|
}
|
|||
|
|
}
|