2025-08-27 11:24:22 +08:00
|
|
|
import {
|
|
|
|
|
Injectable,
|
|
|
|
|
CanActivate,
|
|
|
|
|
ExecutionContext,
|
|
|
|
|
UnauthorizedException,
|
|
|
|
|
} from '@nestjs/common';
|
2025-08-24 02:31:42 +08:00
|
|
|
import { JwtService } from '@nestjs/jwt';
|
|
|
|
|
import { Request } from 'express';
|
|
|
|
|
import { AuthService } from '../services/AuthService';
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class JwtAuthGuard implements CanActivate {
|
|
|
|
|
constructor(
|
|
|
|
|
private readonly jwtService: JwtService,
|
|
|
|
|
private readonly authService: AuthService,
|
|
|
|
|
) {}
|
|
|
|
|
|
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
|
|
|
const request = context.switchToHttp().getRequest();
|
|
|
|
|
const token = this.extractTokenFromHeader(request);
|
2025-08-27 11:24:22 +08:00
|
|
|
|
2025-08-24 02:31:42 +08:00
|
|
|
if (!token) {
|
|
|
|
|
throw new UnauthorizedException('未提供访问令牌');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// 验证Token
|
|
|
|
|
const payload = await this.authService.validateToken(token);
|
2025-08-27 11:24:22 +08:00
|
|
|
|
2025-08-24 02:31:42 +08:00
|
|
|
if (!payload) {
|
|
|
|
|
throw new UnauthorizedException('访问令牌无效或已过期');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 将用户信息添加到请求对象中
|
|
|
|
|
request.user = payload;
|
|
|
|
|
return true;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
throw new UnauthorizedException('访问令牌验证失败');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private extractTokenFromHeader(request: Request): string | undefined {
|
|
|
|
|
const [type, token] = request.headers.authorization?.split(' ') ?? [];
|
|
|
|
|
return type === 'Bearer' ? token : undefined;
|
|
|
|
|
}
|
2025-08-27 11:24:22 +08:00
|
|
|
}
|