本次提交进行了大规模的项目结构调整: 1. 调整文件目录归属,将模块代码按功能域重新组织 2. 删除多处冗余的DTO、实体类和模块文件 3. 统一了常量、装饰器、工具类的存放位置 4. 修复了`.gitignore`的日志目录匹配规则 5. 新增了健康检查、认证、用户、剧集、订单等核心业务模块
43 lines
1.2 KiB
TypeScript
43 lines
1.2 KiB
TypeScript
import {
|
|
CanActivate,
|
|
ExecutionContext,
|
|
Injectable,
|
|
UnauthorizedException,
|
|
} from '@nestjs/common';
|
|
import { JwtService } from '@nestjs/jwt';
|
|
import { Request } from 'express';
|
|
import { UsersService } from '../../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');
|
|
}
|
|
}
|
|
}
|