/** * JwtAuth guard. * @file 用户端 JWT 认证守卫 * @module guards/jwt-auth.guard * @author zhxiao1124 */ import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common"; import { JwtService } from "@nestjs/jwt"; import { Request } from "express"; import { UsersService } from "@src/users/users.service"; @Injectable() export class JwtAuthGuard implements CanActivate { constructor( private readonly jwtService: JwtService, private readonly usersService: UsersService, ) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const authHeader = request.get("authorization"); const token = authHeader?.startsWith("Bearer ") ? authHeader.slice("Bearer ".length) : undefined; if (!token) { throw new UnauthorizedException("Not authenticated"); } try { const payload = await this.jwtService.verifyAsync<{ sub: number }>(token); const user = await this.usersService.findById(payload.sub); if (!user || user.status !== "active") { throw new UnauthorizedException("Not authenticated"); } request.user = user; return true; } catch { throw new UnauthorizedException("Not authenticated"); } } }