2022-05-16 09:23:59 +00:00
|
|
|
import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable, SetMetadata } from '@nestjs/common';
|
2022-04-04 13:42:52 +00:00
|
|
|
import { Reflector } from '@nestjs/core';
|
|
|
|
import { WikiService } from '@services/wiki.service';
|
2022-05-16 09:23:59 +00:00
|
|
|
import { WikiStatus } from '@think/domains';
|
2022-04-04 13:42:52 +00:00
|
|
|
|
|
|
|
const KEY = 'WikiStatus';
|
|
|
|
export const CheckWikiStatus = (status: WikiStatus) => SetMetadata(KEY, status);
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class WikiStatusGuard implements CanActivate {
|
|
|
|
constructor(private readonly reflector: Reflector, private readonly wikiService: WikiService) {}
|
|
|
|
|
|
|
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
|
|
const targetStatus = this.reflector.get<WikiStatus>(KEY, context.getHandler());
|
|
|
|
|
|
|
|
if (!targetStatus) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
const request = context.switchToHttp().getRequest();
|
|
|
|
const { params, query, body } = request;
|
2022-04-11 14:01:51 +00:00
|
|
|
const wikiId = params?.id || params?.wikiId || query?.id || query?.wikiId || body?.wikiId;
|
2022-04-04 13:42:52 +00:00
|
|
|
|
|
|
|
const wiki = await this.wikiService.findById(wikiId);
|
|
|
|
|
|
|
|
if (!wiki) {
|
|
|
|
throw new HttpException('目标知识库不存在', HttpStatus.NOT_FOUND);
|
|
|
|
}
|
|
|
|
if (wiki.status !== targetStatus) {
|
|
|
|
throw new HttpException(
|
|
|
|
targetStatus === WikiStatus.private
|
|
|
|
? '私有知识库,无法查看内容'
|
|
|
|
: '公共知识库,无法查看内容,请提 issue 到 GitHub 仓库反馈',
|
|
|
|
HttpStatus.FORBIDDEN
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|