2026-05-09 18:57:33 +08:00
|
|
|
import {
|
|
|
|
|
Injectable,
|
|
|
|
|
CanActivate,
|
|
|
|
|
ExecutionContext,
|
|
|
|
|
UnauthorizedException,
|
|
|
|
|
} from '@nestjs/common';
|
2026-05-17 00:39:46 +08:00
|
|
|
import { Reflector } from '@nestjs/core';
|
2026-05-09 18:57:33 +08:00
|
|
|
import { JwtService } from '@nestjs/jwt';
|
|
|
|
|
import { ConfigService } from '@nestjs/config';
|
|
|
|
|
import { Request } from 'express';
|
2026-05-17 00:39:46 +08:00
|
|
|
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
2026-05-09 18:25:04 +08:00
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class JwtAuthGuard implements CanActivate {
|
2026-05-09 18:57:33 +08:00
|
|
|
constructor(
|
|
|
|
|
private readonly jwtService: JwtService,
|
|
|
|
|
private readonly configService: ConfigService,
|
2026-05-17 00:39:46 +08:00
|
|
|
private readonly reflector: Reflector,
|
2026-05-09 18:57:33 +08:00
|
|
|
) {}
|
|
|
|
|
|
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
2026-05-17 00:39:46 +08:00
|
|
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
|
|
|
|
context.getHandler(),
|
|
|
|
|
context.getClass(),
|
|
|
|
|
]);
|
|
|
|
|
if (isPublic) return true;
|
|
|
|
|
|
2026-05-09 18:57:33 +08:00
|
|
|
const request = context.switchToHttp().getRequest<Request>();
|
|
|
|
|
const token = this.extractToken(request);
|
|
|
|
|
|
|
|
|
|
if (!token) {
|
|
|
|
|
throw new UnauthorizedException('请先登录');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const payload = await this.jwtService.verifyAsync(token, {
|
|
|
|
|
secret: this.configService.get<string>('jwt.secret'),
|
|
|
|
|
});
|
2026-05-13 17:31:50 +08:00
|
|
|
request.user = { id: String(payload.sub), email: payload.email, role: payload.role };
|
2026-05-09 18:57:33 +08:00
|
|
|
return true;
|
|
|
|
|
} catch {
|
|
|
|
|
throw new UnauthorizedException('登录已过期,请重新登录');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private extractToken(request: Request): string | undefined {
|
|
|
|
|
const authHeader = request.headers.authorization;
|
|
|
|
|
if (!authHeader?.startsWith('Bearer ')) return undefined;
|
|
|
|
|
return authHeader.split(' ')[1];
|
2026-05-09 18:25:04 +08:00
|
|
|
}
|
|
|
|
|
}
|