import { Injectable, CanActivate, ExecutionContext, ForbiddenException, } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { LicenseService } from '../license.service'; import { REQUIRE_LICENSE_KEY } from '../decorators/require-license.decorator'; @Injectable() export class LicenseGuard implements CanActivate { constructor( private reflector: Reflector, private licenseService: LicenseService, ) {} async canActivate(context: ExecutionContext): Promise { const requireLicense = this.reflector.getAllAndOverride( REQUIRE_LICENSE_KEY, [context.getHandler(), context.getClass()], ); if (!requireLicense) { return true; } const request = context.switchToHttp().getRequest(); const user = request.user; if (!user || !user.userId) { throw new ForbiddenException('请先登录'); } const hasValidLicense = await this.licenseService.verifyUserLicense( user.userId, ); if (!hasValidLicense) { throw new ForbiddenException( '您的授权已过期或未激活,请联系管理员获取卡密', ); } return true; } }