Files
cyh-tk-backend/guards/jwt-auth.guard.ts
zhxiao1124 4eff4d877e refactor: 完成项目整体目录重构与路径别名配置
1.  重构项目文件结构,统一文件存放位置与命名规则
2.  配置tsconfig路径别名,替换原有相对路径导入
3.  迁移drama-status枚举到dramas.types统一管理
4.  新增全局配置文件与工具类,补充完整注释与文档
5.  修复所有导入路径与依赖引用问题
2026-07-02 19:17:56 +08:00

43 lines
1.4 KiB
TypeScript

/**
* 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<boolean> {
const request = context.switchToHttp().getRequest<Request & { user?: unknown }>();
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");
}
}
}