创建了完整的NestJS项目结构,包含配置文件、核心模块、工具类、拦截器、过滤器等基础代码,实现了健康检查、用户认证、管理员RBAC、剧集管理、订单支付、媒体管理等核心功能的基础框架,配置了ESLint、TypeScript、Jest等开发工具链。
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 = 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');
|
|
}
|
|
}
|
|
}
|