48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
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<boolean> {
|
|
const requireLicense = this.reflector.getAllAndOverride<boolean>(
|
|
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;
|
|
}
|
|
}
|