1. 重构项目文件结构,统一文件存放位置与命名规则 2. 配置tsconfig路径别名,替换原有相对路径导入 3. 迁移drama-status枚举到dramas.types统一管理 4. 新增全局配置文件与工具类,补充完整注释与文档 5. 修复所有导入路径与依赖引用问题
52 lines
1.8 KiB
TypeScript
52 lines
1.8 KiB
TypeScript
/**
|
|
* AdminJwtAuth guard.
|
|
* @file 管理端 JWT 认证守卫
|
|
* @module guards/admin-jwt-auth.guard
|
|
* @author zhxiao1124
|
|
*/
|
|
|
|
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
|
|
import { JwtService } from "@nestjs/jwt";
|
|
import { Request } from "express";
|
|
import { AdminUserRecord } from "@src/admin/admin.types";
|
|
import { AdminService } from "@src/admin/admin.service";
|
|
|
|
@Injectable()
|
|
export class AdminJwtAuthGuard implements CanActivate {
|
|
constructor(
|
|
private readonly jwtService: JwtService,
|
|
private readonly adminService: AdminService,
|
|
) {}
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
const request = context.switchToHttp().getRequest<Request & { adminUser?: AdminUserRecord; adminId?: number }>();
|
|
const authHeader = request.get("authorization");
|
|
const token = authHeader?.startsWith("Bearer ") ? authHeader.slice("Bearer ".length) : undefined;
|
|
|
|
if (!token) {
|
|
throw new UnauthorizedException("Admin not authenticated");
|
|
}
|
|
|
|
try {
|
|
const payload = await this.jwtService.verifyAsync<{
|
|
sub: number;
|
|
type: string;
|
|
}>(token);
|
|
if (payload.type !== "admin") {
|
|
throw new UnauthorizedException("Admin not authenticated");
|
|
}
|
|
|
|
const adminUser = await this.adminService.findAdminById(payload.sub);
|
|
if (!adminUser || adminUser.status !== "active") {
|
|
throw new UnauthorizedException("Admin not authenticated");
|
|
}
|
|
|
|
request.adminUser = adminUser;
|
|
request.adminId = adminUser.id;
|
|
return true;
|
|
} catch {
|
|
throw new UnauthorizedException("Admin not authenticated");
|
|
}
|
|
}
|
|
}
|