chore: format

This commit is contained in:
xiaojunnuo
2026-05-31 01:41:33 +08:00
parent acd440106b
commit 4b57a0d729
557 changed files with 12530 additions and 14039 deletions
@@ -1,29 +1,29 @@
import {Body, Controller, Get, Inject, Post, Provide} from '@midwayjs/core';
import { BaseController, Constants, FileService, SysSettingsService, SysSiteInfo } from '@certd/lib-server';
import { http, logger } from '@certd/basic';
import { isComm } from '@certd/plus-core';
import { Body, Controller, Get, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, Constants, FileService, SysSettingsService, SysSiteInfo } from "@certd/lib-server";
import { http, logger } from "@certd/basic";
import { isComm } from "@certd/plus-core";
export function normalizeReleaseVersion(release: { tag_name?: string; name?: string }) {
const version = release?.tag_name || release?.name || '';
return version.replace(/^v/i, '');
const version = release?.tag_name || release?.name || "";
return version.replace(/^v/i, "");
}
/**
*/
@Provide()
@Controller('/api/app/')
@Controller("/api/app/")
export class AppController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
fileService: FileService;
@Get('/latest', { description: Constants.per.authOnly })
@Get("/latest", { description: Constants.per.authOnly })
async latest(): Promise<any> {
try {
const res = await http.request({
url: 'https://api.atomgit.com/api/v5/repos/certd/certd/releases/latest',
method: 'get',
url: "https://api.atomgit.com/api/v5/repos/certd/certd/releases/latest",
method: "get",
logRes: false,
timeout: 5000,
});
@@ -31,30 +31,30 @@ export class AppController extends BaseController {
return this.ok(latest);
} catch (e: any) {
logger.error(e);
return this.ok('');
return this.ok("");
}
}
@Get('/favicon', { description: Constants.per.guest })
@Get("/favicon", { description: Constants.per.guest })
public async getFavicon() {
if (isComm()) {
const siteInfo = await this.sysSettingsService.getSetting<SysSiteInfo>(SysSiteInfo);
const favicon = siteInfo.logo;
if (favicon) {
const redirect = '/api/basic/file/download?key=' + favicon;
const redirect = "/api/basic/file/download?key=" + favicon;
this.ctx.response.redirect(redirect);
this.ctx.response.set('Cache-Control', 'public,max-age=25920');
this.ctx.response.set("Cache-Control", "public,max-age=25920");
return;
}
}
const redirect = '/static/images/logo/logo.svg';
const redirect = "/static/images/logo/logo.svg";
this.ctx.response.redirect(redirect);
this.ctx.response.set('Cache-Control', 'public,max-age=25920');
this.ctx.response.set("Cache-Control", "public,max-age=25920");
}
@Post('/webhook', { description: Constants.per.guest })
public async webhook( @Body() body: any) {
logger.info('webhook', JSON.stringify(body))
return this.ok("success")
@Post("/webhook", { description: Constants.per.guest })
public async webhook(@Body() body: any) {
logger.info("webhook", JSON.stringify(body));
return this.ok("success");
}
}
@@ -32,12 +32,12 @@ export class EmailCodeReq {
}
// 找回密码的验证码有效期
const FORGOT_PASSWORD_CODE_DURATION = 3
const FORGOT_PASSWORD_CODE_DURATION = 3;
/**
*/
@Provide()
@Controller('/api/basic/code')
@Controller("/api/basic/code")
export class BasicController extends BaseController {
@Inject()
codeService: CodeService;
@@ -53,13 +53,13 @@ export class BasicController extends BaseController {
@Inject()
addonGetterService: AddonGetterService;
@Post('/captcha/get', { description: Constants.per.guest })
async getCaptcha(@Query("captchaAddonId") captchaAddonId:number) {
const form = await this.captchaService.getCaptcha(captchaAddonId)
return this.ok(form);
@Post("/captcha/get", { description: Constants.per.guest })
async getCaptcha(@Query("captchaAddonId") captchaAddonId: number) {
const form = await this.captchaService.getCaptcha(captchaAddonId);
return this.ok(form);
}
@Post('/sendSmsCode', { description: Constants.per.guest })
@Post("/sendSmsCode", { description: Constants.per.guest })
public async sendSmsCode(
@Body(ALL)
body: SmsCodeReq,
@@ -70,17 +70,17 @@ export class BasicController extends BaseController {
verificationCodeLength: undefined,
duration: undefined,
};
if(body?.verificationType === 'forgotPassword') {
if (body?.verificationType === "forgotPassword") {
opts.duration = FORGOT_PASSWORD_CODE_DURATION;
// opts.verificationCodeLength = 6; //部分厂商这里会设置参数长度这里就不改了
}
await this.codeService.checkCaptcha(body.captcha,{remoteIp});
await this.codeService.checkCaptcha(body.captcha, { remoteIp });
await this.codeService.sendSmsCode(body.phoneCode, body.mobile, opts);
return this.ok(null);
}
@Post('/sendEmailCode', { description: Constants.per.guest })
@Post("/sendEmailCode", { description: Constants.per.guest })
public async sendEmailCode(
@Body(ALL)
body: EmailCodeReq,
@@ -91,20 +91,18 @@ export class BasicController extends BaseController {
verificationCodeLength: undefined,
duration: undefined,
};
if(body?.verificationType === 'forgotPassword') {
if (body?.verificationType === "forgotPassword") {
opts.duration = FORGOT_PASSWORD_CODE_DURATION;
opts.verificationCodeLength = 6;
}else{
} else {
opts.duration = 10;
opts.verificationCodeLength = 6;
}
await this.codeService.checkCaptcha(body.captcha,{remoteIp});
await this.codeService.checkCaptcha(body.captcha, { remoteIp });
await this.codeService.sendEmailCode(body.email, opts);
// 设置缓存内容
return this.ok(null);
}
}
@@ -1,16 +1,16 @@
import { Controller, Fields, Files, Get, Inject, Post, Provide, Query } from '@midwayjs/core';
import { BaseController, Constants, FileService, PermissionException, UploadFileItem, uploadTmpFileCacheKey } from '@certd/lib-server';
import send from 'koa-send';
import { nanoid } from 'nanoid';
import { cache } from '@certd/basic';
import { UploadFileInfo } from '@midwayjs/upload';
import { AuthService } from '../../modules/sys/authority/service/auth-service.js';
import { Controller, Fields, Files, Get, Inject, Post, Provide, Query } from "@midwayjs/core";
import { BaseController, Constants, FileService, PermissionException, UploadFileItem, uploadTmpFileCacheKey } from "@certd/lib-server";
import send from "koa-send";
import { nanoid } from "nanoid";
import { cache } from "@certd/basic";
import { UploadFileInfo } from "@midwayjs/upload";
import { AuthService } from "../../modules/sys/authority/service/auth-service.js";
const imageExtSet = new Set(['.apng', '.avif', '.bmp', '.gif', '.ico', '.jpeg', '.jpg', '.png', '.svg', '.webp']);
const imageExtSet = new Set([".apng", ".avif", ".bmp", ".gif", ".ico", ".jpeg", ".jpg", ".png", ".svg", ".webp"]);
const imageCacheSeconds = 3 * 24 * 60 * 60;
export function isImageFile(filePath: string) {
return imageExtSet.has(filePath.substring(filePath.lastIndexOf('.')).toLowerCase());
return imageExtSet.has(filePath.substring(filePath.lastIndexOf(".")).toLowerCase());
}
export function getImageDownloadOptions(filePath: string) {
@@ -20,7 +20,7 @@ export function getImageDownloadOptions(filePath: string) {
return {
maxage: imageCacheSeconds * 1000,
setHeaders(res: any) {
res.setHeader('Cache-Control', `public,max-age=${imageCacheSeconds}`);
res.setHeader("Cache-Control", `public,max-age=${imageCacheSeconds}`);
},
};
}
@@ -28,7 +28,7 @@ export function getImageDownloadOptions(filePath: string) {
/**
*/
@Provide()
@Controller('/api/basic/file')
@Controller("/api/basic/file")
export class FileController extends BaseController {
@Inject()
fileService: FileService;
@@ -36,9 +36,9 @@ export class FileController extends BaseController {
@Inject()
authService: AuthService;
@Post('/upload', { description: Constants.per.authOnly })
async upload(@Files() files: UploadFileInfo<string>[], @Fields() fields: any, @Query('autoSave') autoSave: string) {
console.log('files', files, fields);
@Post("/upload", { description: Constants.per.authOnly })
async upload(@Files() files: UploadFileInfo<string>[], @Fields() fields: any, @Query("autoSave") autoSave: string) {
console.log("files", files, fields);
const cacheKey = uploadTmpFileCacheKey + nanoid();
const file = files[0];
cache.set(
@@ -51,8 +51,8 @@ export class FileController extends BaseController {
ttl: 1000 * 60 * 60,
}
);
if (autoSave === 'true') {
const key = await this.fileService.saveFile(this.getUserId(), cacheKey, 'public');
if (autoSave === "true") {
const key = await this.fileService.saveFile(this.getUserId(), cacheKey, "public");
return this.ok({
key,
url: `/api/basic/file/download?key=${encodeURIComponent(key)}`,
@@ -63,8 +63,8 @@ export class FileController extends BaseController {
});
}
@Get('/download', { description: Constants.per.guestOptionalAuth })
async download(@Query('key') key: string) {
@Get("/download", { description: Constants.per.guestOptionalAuth })
async download(@Query("key") key: string) {
const filePath = this.getDownloadFilePath(key);
const sendOptions = getImageDownloadOptions(filePath);
if (!sendOptions) {
@@ -74,7 +74,7 @@ export class FileController extends BaseController {
}
private getDownloadFilePath(key: string) {
const isPrivateFile = !key.startsWith('/public');
const isPrivateFile = !key.startsWith("/public");
const userId = isPrivateFile ? this.getUserId() : null;
try {
return this.fileService.getFile(key, userId);
@@ -1,21 +1,18 @@
import {Controller, Get, Provide} from '@midwayjs/core';
import {BaseController, Constants} from '@certd/lib-server';
import { Controller, Get, Provide } from "@midwayjs/core";
import { BaseController, Constants } from "@certd/lib-server";
/**
*/
@Provide()
@Controller('/health')
@Controller("/health")
export class HealthController extends BaseController {
@Get('/liveliness', { description: Constants.per.guest })
@Get("/liveliness", { description: Constants.per.guest })
async liveliness(): Promise<any> {
return this.ok('ok')
return this.ok("ok");
}
@Get('/readiness', { description: Constants.per.guest })
@Get("/readiness", { description: Constants.per.guest })
async readiness(): Promise<any> {
return this.ok('ok')
return this.ok("ok");
}
}
@@ -1,15 +1,15 @@
import { Controller, Get, Inject, MidwayEnvironmentService, Provide } from '@midwayjs/core';
import { logger } from '@certd/basic';
import { Constants } from '@certd/lib-server';
import { Controller, Get, Inject, MidwayEnvironmentService, Provide } from "@midwayjs/core";
import { logger } from "@certd/basic";
import { Constants } from "@certd/lib-server";
@Provide()
@Controller('/home')
@Controller("/home")
export class HomeController {
@Inject()
environmentService: MidwayEnvironmentService;
@Get('/', { description: Constants.per.guest })
@Get("/", { description: Constants.per.guest })
async home(): Promise<string> {
logger.info('当前环境:', this.environmentService.getCurrentEnvironment()); // prod
return 'Hello Midwayjs!';
logger.info("当前环境:", this.environmentService.getCurrentEnvironment()); // prod
return "Hello Midwayjs!";
}
}
@@ -1,13 +1,13 @@
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, CommonException, Constants, SysSettingsService } from "@certd/lib-server";
import { CodeService } from '../../../modules/basic/service/code-service.js';
import { UserService } from '../../../modules/sys/authority/service/user-service.js';
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { UserService } from "../../../modules/sys/authority/service/user-service.js";
import { LoginService } from "../../../modules/login/service/login-service.js";
/**
*/
@Provide()
@Controller('/api')
@Controller("/api")
export class ForgotPasswordController extends BaseController {
@Inject()
loginService: LoginService;
@@ -19,29 +19,29 @@ export class ForgotPasswordController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@Post('/forgotPassword', { description: Constants.per.guest })
@Post("/forgotPassword", { description: Constants.per.guest })
public async forgotPassword(
@Body(ALL)
body: any,
body: any
) {
const sysSettings = await this.sysSettingsService.getPublicSettings();
if(!sysSettings.selfServicePasswordRetrievalEnabled) {
throw new CommonException('暂未开启自助找回');
if (!sysSettings.selfServicePasswordRetrievalEnabled) {
throw new CommonException("暂未开启自助找回");
}
// 找回密码的验证码允许错误次数
const maxErrorCount = 5;
if(body.type === 'email') {
if (body.type === "email") {
this.codeService.checkEmailCode({
verificationType: 'forgotPassword',
verificationType: "forgotPassword",
email: body.input,
validateCode: body.validateCode,
maxErrorCount: maxErrorCount,
throwError: true,
});
} else if(body.type === 'mobile') {
} else if (body.type === "mobile") {
await this.codeService.checkSmsCode({
verificationType: 'forgotPassword',
verificationType: "forgotPassword",
mobile: body.input,
phoneCode: body.phoneCode,
smsCode: body.validateCode,
@@ -49,10 +49,10 @@ export class ForgotPasswordController extends BaseController {
throwError: true,
});
} else {
throw new CommonException('暂不支持的找回类型,请联系管理员找回');
throw new CommonException("暂不支持的找回类型,请联系管理员找回");
}
const username = await this.userService.forgotPassword(body);
username && this.loginService.clearCacheOnSuccess(username)
username && this.loginService.clearCacheOnSuccess(username);
return this.ok();
}
}
@@ -9,7 +9,7 @@ import { PasskeyService } from "../../../modules/login/service/passkey-service.j
/**
*/
@Provide()
@Controller('/api/')
@Controller("/api/")
export class LoginController extends BaseController {
@Inject()
loginService: LoginService;
@@ -24,20 +24,19 @@ export class LoginController extends BaseController {
@Inject()
captchaService: CaptchaService;
@Inject()
@Inject()
passkeyService: PasskeyService;
@Post('/login', { description: Constants.per.guest })
@Post("/login", { description: Constants.per.guest })
public async login(
@Body(ALL)
body: any,
@RequestIP()
remoteIp: string
) {
const settings = await this.sysSettingsService.getPublicSettings()
const settings = await this.sysSettingsService.getPublicSettings();
if (settings.captchaEnabled === true) {
await this.captchaService.doValidate({form:body.captcha,must:false,captchaAddonId:settings.captchaAddonId,req:{remoteIp}})
await this.captchaService.doValidate({ form: body.captcha, must: false, captchaAddonId: settings.captchaAddonId, req: { remoteIp } });
}
const token = await this.loginService.loginByPassword(body);
this.writeTokenCookie(token);
@@ -48,14 +47,14 @@ export class LoginController extends BaseController {
// this.loginService.writeTokenCookie(this.ctx,token);
}
@Post('/loginBySms', { description: Constants.per.guest })
@Post("/loginBySms", { description: Constants.per.guest })
public async loginBySms(
@Body(ALL)
body: any
) {
const settings = await this.sysSettingsService.getSetting<SysPublicSettings>(SysPublicSettings);
if (settings.smsLoginEnabled !== true) {
throw new Error('当前站点禁止短信验证码登录');
throw new Error("当前站点禁止短信验证码登录");
}
checkComm();
@@ -72,12 +71,11 @@ export class LoginController extends BaseController {
return this.ok(token);
}
@Post('/loginByTwoFactor', { description: Constants.per.guest })
@Post("/loginByTwoFactor", { description: Constants.per.guest })
public async loginByTwoFactor(
@Body(ALL)
body: any
) {
const token = await this.loginService.loginByTwoFactor({
loginId: body.loginId,
verifyCode: body.verifyCode,
@@ -87,19 +85,14 @@ export class LoginController extends BaseController {
return this.ok(token);
}
@Post('/passkey/generateAuthentication', { description: Constants.per.guest })
@Post("/passkey/generateAuthentication", { description: Constants.per.guest })
public async generateAuthentication() {
const options = await this.passkeyService.generateAuthenticationOptions(
this.ctx
);
const options = await this.passkeyService.generateAuthenticationOptions(this.ctx);
return this.ok(options);
}
@Post('/loginByPasskey', { description: Constants.per.guest })
@Post("/loginByPasskey", { description: Constants.per.guest })
public async loginByPasskey(
@Body(ALL)
body: any
@@ -107,19 +100,22 @@ export class LoginController extends BaseController {
const credential = body.credential;
const challenge = body.challenge;
const token = await this.loginService.loginByPasskey({
credential,
challenge,
}, this.ctx);
const token = await this.loginService.loginByPasskey(
{
credential,
challenge,
},
this.ctx
);
// this.writeTokenCookie(token);
return this.ok(token);
}
@Post('/logout', { description: Constants.per.authOnly })
@Post("/logout", { description: Constants.per.authOnly })
public logout() {
this.ctx.cookies.set("certd_token", "", {
maxAge: 0
maxAge: 0,
});
return this.ok();
}
@@ -32,9 +32,8 @@ function getOauthBoundType(type: string, subtype?: string) {
/**
*/
@Provide()
@Controller('/api/oauth')
@Controller("/api/oauth")
export class ConnectController extends BaseController {
@Inject()
addonGetterService: AddonGetterService;
@Inject()
@@ -52,10 +51,8 @@ export class ConnectController extends BaseController {
@Inject()
addonService: AddonService;
private async getOauthProvider(type: string) {
const publicSettings = await this.sysSettingsService.getPublicSettings()
const publicSettings = await this.sysSettingsService.getPublicSettings();
if (!publicSettings?.oauthEnabled) {
throw new Error("OAuth功能未启用");
}
@@ -64,7 +61,7 @@ export class ConnectController extends BaseController {
throw new Error(`未配置该OAuth类型:${type}`);
}
const addon = await this.addonGetterService.getAddonById(setting.addonId, true, 0,null);
const addon = await this.addonGetterService.getAddonById(setting.addonId, true, 0, null);
if (!addon) {
throw new Error("初始化OAuth插件失败");
}
@@ -74,19 +71,18 @@ export class ConnectController extends BaseController {
};
}
@Post('/login', { description: Constants.per.guest })
public async login(@Body(ALL) body: { type: string, subtype?: string, forType?:string ,from?:string }) {
@Post("/login", { description: Constants.per.guest })
public async login(@Body(ALL) body: { type: string; subtype?: string; forType?: string; from?: string }) {
const oauthProvider = await this.getOauthProvider(body.type);
const installInfo = await this.sysSettingsService.getSetting<SysInstallInfo>(SysInstallInfo);
const bindUrl = installInfo?.bindUrl || "";
//构造登录url
const redirectUrl = `${bindUrl}api/oauth/callback/${body.type}`;
let stateObj = {
forType: body.forType || 'login',
}
const state = utils.hash.base64(JSON.stringify(stateObj))
const stateObj = {
forType: body.forType || "login",
};
const state = utils.hash.base64(JSON.stringify(stateObj));
const { loginUrl, ticketValue } = await oauthProvider.addon.buildLoginUrl({
redirectUri: redirectUrl,
forType: body.forType,
@@ -94,25 +90,23 @@ export class ConnectController extends BaseController {
subtype: body.subtype,
state,
});
const ticket = this.codeService.setValidationValue({
...ticketValue,
state,
subtype: body.subtype,
})
});
this.ctx.cookies.set("oauth_ticket", ticket, {
httpOnly: true,
// secure: true,
// sameSite: "strict",
})
});
return this.ok({ loginUrl, ticket });
}
@Get('/callback/:type', { description: Constants.per.guest })
public async callback(@Param('type') type: string, @Query() query: Record<string, string>) {
checkPlus()
@Get("/callback/:type", { description: Constants.per.guest })
public async callback(@Param("type") type: string, @Query() query: Record<string, string>) {
checkPlus();
//处理登录回调
const oauthProvider = await this.getOauthProvider(type);
@@ -133,13 +127,13 @@ export class ConnectController extends BaseController {
const installInfo = await this.sysSettingsService.getSetting<SysInstallInfo>(SysInstallInfo);
const bindUrl = installInfo?.bindUrl || "";
const currentUrl = `${bindUrl}api/oauth/callback/${type}?${request.querystring}`
const currentUrl = `${bindUrl}api/oauth/callback/${type}?${request.querystring}`;
try {
const tokenRes = await oauthProvider.addon.onCallback({
code: query.code,
state: query.state,
ticketValue,
currentURL: new URL(currentUrl)
currentURL: new URL(currentUrl),
});
const userInfo = tokenRes.userInfo;
@@ -149,7 +143,7 @@ export class ConnectController extends BaseController {
userInfo,
});
let state = {forType:""}
let state = { forType: "" };
if (query.state) {
state = JSON.parse(utils.hash.base64Decode(query.state));
}
@@ -160,12 +154,11 @@ export class ConnectController extends BaseController {
logger.error(err);
this.ctx.redirect(`${bindUrl}#/oauth/callback/${type}?error=${err.error_description || err.message}`);
}
}
@Post('/getLogoutUrl', { description: Constants.per.guest })
@Post("/getLogoutUrl", { description: Constants.per.guest })
public async logout(@Body(ALL) body: any) {
checkPlus()
checkPlus();
const oauthProvider = await this.getOauthProvider(body.type);
const { logoutUrl } = await oauthProvider.addon.buildLogoutUrl({
...body,
@@ -173,10 +166,9 @@ export class ConnectController extends BaseController {
return this.ok({ logoutUrl });
}
@Post('/token', { description: Constants.per.guest })
public async token(@Body(ALL) body: { validationCode: string, type: string }) {
checkPlus()
@Post("/token", { description: Constants.per.guest })
public async token(@Body(ALL) body: { validationCode: string; type: string }) {
checkPlus();
const validationValue = await this.codeService.getValidationValue(body.validationCode);
if (!validationValue) {
throw new Error("校验码错误");
@@ -191,7 +183,6 @@ export class ConnectController extends BaseController {
const loginRes = await this.loginService.loginByOpenId({ openId, type });
if (loginRes == null) {
return this.ok({
bindRequired: true,
validationCode: body.validationCode,
@@ -207,24 +198,22 @@ export class ConnectController extends BaseController {
// this.loginService.writeTokenCookie(this.ctx,token);
}
@Post('/autoRegister', { description: Constants.per.guest })
public async autoRegister(@Body(ALL) body: { validationCode: string, type: string }) {
@Post("/autoRegister", { description: Constants.per.guest })
public async autoRegister(@Body(ALL) body: { validationCode: string; type: string }) {
const validationValue = this.codeService.getValidationValue(body.validationCode);
if (!validationValue) {
throw new Error("第三方认证授权已过期");
}
const userInfo = validationValue.userInfo;
const oauthType = validationValue.type;
let newUser = new UserEntity()
let newUser = new UserEntity();
newUser.username = `${userInfo.nickName}_${simpleNanoId(6)}_${oauthType}`;
newUser.avatar = userInfo.avatar;
newUser.nickName = userInfo.nickName || simpleNanoId(6);
newUser.email = userInfo.email || "";
newUser = await this.userService.register("username", newUser, async (txManager) => {
const oauthBound: OauthBoundEntity = new OauthBoundEntity()
newUser = await this.userService.register("username", newUser, async txManager => {
const oauthBound: OauthBoundEntity = new OauthBoundEntity();
oauthBound.userId = newUser.id;
oauthBound.type = oauthType;
oauthBound.openId = userInfo.openId;
@@ -236,8 +225,7 @@ export class ConnectController extends BaseController {
return this.ok(loginRes);
}
@Post('/bind', { description: Constants.per.loginOnly })
@Post("/bind", { description: Constants.per.loginOnly })
public async bind(@Body(ALL) body: any) {
//需要已登录
const userId = this.getUserId();
@@ -256,7 +244,7 @@ export class ConnectController extends BaseController {
return this.ok(1);
}
@Post('/unbind', { description: Constants.per.loginOnly })
@Post("/unbind", { description: Constants.per.loginOnly })
public async unbind(@Body(ALL) body: any) {
//需要已登录
const userId = this.getUserId();
@@ -267,20 +255,19 @@ export class ConnectController extends BaseController {
return this.ok(1);
}
@Post('/bounds', { description: Constants.per.loginOnly })
@Post("/bounds", { description: Constants.per.loginOnly })
public async bounds(@Body(ALL) body: any) {
//需要已登录
const userId = this.getUserId();
const bounds = await this.oauthBoundService.find({
where :{
where: {
userId,
}
},
});
return this.ok(bounds);
}
@Post('/providers', { description: Constants.per.guest })
@Post("/providers", { description: Constants.per.guest })
public async providers() {
const defineList = addonRegistry.getDefineList("oauth");
@@ -289,27 +276,27 @@ export class ConnectController extends BaseController {
const list = [];
for (const item of defineList) {
const type = item.name
const type = item.name;
const conf = oauthProviders[type];
const provider:any = {
const provider: any = {
...item,
}
delete provider.input
};
delete provider.input;
if (conf && conf.addonId) {
const addonEntity = await this.addonService.info(conf.addonId);
if (addonEntity) {
provider.addonId = conf.addonId;
provider.addonTitle = addonEntity.name;
const addon = await this.addonGetterService.getAddonById(conf.addonId,true,0,null) as IOauthProvider & { icon?: string; types?: OauthProviderType[] };
const {logoutUrl} = await addon.buildLogoutUrl({});
if (logoutUrl){
const addon = (await this.addonGetterService.getAddonById(conf.addonId, true, 0, null)) as IOauthProvider & { icon?: string; types?: OauthProviderType[] };
const { logoutUrl } = await addon.buildLogoutUrl({});
if (logoutUrl) {
provider.logoutUrl = logoutUrl;
}
if(addon.icon){
if (addon.icon) {
provider.icon = addon.icon;
}
if(addon.types?.length){
if (addon.types?.length) {
provider.types = addon.types;
}
}
@@ -1,9 +1,9 @@
import { ALL, Body, Controller, Inject, Post, Provide, RequestIP } from '@midwayjs/core';
import { BaseController, Constants, SysSettingsService } from '@certd/lib-server';
import { RegisterType, UserService } from '../../../modules/sys/authority/service/user-service.js';
import { CodeService } from '../../../modules/basic/service/code-service.js';
import { checkComm, checkPlus } from '@certd/plus-core';
import { InviteService } from '@certd/commercial-core';
import { ALL, Body, Controller, Inject, Post, Provide, RequestIP } from "@midwayjs/core";
import { BaseController, Constants, SysSettingsService } from "@certd/lib-server";
import { RegisterType, UserService } from "../../../modules/sys/authority/service/user-service.js";
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { checkComm, checkPlus } from "@certd/plus-core";
import { InviteService } from "@certd/commercial-core";
export type RegisterReq = {
type: RegisterType;
@@ -14,14 +14,14 @@ export type RegisterReq = {
phoneCode?: string;
validateCode: string;
captcha:any;
captcha: any;
inviteCode?: string;
};
/**
*/
@Provide()
@Controller('/api/')
@Controller("/api/")
export class RegisterController extends BaseController {
@Inject()
userService: UserService;
@@ -34,7 +34,7 @@ export class RegisterController extends BaseController {
@Inject()
inviteService: InviteService;
@Post('/register', { description: Constants.per.guest })
@Post("/register", { description: Constants.per.guest })
public async register(
@Body(ALL)
body: RegisterReq,
@@ -42,22 +42,22 @@ export class RegisterController extends BaseController {
) {
const sysPublicSettings = await this.sysSettingsService.getPublicSettings();
if (sysPublicSettings.registerEnabled === false) {
throw new Error('当前站点已禁止自助注册功能');
throw new Error("当前站点已禁止自助注册功能");
}
if (body.username && ["admin","certd"].includes(body.username) ) {
throw new Error('用户名不能为保留字');
if (body.username && ["admin", "certd"].includes(body.username)) {
throw new Error("用户名不能为保留字");
}
if (body.type === 'username') {
if (body.type === "username") {
if (sysPublicSettings.usernameRegisterEnabled === false) {
throw new Error('当前站点已禁止用户名注册功能');
throw new Error("当前站点已禁止用户名注册功能");
}
if (!body.username) {
throw new Error('用户名不能为空');
throw new Error("用户名不能为空");
}
await this.codeService.checkCaptcha(body.captcha,{remoteIp});
await this.codeService.checkCaptcha(body.captcha, { remoteIp });
const registerUser = {
username: body.username,
password: body.password,
@@ -66,9 +66,9 @@ export class RegisterController extends BaseController {
await this.inviteService.bindInvitee({ manager: txManager }, { inviteeUserId: registerUser.id, inviteCode: body.inviteCode });
});
return this.ok(newUser);
} else if (body.type === 'mobile') {
} else if (body.type === "mobile") {
if (sysPublicSettings.mobileRegisterEnabled === false) {
throw new Error('当前站点已禁止手机号注册功能');
throw new Error("当前站点已禁止手机号注册功能");
}
checkComm();
//验证短信验证码
@@ -88,9 +88,9 @@ export class RegisterController extends BaseController {
await this.inviteService.bindInvitee({ manager: txManager }, { inviteeUserId: registerUser.id, inviteCode: body.inviteCode });
});
return this.ok(newUser);
} else if (body.type === 'email') {
} else if (body.type === "email") {
if (sysPublicSettings.emailRegisterEnabled === false) {
throw new Error('当前站点已禁止Email注册功能');
throw new Error("当前站点已禁止Email注册功能");
}
checkPlus();
this.codeService.checkEmailCode({
@@ -1,18 +1,18 @@
import { Controller, Get, Inject, Provide } from '@midwayjs/core';
import { Constants, SysSettingsService } from '@certd/lib-server';
import { Controller, Get, Inject, Provide } from "@midwayjs/core";
import { Constants, SysSettingsService } from "@certd/lib-server";
@Provide()
@Controller('/')
@Controller("/")
export class HomeController {
@Inject()
sysSettingsService: SysSettingsService;
@Get('/robots.txt', { description: Constants.per.guest })
@Get("/robots.txt", { description: Constants.per.guest })
async robots(): Promise<string> {
const publicSettings = await this.sysSettingsService.getPublicSettings();
if (!publicSettings.robots) {
return 'User-agent: *\nDisallow: /';
return "User-agent: *\nDisallow: /";
} else {
return 'User-agent: *\nAllow: /';
return "User-agent: *\nAllow: /";
}
}
}
@@ -1,15 +1,5 @@
import { Config, Controller, Get, Inject, Provide } from "@midwayjs/core";
import {
BaseController,
Constants,
SysHeaderMenus,
SysInstallInfo,
SysPublicSettings,
SysSettingsService,
SysSiteEnv,
SysSiteInfo,
SysSuiteSetting
} from "@certd/lib-server";
import { BaseController, Constants, SysHeaderMenus, SysInstallInfo, SysPublicSettings, SysSettingsService, SysSiteEnv, SysSiteInfo, SysSuiteSetting } from "@certd/lib-server";
import { AppKey, getPlusInfo, isComm } from "@certd/plus-core";
import { SysInviteCommissionSetting } from "@certd/commercial-core";
import { cloneDeep } from "lodash-es";
@@ -54,7 +44,7 @@ export class BasicSettingsController extends BaseController {
}
const setting = await this.sysSettingsService.getSetting<SysSuiteSetting>(SysSuiteSetting);
return {
enabled: setting.enabled
enabled: setting.enabled,
};
}
@@ -72,7 +62,7 @@ export class BasicSettingsController extends BaseController {
public async getSiteEnv() {
const env: SysSiteEnv = {
agent: this.agentConfig
agent: this.agentConfig,
};
return env;
}
@@ -87,10 +77,9 @@ export class BasicSettingsController extends BaseController {
@Get("/productInfo", { description: Constants.per.guest })
async getProductInfo() {
const info = await http.request({
url: "https://app.handfree.work/certd/info.json"
url: "https://app.handfree.work/certd/info.json",
});
return this.ok(info);
}
@Get("/all", { description: Constants.per.guest })
@@ -118,7 +107,7 @@ export class BasicSettingsController extends BaseController {
inviteSetting,
app: {
time: new Date().getTime(),
version
version,
},
});
}
@@ -1,8 +1,8 @@
import {Body, Controller, Get, Inject, Post, Provide} from '@midwayjs/core';
import {Constants, NotFoundException, ParamException, SysInstallInfo, SysSettingsService} from '@certd/lib-server';
import {utils} from "@certd/basic";
import {hiddenStatus, SafeService} from "../../modules/sys/settings/safe-service.js";
import {IMidwayKoaContext} from "@midwayjs/koa";
import { Body, Controller, Get, Inject, Post, Provide } from "@midwayjs/core";
import { Constants, NotFoundException, ParamException, SysInstallInfo, SysSettingsService } from "@certd/lib-server";
import { utils } from "@certd/basic";
import { hiddenStatus, SafeService } from "../../modules/sys/settings/safe-service.js";
import { IMidwayKoaContext } from "@midwayjs/koa";
const unhiddenHtml = `
<html lang="en">
@@ -19,48 +19,47 @@ const unhiddenHtml = `
</body>
</html>
`
`;
@Provide()
@Controller('/api/unhidden')
@Controller("/api/unhidden")
export class UnhiddenController {
@Inject()
ctx: IMidwayKoaContext;
@Inject()
safeService: SafeService;
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
ctx: IMidwayKoaContext;
@Inject()
safeService: SafeService;
@Inject()
sysSettingsService: SysSettingsService;
@Post('/:randomPath', {description: Constants.per.guest})
async randomPath(@Body("password") password: any) {
await this.checkUnhiddenPath()
const hiddenSetting = await this.safeService.getHiddenSetting()
if (utils.hash.md5(password) === hiddenSetting.openPassword) {
//解锁
hiddenStatus.isHidden = false;
const setting = await this.sysSettingsService.getSetting<SysInstallInfo>(SysInstallInfo)
const bindUrl = setting.bindUrl
//解锁成功,跳转回首页,redirect
this.ctx.response.redirect(bindUrl || "/");
return
} else {
//密码错误
throw new ParamException('解锁密码错误');
}
@Post("/:randomPath", { description: Constants.per.guest })
async randomPath(@Body("password") password: any) {
await this.checkUnhiddenPath();
const hiddenSetting = await this.safeService.getHiddenSetting();
if (utils.hash.md5(password) === hiddenSetting.openPassword) {
//解锁
hiddenStatus.isHidden = false;
const setting = await this.sysSettingsService.getSetting<SysInstallInfo>(SysInstallInfo);
const bindUrl = setting.bindUrl;
//解锁成功,跳转回首页,redirect
this.ctx.response.redirect(bindUrl || "/");
return;
} else {
//密码错误
throw new ParamException("解锁密码错误");
}
}
@Get('/:randomPath', {description: Constants.per.guest})
async unhiddenGet() {
await this.checkUnhiddenPath()
this.ctx.response.body = unhiddenHtml
}
@Get("/:randomPath", { description: Constants.per.guest })
async unhiddenGet() {
await this.checkUnhiddenPath();
this.ctx.response.body = unhiddenHtml;
}
async checkUnhiddenPath() {
const hiddenSetting = await this.safeService.getHiddenSetting()
if (this.ctx.path != `/api/unhidden/${hiddenSetting.openPath}`) {
this.ctx.res.statusCode = 404
throw new NotFoundException("Page not found")
}
async checkUnhiddenPath() {
const hiddenSetting = await this.safeService.getHiddenSetting();
if (this.ctx.path != `/api/unhidden/${hiddenSetting.openPath}`) {
this.ctx.res.statusCode = 404;
throw new NotFoundException("Page not found");
}
}
}
@@ -1,18 +1,18 @@
import { BaseController, Constants } from '@certd/lib-server';
import { Controller, Get, Inject, Param, Post, Provide } from '@midwayjs/core';
import { PipelineService } from '../../modules/pipeline/service/pipeline-service.js';
import { BaseController, Constants } from "@certd/lib-server";
import { Controller, Get, Inject, Param, Post, Provide } from "@midwayjs/core";
import { PipelineService } from "../../modules/pipeline/service/pipeline-service.js";
/**
*/
@Provide()
@Controller('/api/webhook/')
@Controller("/api/webhook/")
export class WebhookController extends BaseController {
@Inject()
pipelineService: PipelineService;
@Get('/:webhookKey', { description: Constants.per.guest })
@Post('/:webhookKey', { description: Constants.per.guest })
async webhook(@Param('webhookKey') webhookKey: string): Promise<any> {
@Get("/:webhookKey", { description: Constants.per.guest })
@Post("/:webhookKey", { description: Constants.per.guest })
async webhook(@Param("webhookKey") webhookKey: string): Promise<any> {
await this.pipelineService.triggerByWebhook(webhookKey);
return this.ok({});
}
@@ -1,12 +1,12 @@
import { BaseController, Encryptor } from '@certd/lib-server';
import { OpenKey } from '../../modules/open/service/open-key-service.js';
import { BaseController, Encryptor } from "@certd/lib-server";
import { OpenKey } from "../../modules/open/service/open-key-service.js";
export class BaseOpenController extends BaseController {
ok(res: any) {
const openKey: OpenKey = this.ctx.openKey;
if (openKey.encrypt) {
const data = JSON.stringify(res);
const encryptor = new Encryptor(openKey.keySecret, 'hex');
const encryptor = new Encryptor(openKey.keySecret, "hex");
const encrypted = encryptor.encrypt(data);
return this.ok(encrypted);
}
@@ -10,39 +10,39 @@ import { ApiTags } from "@midwayjs/swagger";
export type CertGetReq = {
domains?: string;
certId: number;
autoApply?:boolean;
format?:string; //默认是所有,pem,der,p12,pfx,jks,one,p7b
autoApply?: boolean;
format?: string; //默认是所有,pem,der,p12,pfx,jks,one,p7b
};
/**
*/
@Provide()
@Controller('/api/v1/cert')
@ApiTags(['openapi'])
@Controller("/api/v1/cert")
@ApiTags(["openapi"])
export class OpenCertController extends BaseOpenController {
@Inject()
certInfoFacade: CertInfoFacade;
@Inject()
encryptService: EncryptService;
@Get('/get', { description: Constants.per.open, summary: "根据域名或ID获取证书,支持自动申请" })
@Post('/get', { description: Constants.per.open, summary: "根据域名或ID获取证书,支持自动申请" })
@Get("/get", { description: Constants.per.open, summary: "根据域名或ID获取证书,支持自动申请" })
@Post("/get", { description: Constants.per.open, summary: "根据域名或ID获取证书,支持自动申请" })
async get(@Body(ALL) bean: CertGetReq, @Query(ALL) query: CertGetReq) {
const openKey: OpenKey = this.ctx.openKey;
const userId = openKey.userId;
if (userId==null) {
if (userId == null) {
throw new CodeException(Constants.res.openKeyError);
}
const projectId = openKey.projectId;
const req = merge({}, bean, query)
const req = merge({}, bean, query);
const res: CertInfo = await this.certInfoFacade.getCertInfo({
userId,
domains: req.domains,
certId: req.certId,
autoApply: req.autoApply??false,
autoApply: req.autoApply ?? false,
format: req.format,
projectId,
});
@@ -6,7 +6,7 @@ import { AccessController } from "../../user/pipeline/access-controller.js";
* 授权
*/
@Provide()
@Controller('/api/sys/access')
@Controller("/api/sys/access")
export class SysAccessController extends AccessController {
@Inject()
service2: AccessService;
@@ -15,10 +15,11 @@ export class SysAccessController extends AccessController {
return this.service2;
}
async getProjectUserId(permission:string){
async getProjectUserId(permission: string) {
return {
projectId:null,userId:0
}
projectId: null,
userId: 0,
};
}
getUserId() {
@@ -26,58 +27,58 @@ export class SysAccessController extends AccessController {
return 0;
}
@Post('/page', { description: 'sys:settings:view' })
@Post("/page", { description: "sys:settings:view" })
async page(@Body(ALL) body: any) {
return await super.page(body);
}
@Post('/list', { description: 'sys:settings:view' })
@Post("/list", { description: "sys:settings:view" })
async list(@Body(ALL) body: any) {
return await super.list(body);
}
@Post('/add', { description: 'sys:settings:edit' })
@Post("/add", { description: "sys:settings:edit" })
async add(@Body(ALL) bean: any) {
return await super.add(bean);
}
@Post('/update', { description: 'sys:settings:edit' })
@Post("/update", { description: "sys:settings:edit" })
async update(@Body(ALL) bean: any) {
return await super.update(bean);
}
@Post('/info', { description: 'sys:settings:view' })
async info(@Query('id') id: number) {
@Post("/info", { description: "sys:settings:view" })
async info(@Query("id") id: number) {
return await super.info(id);
}
@Post('/delete', { description: 'sys:settings:edit' })
async delete(@Query('id') id: number) {
@Post("/delete", { description: "sys:settings:edit" })
async delete(@Query("id") id: number) {
return await super.delete(id);
}
@Post('/define', { description: 'sys:settings:view' })
async define(@Query('type') type: string) {
@Post("/define", { description: "sys:settings:view" })
async define(@Query("type") type: string) {
return await super.define(type);
}
@Post('/getSecretPlain', { description: 'sys:settings:view' })
@Post("/getSecretPlain", { description: "sys:settings:view" })
async getSecretPlain(@Body(ALL) body: { id: number; key: string }) {
const value = await this.service.getById(body.id, 0);
return this.ok(value[body.key]);
}
@Post('/accessTypeDict', { description: 'sys:settings:view' })
@Post("/accessTypeDict", { description: "sys:settings:view" })
async getAccessTypeDict() {
return await super.getAccessTypeDict();
}
@Post('/simpleInfo', { description: 'sys:settings:view' })
async simpleInfo(@Query('id') id: number) {
@Post("/simpleInfo", { description: "sys:settings:view" })
async simpleInfo(@Query("id") id: number) {
return await super.simpleInfo(id);
}
@Post('/getDictByIds', { description: 'sys:settings:view' })
async getDictByIds(@Body('ids') ids: number[]) {
return await super.getDictByIds(ids);
}
@Post("/getDictByIds", { description: "sys:settings:view" })
async getDictByIds(@Body("ids") ids: number[]) {
return await super.getDictByIds(ids);
}
}
@@ -1,5 +1,5 @@
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { BaseController, PlusService, SysInstallInfo, SysSettingsService } from '@certd/lib-server';
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, PlusService, SysInstallInfo, SysSettingsService } from "@certd/lib-server";
export type PreBindUserReq = {
userId: number;
@@ -10,7 +10,7 @@ export type BindUserReq = {
/**
*/
@Provide()
@Controller('/api/sys/account')
@Controller("/api/sys/account")
export class BasicController extends BaseController {
@Inject()
plusService: PlusService;
@@ -18,7 +18,7 @@ export class BasicController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@Post('/preBindUser', { description: 'sys:settings:edit' })
@Post("/preBindUser", { description: "sys:settings:edit" })
public async preBindUser(@Body(ALL) body: PreBindUserReq) {
// 设置缓存内容
if (body.userId == null || body.userId <= 0) {
@@ -28,7 +28,7 @@ export class BasicController extends BaseController {
return this.ok({});
}
@Post('/bindUser', { description: 'sys:settings:edit' })
@Post("/bindUser", { description: "sys:settings:edit" })
public async bindUser(@Body(ALL) body: BindUserReq) {
if (body.userId == null || body.userId <= 0) {
throw new Error("用户ID不能为空");
@@ -39,7 +39,7 @@ export class BasicController extends BaseController {
return this.ok({});
}
@Post('/unbindUser', { description: 'sys:settings:edit' })
@Post("/unbindUser", { description: "sys:settings:edit" })
public async unbindUser() {
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
installInfo.bindUserId = null;
@@ -47,7 +47,7 @@ export class BasicController extends BaseController {
return this.ok({});
}
@Post('/updateLicense', { description: 'sys:settings:edit' })
@Post("/updateLicense", { description: "sys:settings:edit" })
public async updateLicense(@Body(ALL) body: { license: string }) {
await this.plusService.updateLicense(body.license);
return this.ok(true);
@@ -3,7 +3,7 @@ import { AddonRequestHandleReq, AddonService, Constants } from "@certd/lib-serve
import { AddonController } from "../../user/addon/addon-controller.js";
@Provide()
@Controller('/api/sys/addon')
@Controller("/api/sys/addon")
export class SysAddonController extends AddonController {
@Inject()
service2: AddonService;
@@ -12,77 +12,77 @@ export class SysAddonController extends AddonController {
return this.service2;
}
async getProjectUserId(permission:string){
async getProjectUserId(permission: string) {
return {
projectId:null,userId:0 //0为系统级别
}
projectId: null,
userId: 0, //0为系统级别
};
}
getUserId() {
// checkComm();
return 0;
}
@Post('/page', { description: 'sys:settings:view' })
@Post("/page", { description: "sys:settings:view" })
async page(@Body(ALL) body: any) {
return await super.page(body);
}
@Post('/list', { description: 'sys:settings:view' })
@Post("/list", { description: "sys:settings:view" })
async list(@Body(ALL) body: any) {
return await super.list(body);
}
@Post('/add', { description: 'sys:settings:edit' })
@Post("/add", { description: "sys:settings:edit" })
async add(@Body(ALL) bean: any) {
return await super.add(bean);
}
@Post('/update', { description: 'sys:settings:edit' })
@Post("/update", { description: "sys:settings:edit" })
async update(@Body(ALL) bean: any) {
return await super.update(bean);
}
@Post('/info', { description: 'sys:settings:view' })
async info(@Query('id') id: number) {
@Post("/info", { description: "sys:settings:view" })
async info(@Query("id") id: number) {
return await super.info(id);
}
@Post('/delete', { description: 'sys:settings:edit' })
async delete(@Query('id') id: number) {
@Post("/delete", { description: "sys:settings:edit" })
async delete(@Query("id") id: number) {
return await super.delete(id);
}
@Post('/define', { description: Constants.per.authOnly })
async define(@Query('type') type: string,@Query('addonType') addonType: string) {
return await super.define(type,addonType);
@Post("/define", { description: Constants.per.authOnly })
async define(@Query("type") type: string, @Query("addonType") addonType: string) {
return await super.define(type, addonType);
}
@Post('/getTypeDict', { description: Constants.per.authOnly })
async getTypeDict(@Query('addonType') addonType: string) {
@Post("/getTypeDict", { description: Constants.per.authOnly })
async getTypeDict(@Query("addonType") addonType: string) {
return await super.getTypeDict(addonType);
}
@Post('/simpleInfo', { description: Constants.per.authOnly })
async simpleInfo(@Query('addonType') addonType: string,@Query('id') id: number) {
return await super.simpleInfo(addonType,id);
@Post("/simpleInfo", { description: Constants.per.authOnly })
async simpleInfo(@Query("addonType") addonType: string, @Query("id") id: number) {
return await super.simpleInfo(addonType, id);
}
@Post('/getDefaultId', { description: Constants.per.authOnly })
async getDefaultId(@Query('addonType') addonType: string) {
return await super.getDefaultId(addonType);
@Post("/getDefaultId", { description: Constants.per.authOnly })
async getDefaultId(@Query("addonType") addonType: string) {
return await super.getDefaultId(addonType);
}
@Post('/setDefault', { description: Constants.per.authOnly })
async setDefault(@Query('addonType') addonType: string,@Query('id') id: number) {
return await super.setDefault(addonType,id);
@Post("/setDefault", { description: Constants.per.authOnly })
async setDefault(@Query("addonType") addonType: string, @Query("id") id: number) {
return await super.setDefault(addonType, id);
}
@Post('/options', { description: Constants.per.authOnly })
async options(@Query('addonType') addonType: string) {
@Post("/options", { description: Constants.per.authOnly })
async options(@Query("addonType") addonType: string) {
return await super.options(addonType);
}
@Post('/handle', { description: Constants.per.authOnly })
@Post("/handle", { description: Constants.per.authOnly })
async handle(@Body(ALL) body: AddonRequestHandleReq) {
return await super.handle(body);
return await super.handle(body);
}
}
@@ -1,12 +1,12 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { CrudController } from '@certd/lib-server';
import { PermissionService } from '../../../modules/sys/authority/service/permission-service.js';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { CrudController } from "@certd/lib-server";
import { PermissionService } from "../../../modules/sys/authority/service/permission-service.js";
/**
* 权限资源
*/
@Provide()
@Controller('/api/sys/authority/permission')
@Controller("/api/sys/authority/permission")
export class PermissionController extends CrudController<PermissionService> {
@Inject()
service: PermissionService;
@@ -15,7 +15,7 @@ export class PermissionController extends CrudController<PermissionService> {
return this.service;
}
@Post('/page', { description: 'sys:auth:per:view' })
@Post("/page", { description: "sys:auth:per:view" })
async page(
@Body(ALL)
body
@@ -23,7 +23,7 @@ export class PermissionController extends CrudController<PermissionService> {
return await super.page(body);
}
@Post('/add', { description: 'sys:auth:per:add' })
@Post("/add", { description: "sys:auth:per:add" })
async add(
@Body(ALL)
bean
@@ -31,22 +31,22 @@ export class PermissionController extends CrudController<PermissionService> {
return await super.add(bean);
}
@Post('/update', { description: 'sys:auth:per:edit' })
@Post("/update", { description: "sys:auth:per:edit" })
async update(
@Body(ALL)
bean
) {
return await super.update(bean);
}
@Post('/delete', { description: 'sys:auth:per:remove' })
@Post("/delete", { description: "sys:auth:per:remove" })
async delete(
@Query('id')
@Query("id")
id: number
) {
return await super.delete(id);
}
@Post('/tree', { description: 'sys:auth:per:view' })
@Post("/tree", { description: "sys:auth:per:view" })
async tree() {
const tree = await this.service.tree({});
return this.ok(tree);
@@ -1,12 +1,12 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { CrudController } from '@certd/lib-server';
import { RoleService } from '../../../modules/sys/authority/service/role-service.js';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { CrudController } from "@certd/lib-server";
import { RoleService } from "../../../modules/sys/authority/service/role-service.js";
/**
* 系统用户
*/
@Provide()
@Controller('/api/sys/authority/role')
@Controller("/api/sys/authority/role")
export class RoleController extends CrudController<RoleService> {
@Inject()
service: RoleService;
@@ -15,7 +15,7 @@ export class RoleController extends CrudController<RoleService> {
return this.service;
}
@Post('/page', { description: 'sys:auth:role:view' })
@Post("/page", { description: "sys:auth:role:view" })
async page(
@Body(ALL)
body
@@ -23,13 +23,13 @@ export class RoleController extends CrudController<RoleService> {
return await super.page(body);
}
@Post('/list', { description: 'sys:auth:role:view' })
@Post("/list", { description: "sys:auth:role:view" })
async list() {
const ret = await this.service.find({});
return this.ok(ret);
}
@Post('/add', { description: 'sys:auth:role:add' })
@Post("/add", { description: "sys:auth:role:add" })
async add(
@Body(ALL)
bean
@@ -37,36 +37,36 @@ export class RoleController extends CrudController<RoleService> {
return await super.add(bean);
}
@Post('/update', { description: 'sys:auth:role:edit' })
@Post("/update", { description: "sys:auth:role:edit" })
async update(
@Body(ALL)
bean
) {
return await super.update(bean);
}
@Post('/delete', { description: 'sys:auth:role:remove' })
@Post("/delete", { description: "sys:auth:role:remove" })
async delete(
@Query('id')
@Query("id")
id: number
) {
if (id === 1) {
throw new Error('不能删除默认的管理员角色');
throw new Error("不能删除默认的管理员角色");
}
return await super.delete(id);
}
@Post('/getPermissionTree', { description: 'sys:auth:role:view' })
@Post("/getPermissionTree", { description: "sys:auth:role:view" })
async getPermissionTree(
@Query('id')
@Query("id")
id: number
) {
const ret = await this.service.getPermissionTreeByRoleId(id);
return this.ok(ret);
}
@Post('/getPermissionIds', { description: 'sys:auth:role:view' })
@Post("/getPermissionIds", { description: "sys:auth:role:view" })
async getPermissionIds(
@Query('id')
@Query("id")
id: number
) {
const ret = await this.service.getPermissionIdsByRoleId(id);
@@ -78,8 +78,8 @@ export class RoleController extends CrudController<RoleService> {
* @param roleId
* @param permissionIds
*/
@Post('/authz', { description: 'sys:auth:role:edit' })
async authz(@Body('roleId') roleId, @Body('permissionIds') permissionIds) {
@Post("/authz", { description: "sys:auth:role:edit" })
async authz(@Body("roleId") roleId, @Body("permissionIds") permissionIds) {
await this.service.authz(roleId, permissionIds);
return this.ok(null);
}
@@ -1,17 +1,17 @@
import {Provide, Controller, Post, Inject, Body, Query, ALL} from '@midwayjs/core';
import {UserService} from '../../../modules/sys/authority/service/user-service.js';
import {CrudController} from '@certd/lib-server';
import {RoleService} from '../../../modules/sys/authority/service/role-service.js';
import {PermissionService} from '../../../modules/sys/authority/service/permission-service.js';
import {Constants} from '@certd/lib-server';
import {In} from 'typeorm';
import {LoginService} from "../../../modules/login/service/login-service.js";
import { Provide, Controller, Post, Inject, Body, Query, ALL } from "@midwayjs/core";
import { UserService } from "../../../modules/sys/authority/service/user-service.js";
import { CrudController } from "@certd/lib-server";
import { RoleService } from "../../../modules/sys/authority/service/role-service.js";
import { PermissionService } from "../../../modules/sys/authority/service/permission-service.js";
import { Constants } from "@certd/lib-server";
import { In } from "typeorm";
import { LoginService } from "../../../modules/login/service/login-service.js";
/**
* 系统用户
*/
@Provide()
@Controller('/api/sys/authority/user')
@Controller("/api/sys/authority/user")
export class UserController extends CrudController<UserService> {
@Inject()
service: UserService;
@@ -28,8 +28,8 @@ export class UserController extends CrudController<UserService> {
return this.service;
}
@Post('/getSimpleUserByIds', {description: 'sys:auth:user:view'})
async getSimpleUserByIds(@Body('ids') ids: number[]) {
@Post("/getSimpleUserByIds", { description: "sys:auth:user:view" })
async getSimpleUserByIds(@Body("ids") ids: number[]) {
const users = await this.service.find({
select: {
id: true,
@@ -46,8 +46,7 @@ export class UserController extends CrudController<UserService> {
return this.ok(users);
}
@Post('/getSimpleUsers', {description: 'sys:auth:user:view'})
@Post("/getSimpleUsers", { description: "sys:auth:user:view" })
async getSimpleUsers() {
const users = await this.service.find({
select: {
@@ -61,10 +60,10 @@ export class UserController extends CrudController<UserService> {
return this.ok(users);
}
@Post('/page', {description: 'sys:auth:user:view'})
@Post("/page", { description: "sys:auth:user:view" })
async page(
@Body(ALL)
body
body
) {
const ret = await super.page(body);
@@ -93,32 +92,32 @@ export class UserController extends CrudController<UserService> {
return ret;
}
@Post('/add', {description: 'sys:auth:user:add'})
@Post("/add", { description: "sys:auth:user:add" })
async add(
@Body(ALL)
bean
bean
) {
return await super.add(bean);
}
@Post('/update', {description: 'sys:auth:user:edit'})
@Post("/update", { description: "sys:auth:user:edit" })
async update(
@Body(ALL)
bean
bean
) {
return await super.update(bean);
}
@Post('/delete', {description: 'sys:auth:user:remove'})
@Post("/delete", { description: "sys:auth:user:remove" })
async delete(
@Query('id')
id: number
@Query("id")
id: number
) {
if (id === 1) {
throw new Error('不能删除默认的管理员角色');
throw new Error("不能删除默认的管理员角色");
}
if (id === 3) {
throw new Error('不能删除默认的普通用户角色');
throw new Error("不能删除默认的普通用户角色");
}
return await super.delete(id);
}
@@ -126,12 +125,12 @@ export class UserController extends CrudController<UserService> {
/**
* 解除登录锁定
*/
@Post('/unlockBlock', {description: "sys:auth:user:edit"})
public async unlockBlock(@Body('id') id: number) {
const info = await this.service.info(id, ['password']);
this.loginService.clearCacheOnSuccess(info.username)
@Post("/unlockBlock", { description: "sys:auth:user:edit" })
public async unlockBlock(@Body("id") id: number) {
const info = await this.service.info(id, ["password"]);
this.loginService.clearCacheOnSuccess(info.username);
if (info.mobile) {
this.loginService.clearCacheOnSuccess(info.mobile)
this.loginService.clearCacheOnSuccess(info.mobile);
}
return this.ok(info);
}
@@ -139,17 +138,17 @@ export class UserController extends CrudController<UserService> {
/**
* 当前登录用户的个人信息
*/
@Post('/mine', {description: Constants.per.authOnly})
@Post("/mine", { description: Constants.per.authOnly })
public async mine() {
const id = this.getUserId();
const info = await this.service.info(id, ['password']);
const info = await this.service.info(id, ["password"]);
return this.ok(info);
}
/**
* 当前登录用户的权限列表
*/
@Post('/permissions', {description: Constants.per.authOnly})
@Post("/permissions", { description: Constants.per.authOnly })
public async permissions() {
const id = this.getUserId();
const permissions = await this.service.getUserPermissions(id);
@@ -159,15 +158,11 @@ export class UserController extends CrudController<UserService> {
/**
* 当前登录用户的权限树形列表
*/
@Post('/permissionTree', {description: Constants.per.authOnly})
@Post("/permissionTree", { description: Constants.per.authOnly })
public async permissionTree() {
const id = this.getUserId();
const permissions = await this.service.getUserPermissions(id);
const tree = this.permissionService.buildTree(permissions);
return this.ok(tree);
}
}
@@ -1,13 +1,13 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { CrudController } from '@certd/lib-server';
import { merge } from 'lodash-es';
import { CnameProviderService } from '../../../modules/cname/service/cname-provider-service.js';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { CrudController } from "@certd/lib-server";
import { merge } from "lodash-es";
import { CnameProviderService } from "../../../modules/cname/service/cname-provider-service.js";
/**
* 授权
*/
@Provide()
@Controller('/api/sys/cname/provider')
@Controller("/api/sys/cname/provider")
export class CnameRecordController extends CrudController<CnameProviderService> {
@Inject()
service: CnameProviderService;
@@ -16,18 +16,18 @@ export class CnameRecordController extends CrudController<CnameProviderService>
return this.service;
}
@Post('/page', { description: 'sys:settings:view' })
@Post("/page", { description: "sys:settings:view" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
return await super.page(body);
}
@Post('/list', { description: 'sys:settings:view' })
@Post("/list", { description: "sys:settings:view" })
async list(@Body(ALL) body: any) {
return super.list(body);
}
@Post('/add', { description: 'sys:settings:edit' })
@Post("/add", { description: "sys:settings:edit" })
async add(@Body(ALL) bean: any) {
const def: any = {
isDefault: false,
@@ -38,36 +38,36 @@ export class CnameRecordController extends CrudController<CnameProviderService>
return super.add(bean);
}
@Post('/update', { description: 'sys:settings:edit' })
@Post("/update", { description: "sys:settings:edit" })
async update(@Body(ALL) bean: any) {
bean.userId = this.getUserId();
return super.update(bean);
}
@Post('/info', { description: 'sys:settings:view' })
async info(@Query('id') id: number) {
@Post("/info", { description: "sys:settings:view" })
async info(@Query("id") id: number) {
return super.info(id);
}
@Post('/delete', { description: 'sys:settings:edit' })
async delete(@Query('id') id: number) {
@Post("/delete", { description: "sys:settings:edit" })
async delete(@Query("id") id: number) {
return super.delete(id);
}
@Post('/deleteByIds', { description: 'sys:settings:edit' })
async deleteByIds(@Body('ids') ids: number[]) {
@Post("/deleteByIds", { description: "sys:settings:edit" })
async deleteByIds(@Body("ids") ids: number[]) {
const res = await this.service.delete(ids);
return this.ok(res);
}
@Post('/setDefault', { description: 'sys:settings:edit' })
async setDefault(@Body('id') id: number) {
@Post("/setDefault", { description: "sys:settings:edit" })
async setDefault(@Body("id") id: number) {
await this.service.setDefault(id);
return this.ok();
}
@Post('/setDisabled', { description: 'sys:settings:edit' })
async setDisabled(@Body('id') id: number, @Body('disabled') disabled: boolean) {
@Post("/setDisabled", { description: "sys:settings:edit" })
async setDisabled(@Body("id") id: number, @Body("disabled") disabled: boolean) {
await this.service.setDisabled(id, disabled);
return this.ok();
}
@@ -1,9 +1,9 @@
import { Controller, Inject, Post, Provide } from '@midwayjs/core';
import { BaseController } from '@certd/lib-server';
import { UserService } from '../../../modules/sys/authority/service/user-service.js';
import { RoleService } from '../../../modules/sys/authority/service/role-service.js';
import { PipelineService } from '../../../modules/pipeline/service/pipeline-service.js';
import { HistoryService } from '../../../modules/pipeline/service/history-service.js';
import { Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController } from "@certd/lib-server";
import { UserService } from "../../../modules/sys/authority/service/user-service.js";
import { RoleService } from "../../../modules/sys/authority/service/role-service.js";
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { HistoryService } from "../../../modules/pipeline/service/history-service.js";
export type ChartItem = {
name: string;
@@ -19,7 +19,7 @@ export type SysStatisticCount = {
/**
*/
@Provide()
@Controller('/api/sys/statistic/')
@Controller("/api/sys/statistic/")
export class SysStatisticController extends BaseController {
@Inject()
userService: UserService;
@@ -31,7 +31,7 @@ export class SysStatisticController extends BaseController {
@Inject()
historyService: HistoryService;
@Post('/count', { description: 'sys:settings:view' })
@Post("/count", { description: "sys:settings:view" })
public async count() {
const userCount = await this.userService.count();
const userRegisterCountPerDay = await this.userService.registerCountPerDay({ days: 7 });
@@ -40,7 +40,7 @@ export class SysProjectController extends CrudController<ProjectEntity> {
bean.userId = this.getUserId();
return super.add({
...bean,
userId:-1, //企业用户id固定为-1
userId: -1, //企业用户id固定为-1
adminId: bean.userId,
});
}
@@ -55,12 +55,12 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
if (!bean.id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(bean.id)
const projectId = await this.service.getProjectId(bean.id);
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId: projectId,
});
const res =await this.service.update({
const res = await this.service.update({
id: bean.id,
permission: bean.permission,
status: bean.status,
@@ -70,13 +70,13 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
@Post("/info", { description: "sys:settings:view" })
async info(@Query("id") id: number) {
if (!id) {
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
const projectId = await this.service.getProjectId(id);
await this.projectService.checkReadPermission({
userId: this.getUserId(),
projectId:projectId,
projectId: projectId,
});
return super.info(id);
}
@@ -86,10 +86,10 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
const projectId = await this.service.getProjectId(id);
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId:projectId,
projectId: projectId,
});
return super.delete(id);
}
@@ -100,14 +100,14 @@ export class SysProjectMemberController extends CrudController<ProjectMemberEnti
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
const projectId = await this.service.getProjectId(id);
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId:projectId,
projectId: projectId,
});
await this.service.delete(id as any);
}
return this.ok({});
}
}
@@ -1,46 +1,39 @@
import { BaseController } from '@certd/lib-server';
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { NetTestService } from '../../../modules/sys/nettest/nettest-service.js';
import { BaseController } from "@certd/lib-server";
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { NetTestService } from "../../../modules/sys/nettest/nettest-service.js";
@Provide()
@Controller('/api/sys/nettest/')
@Controller("/api/sys/nettest/")
export class SysNetTestController extends BaseController {
@Inject()
netTestService: NetTestService;
@Post('/domainResolve', { description: 'sys:settings:view' })
@Post("/domainResolve", { description: "sys:settings:view" })
public async domainResolve(@Body(ALL) body: { domain: string }) {
const { domain } = body;
const result = await this.netTestService.domainResolve(domain);
return this.ok(result);
}
// ping
@Post('/ping', { description: 'sys:settings:view' })
@Post("/ping", { description: "sys:settings:view" })
public async ping(@Body(ALL) body: { domain: string }) {
const { domain } = body;
const result = await this.netTestService.ping(domain);
return this.ok(result);
}
// telnet
@Post('/telnet', { description: 'sys:settings:view' })
public async telnet(@Body(ALL) body: { domain: string, port: number }) {
// telnet
@Post("/telnet", { description: "sys:settings:view" })
public async telnet(@Body(ALL) body: { domain: string; port: number }) {
const { domain, port } = body;
const result = await this.netTestService.telnet(domain, port);
return this.ok(result);
}
// telnet
@Post('/serverInfo', { description: 'sys:settings:view' })
// telnet
@Post("/serverInfo", { description: "sys:settings:view" })
public async serverInfo() {
const result = await this.netTestService.serverInfo();
return this.ok(result);
}
@@ -1,17 +1,13 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { merge } from 'lodash-es';
import { CrudController } from '@certd/lib-server';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { merge } from "lodash-es";
import { CrudController } from "@certd/lib-server";
import { PluginImportReq, PluginService } from "../../../modules/plugin/service/plugin-service.js";
import {
CommPluginConfig,
PluginConfig,
PluginConfigService
} from '../../../modules/plugin/service/plugin-config-service.js';
import { CommPluginConfig, PluginConfig, PluginConfigService } from "../../../modules/plugin/service/plugin-config-service.js";
/**
* 插件
*/
@Provide()
@Controller('/api/sys/plugin')
@Controller("/api/sys/plugin")
export class PluginController extends CrudController<PluginService> {
@Inject()
service: PluginService;
@@ -23,18 +19,18 @@ export class PluginController extends CrudController<PluginService> {
return this.service;
}
@Post('/page', { description: 'sys:settings:view' })
@Post("/page", { description: "sys:settings:view" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
return await super.page(body);
}
@Post('/list', { description: 'sys:settings:view' })
@Post("/list", { description: "sys:settings:view" })
async list(@Body(ALL) body: any) {
return super.list(body);
}
@Post('/add', { description: 'sys:settings:edit' })
@Post("/add", { description: "sys:settings:edit" })
async add(@Body(ALL) bean: any) {
const def: any = {
isDefault: false,
@@ -44,69 +40,68 @@ export class PluginController extends CrudController<PluginService> {
return super.add(bean);
}
@Post('/update', { description: 'sys:settings:edit' })
@Post("/update", { description: "sys:settings:edit" })
async update(@Body(ALL) bean: any) {
const res = await super.update(bean);
return res
return res;
}
@Post('/info', { description: 'sys:settings:view' })
async info(@Query('id') id: number) {
@Post("/info", { description: "sys:settings:view" })
async info(@Query("id") id: number) {
return super.info(id);
}
@Post('/delete', { description: 'sys:settings:edit' })
async delete(@Query('id') id: number) {
@Post("/delete", { description: "sys:settings:edit" })
async delete(@Query("id") id: number) {
const res = await this.service.deleteByIds([id]);
return this.ok(res);
}
@Post('/deleteByIds', { description: 'sys:settings:edit' })
async deleteByIds(@Body('ids') ids: number[]) {
@Post("/deleteByIds", { description: "sys:settings:edit" })
async deleteByIds(@Body("ids") ids: number[]) {
const res = await this.service.deleteByIds(ids);
return this.ok(res);
}
@Post('/setDisabled', { description: 'sys:settings:edit' })
@Post("/setDisabled", { description: "sys:settings:edit" })
async setDisabled(@Body(ALL) body: { id: number; name: string; type: string; disabled: boolean }) {
await this.service.setDisabled(body);
return this.ok();
}
@Post('/getCommPluginConfigs', { description: 'sys:settings:view' })
@Post("/getCommPluginConfigs", { description: "sys:settings:view" })
async getCommPluginConfigs() {
const res = await this.pluginConfigService.getCommPluginConfig();
return this.ok(res);
}
@Post('/saveCommPluginConfigs', { description: 'sys:settings:edit' })
@Post("/saveCommPluginConfigs", { description: "sys:settings:edit" })
async saveCommPluginConfigs(@Body(ALL) body: CommPluginConfig) {
const res = await this.pluginConfigService.saveCommPluginConfig(body);
return this.ok(res);
}
@Post('/getPluginByName', { description: 'sys:settings:view' })
async getPluginByName(@Body('name') name: string) {
@Post("/getPluginByName", { description: "sys:settings:view" })
async getPluginByName(@Body("name") name: string) {
const res = await this.pluginConfigService.getPluginConfig({
name: name,
type: 'builtIn'
type: "builtIn",
});
return this.ok(res);
}
@Post('/saveSetting', { description: 'sys:settings:edit' })
@Post("/saveSetting", { description: "sys:settings:edit" })
async saveSetting(@Body(ALL) body: PluginConfig) {
const res = await this.pluginConfigService.savePluginConfig(body);
return this.ok(res);
}
@Post('/import', { description: 'sys:settings:edit' })
@Post("/import", { description: "sys:settings:edit" })
async import(@Body(ALL) body: PluginImportReq) {
const res = await this.service.importPlugin(body);
return this.ok(res);
}
@Post('/export', { description: 'sys:settings:edit' })
async export(@Body('id') id: number) {
@Post("/export", { description: "sys:settings:edit" })
async export(@Body("id") id: number) {
const res = await this.service.exportPlugin(id);
return this.ok(res);
}
@@ -1,11 +1,11 @@
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { BaseController, PlusService, SysInstallInfo, SysSettingsService } from '@certd/lib-server';
import { logger } from '@certd/basic';
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, PlusService, SysInstallInfo, SysSettingsService } from "@certd/lib-server";
import { logger } from "@certd/basic";
/**
*/
@Provide()
@Controller('/api/sys/plus')
@Controller("/api/sys/plus")
export class SysPlusController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@@ -13,7 +13,7 @@ export class SysPlusController extends BaseController {
@Inject()
plusService: PlusService;
@Post('/active', { description: 'sys:settings:edit' })
@Post("/active", { description: "sys:settings:edit" })
async active(@Body(ALL) body) {
const { code, inviteCode } = body;
@@ -21,33 +21,32 @@ export class SysPlusController extends BaseController {
return this.ok(true);
}
@Post('/bindUrl', { description: 'sys:settings:edit' })
async bindUrl(@Body(ALL) body: { url: string ,url2?:string }) {
const { url,url2 } = body;
@Post("/bindUrl", { description: "sys:settings:edit" })
async bindUrl(@Body(ALL) body: { url: string; url2?: string }) {
const { url, url2 } = body;
await this.plusService.register();
const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo);
await this.plusService.bindUrl(url,url2);
await this.plusService.bindUrl(url, url2);
installInfo.bindUrl = url;
installInfo.bindUrl2 = url2;
await this.sysSettingsService.saveSetting(installInfo);
//重新验证vip
try{
try {
await this.plusService.verify();
}catch(e){
} catch (e) {
logger.error(`验证配置失败:${e}`);
}
return this.ok(true);
}
@Post('/getVipTrial', { description: 'sys:settings:edit' })
async getVipTrial(@Body("vipType") vipType?:string) {
@Post("/getVipTrial", { description: "sys:settings:edit" })
async getVipTrial(@Body("vipType") vipType?: string) {
const res = await this.plusService.getVipTrial(vipType);
return this.ok(res);
}
@Post('/getTodayVipOrderCount', { description: 'sys:settings:edit' })
@Post("/getTodayVipOrderCount", { description: "sys:settings:edit" })
async getTodayVipOrderCount() {
const res = await this.plusService.getTodayOrderCount();
return this.ok(res);
@@ -3,21 +3,18 @@ import { BaseController, SysSafeSetting } from "@certd/lib-server";
import { cloneDeep } from "lodash-es";
import { SafeService } from "../../../modules/sys/settings/safe-service.js";
/**
*/
@Provide()
@Controller('/api/sys/settings/safe')
@Controller("/api/sys/settings/safe")
export class SysSettingsController extends BaseController {
@Inject()
safeService: SafeService;
@Post("/get", { description: "sys:settings:view" })
async safeGet() {
const res = await this.safeService.getSafeSetting()
const clone:SysSafeSetting = cloneDeep(res);
const res = await this.safeService.getSafeSetting();
const clone: SysSafeSetting = cloneDeep(res);
delete clone.hidden?.openPassword;
return this.ok(clone);
}
@@ -1,14 +1,5 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query, RequestIP } from "@midwayjs/core";
import {
addonRegistry,
AddonService,
CrudController,
SysPrivateSettings,
SysPublicSettings,
SysSafeSetting,
SysSettingsEntity,
SysSettingsService
} from "@certd/lib-server";
import { addonRegistry, AddonService, CrudController, SysPrivateSettings, SysPublicSettings, SysSafeSetting, SysSettingsEntity, SysSettingsService } from "@certd/lib-server";
import { cloneDeep, merge } from "lodash-es";
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { UserSettingsService } from "../../../modules/mine/service/user-settings-service.js";
@@ -17,11 +8,10 @@ import { http, logger, utils } from "@certd/basic";
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { SmsServiceFactory } from "../../../modules/basic/sms/factory.js";
/**
*/
@Provide()
@Controller('/api/sys/settings')
@Controller("/api/sys/settings")
export class SysSettingsController extends CrudController<SysSettingsService> {
@Inject()
service: SysSettingsService;
@@ -31,84 +21,84 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
pipelineService: PipelineService;
@Inject()
codeService: CodeService;
@Inject()
@Inject()
addonService: AddonService;
getService() {
return this.service;
}
@Post('/page', { description: 'sys:settings:view' })
@Post("/page", { description: "sys:settings:view" })
async page(@Body(ALL) body) {
return super.page(body);
}
@Post('/list', { description: 'sys:settings:view' })
@Post("/list", { description: "sys:settings:view" })
async list(@Body(ALL) body) {
return super.list(body);
}
@Post('/add', { description: 'sys:settings:edit' })
@Post("/add", { description: "sys:settings:edit" })
async add(@Body(ALL) bean) {
return super.add(bean);
}
@Post('/update', { description: 'sys:settings:edit' })
@Post("/update", { description: "sys:settings:edit" })
async update(@Body(ALL) bean) {
await this.service.checkUserId(bean.id, this.getUserId());
return super.update(bean);
}
@Post('/info', { description: 'sys:settings:view' })
async info(@Query('id') id: number) {
@Post("/info", { description: "sys:settings:view" })
async info(@Query("id") id: number) {
await this.service.checkUserId(id, this.getUserId());
return super.info(id);
}
@Post('/delete', { description: 'sys:settings:edit' })
async delete(@Query('id') id: number) {
@Post("/delete", { description: "sys:settings:edit" })
async delete(@Query("id") id: number) {
await this.service.checkUserId(id, this.getUserId());
return super.delete(id);
}
@Post('/save', { description: 'sys:settings:edit' })
@Post("/save", { description: "sys:settings:edit" })
async save(@Body(ALL) bean: SysSettingsEntity) {
await this.service.save(bean);
return this.ok({});
}
@Post('/get', { description: 'sys:settings:view' })
async get(@Query('key') key: string) {
@Post("/get", { description: "sys:settings:view" })
async get(@Query("key") key: string) {
const entity = await this.service.getByKey(key);
return this.ok(entity);
}
// savePublicSettings
@Post('/getEmailSettings', { description: 'sys:settings:view' })
@Post("/getEmailSettings", { description: "sys:settings:view" })
async getEmailSettings(@Body(ALL) body) {
const conf = await getEmailSettings(this.service, this.userSettingsService);
return this.ok(conf);
}
@Post('/getEmailTemplates', { description: 'sys:settings:view' })
@Post("/getEmailTemplates", { description: "sys:settings:view" })
async getEmailTemplates(@Body(ALL) body) {
const conf = await getEmailSettings(this.service, this.userSettingsService);
const templates = conf.templates || {}
const templates = conf.templates || {};
const emailTemplateProviders = await this.addonService.getDefineList("emailTemplate")
const emailTemplateProviders = await this.addonService.getDefineList("emailTemplate");
const proviers = []
const proviers = [];
for (const item of emailTemplateProviders) {
const templateConf = templates[item.name] || {}
const templateConf = templates[item.name] || {};
proviers.push({
name: item.name,
title: item.title,
addonId : templateConf.addonId,
})
addonId: templateConf.addonId,
});
}
return this.ok(proviers);
}
@Post('/saveEmailSettings', { description: 'sys:settings:edit' })
@Post("/saveEmailSettings", { description: "sys:settings:edit" })
async saveEmailSettings(@Body(ALL) body) {
const conf = await getEmailSettings(this.service, this.userSettingsService);
merge(conf, body);
@@ -116,7 +106,7 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
return this.ok(conf);
}
@Post('/getSysSettings', { description: 'sys:settings:view' })
@Post("/getSysSettings", { description: "sys:settings:view" })
async getSysSettings() {
const publicSettings = await this.service.getPublicSettings();
let privateSettings = await this.service.getPrivateSettings();
@@ -125,7 +115,7 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
}
// savePublicSettings
@Post('/saveSysSettings', { description: 'sys:settings:edit' })
@Post("/saveSysSettings", { description: "sys:settings:edit" })
async saveSysSettings(@Body(ALL) body: { public: SysPublicSettings; private: SysPrivateSettings }) {
const publicSettings = await this.service.getPublicSettings();
const privateSettings = await this.service.getPrivateSettings();
@@ -136,21 +126,21 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
return this.ok({});
}
@Post('/stopOtherUserTimer', { description: 'sys:settings:edit' })
@Post("/stopOtherUserTimer", { description: "sys:settings:edit" })
async stopOtherUserTimer(@Body(ALL) body) {
await this.pipelineService.stopOtherUserPipeline(1);
return this.ok({});
}
@Post('/testProxy', { description: 'sys:settings:edit' })
@Post("/testProxy", { description: "sys:settings:edit" })
async testProxy(@Body(ALL) body) {
const google = 'https://www.google.com/';
const baidu = 'https://www.baidu.com/';
const google = "https://www.google.com/";
const baidu = "https://www.baidu.com/";
let googleRes = false;
try {
await http.request({
url: google,
method: 'GET',
method: "GET",
timeout: 5000,
logRes: false,
logParams: false,
@@ -158,13 +148,13 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
googleRes = true;
} catch (e) {
googleRes = e.message;
logger.info('test google error:', e);
logger.info("test google error:", e);
}
let baiduRes = false;
try {
await http.request({
url: baidu,
method: 'GET',
method: "GET",
timeout: 5000,
logRes: false,
logParams: false,
@@ -172,7 +162,7 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
baiduRes = true;
} catch (e) {
baiduRes = e.message;
logger.info('test baidu error:', e);
logger.info("test baidu error:", e);
}
return this.ok({
google: googleRes,
@@ -180,51 +170,48 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
});
}
@Post('/testSms', { description: 'sys:settings:edit' })
@Post("/testSms", { description: "sys:settings:edit" })
async testSms(@Body(ALL) body) {
await this.codeService.sendSmsCode(body.phoneCode, body.mobile );
await this.codeService.sendSmsCode(body.phoneCode, body.mobile);
return this.ok({});
}
@Post('/getSmsTypeDefine', { description: 'sys:settings:view' })
async getSmsTypeDefine(@Body('type') type: string) {
const define =await SmsServiceFactory.getDefine(type);
@Post("/getSmsTypeDefine", { description: "sys:settings:view" })
async getSmsTypeDefine(@Body("type") type: string) {
const define = await SmsServiceFactory.getDefine(type);
return this.ok(define);
}
@Post("/safe/get", { description: "sys:settings:view" })
async safeGet() {
const res = await this.service.getSetting<SysSafeSetting>(SysSafeSetting);
const clone:SysSafeSetting = cloneDeep(res);
const clone: SysSafeSetting = cloneDeep(res);
delete clone.hidden?.openPassword;
return this.ok(clone);
}
@Post("/safe/save", { description: "sys:settings:edit" })
async safeSave(@Body(ALL) body: any) {
if(body.hidden.openPassword){
if (body.hidden.openPassword) {
body.hidden.openPassword = utils.hash.md5(body.hidden.openPassword);
}
const blankSetting = new SysSafeSetting()
const blankSetting = new SysSafeSetting();
const setting = await this.service.getSetting<SysSafeSetting>(SysSafeSetting);
const newSetting = merge(blankSetting,cloneDeep(setting), body);
if(newSetting.hidden?.enabled && !newSetting.hidden?.openPassword){
throw new Error("首次设置需要填写解锁密码")
const newSetting = merge(blankSetting, cloneDeep(setting), body);
if (newSetting.hidden?.enabled && !newSetting.hidden?.openPassword) {
throw new Error("首次设置需要填写解锁密码");
}
await this.service.saveSetting(blankSetting);
return this.ok({});
}
@Post("/captchaTest", { description: "sys:settings:edit" })
async captchaTest(@Body(ALL) body: any,@RequestIP() remoteIp: string) {
await this.codeService.checkCaptcha(body,{remoteIp});
async captchaTest(@Body(ALL) body: any, @RequestIP() remoteIp: string) {
await this.codeService.checkCaptcha(body, { remoteIp });
return this.ok({});
}
@Post('/oauth/providers', { description: 'sys:settings:view' })
@Post("/oauth/providers", { description: "sys:settings:view" })
async oauthProviders() {
const list = await addonRegistry.getDefineList("oauth");
return this.ok(list);
@@ -1,13 +1,5 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import {
AddonDefine,
AddonRequestHandleReq,
AddonService,
Constants,
CrudController,
newAddon,
ValidateException
} from "@certd/lib-server";
import { AddonDefine, AddonRequestHandleReq, AddonService, Constants, CrudController, newAddon, ValidateException } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { checkPlus } from "@certd/plus-core";
import { http, logger, utils } from "@certd/basic";
@@ -19,14 +11,14 @@ import { ApiTags } from "@midwayjs/swagger";
*/
@Provide()
@Controller("/api/addon")
@ApiTags(['addon'])
@ApiTags(["addon"])
export class AddonController extends CrudController<AddonService> {
@Inject()
service: AddonService;
@Inject()
authService: AuthService;
@Inject()
taskServiceBuilder:TaskServiceBuilder
taskServiceBuilder: TaskServiceBuilder;
getService(): AddonService {
return this.service;
@@ -34,7 +26,7 @@ export class AddonController extends CrudController<AddonService> {
@Post("/page", { description: Constants.per.authOnly, summary: "查询Addon分页列表" })
async page(@Body(ALL) body) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
delete body.query.userId;
body.query.projectId = projectId;
@@ -45,14 +37,14 @@ export class AddonController extends CrudController<AddonService> {
query: body.query,
page: body.page,
sort: body.sort,
buildQuery
buildQuery,
});
return this.ok(res);
}
@Post("/list", { description: Constants.per.authOnly, summary: "查询Addon列表" })
async list(@Body(ALL) body) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId;
@@ -61,7 +53,7 @@ export class AddonController extends CrudController<AddonService> {
@Post("/add", { description: Constants.per.authOnly, summary: "添加Addon" })
async add(@Body(ALL) bean) {
const {userId,projectId} = await this.getProjectUserIdRead();
const { userId, projectId } = await this.getProjectUserIdRead();
bean.userId = userId;
bean.projectId = projectId;
const type = bean.type;
@@ -129,7 +121,7 @@ export class AddonController extends CrudController<AddonService> {
value: item.name,
label: item.title,
needPlus: item.needPlus ?? false,
icon: item.icon
icon: item.icon,
});
}
dict = dict.sort(a => {
@@ -142,43 +134,42 @@ export class AddonController extends CrudController<AddonService> {
async simpleInfo(@Query("addonType") addonType: string, @Query("id") id: number) {
if (id === 0) {
//获取默认
const {projectId,userId} = await this.getProjectUserIdRead();
const res = await this.service.getDefault(userId, addonType,projectId);
const { projectId, userId } = await this.getProjectUserIdRead();
const res = await this.service.getDefault(userId, addonType, projectId);
if (!res) {
throw new ValidateException("默认Addon配置不存在");
}
const simple = await this.service.getSimpleInfo(res.id);
return this.ok(simple);
}
await this.checkOwner(this.getService(), id, "read",true);
await this.checkOwner(this.getService(), id, "read", true);
const res = await this.service.getSimpleInfo(id);
return this.ok(res);
}
@Post("/getDefaultId", { description: Constants.per.authOnly, summary: "查询Addon插件默认配置ID" })
async getDefaultId(@Query("addonType") addonType: string) {
const {projectId,userId} = await this.getProjectUserIdRead();
const res = await this.service.getDefault(userId, addonType,projectId);
const { projectId, userId } = await this.getProjectUserIdRead();
const res = await this.service.getDefault(userId, addonType, projectId);
return this.ok(res?.id);
}
@Post("/setDefault", { description: Constants.per.authOnly, summary: "设置Addon插件默认配置" })
async setDefault(@Query("addonType") addonType: string, @Query("id") id: number) {
const {projectId,userId} = await this.checkOwner(this.getService(), id, "write",true);
const res = await this.service.setDefault(id, userId, addonType,projectId);
const { projectId, userId } = await this.checkOwner(this.getService(), id, "write", true);
const res = await this.service.setDefault(id, userId, addonType, projectId);
return this.ok(res);
}
@Post("/options", { description: Constants.per.authOnly, summary: "查询Addon插件配置字典" })
async options(@Query("addonType") addonType: string) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
const res = await this.service.list({
query: {
userId,
addonType,
projectId
}
projectId,
},
});
for (const item of res) {
delete item.setting;
@@ -186,25 +177,24 @@ export class AddonController extends CrudController<AddonService> {
return this.ok(res);
}
@Post("/handle", { description: Constants.per.authOnly, summary: "Addon插件处理请求" })
async handle(@Body(ALL) body: AddonRequestHandleReq) {
let inputAddon = body.input.addon;
if (body.input.id > 0) {
await this.checkOwner(this.getService(), body.input.id, "write",true);
await this.checkOwner(this.getService(), body.input.id, "write", true);
const oldEntity = await this.service.info(body.input.id);
if (oldEntity) {
inputAddon = JSON.parse(oldEntity.setting);
}
}
const {projectId,userId} = await this.getProjectUserIdRead();
const serviceGetter = this.taskServiceBuilder.create({ userId,projectId });
const { projectId, userId } = await this.getProjectUserIdRead();
const serviceGetter = this.taskServiceBuilder.create({ userId, projectId });
const ctx = {
http: http,
logger: logger,
utils: utils,
serviceGetter
serviceGetter,
};
const addon = await newAddon(body.addonType, body.typeName, inputAddon, ctx);
const res = await addon.onRequest(body);
@@ -1,15 +1,15 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController } from '@certd/lib-server';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { GroupService } from '../../../modules/basic/service/group-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { Constants, CrudController } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { GroupService } from "../../../modules/basic/service/group-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
* 通知
*/
@Provide()
@Controller('/api/basic/group')
@ApiTags(['basic-group'])
@Controller("/api/basic/group")
@ApiTags(["basic-group"])
export class GroupController extends CrudController<GroupService> {
@Inject()
service: GroupService;
@@ -20,14 +20,14 @@ export class GroupController extends CrudController<GroupService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询分组分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询分组分页列表" })
async page(@Body(ALL) body: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.projectId = projectId;
delete body.query.userId;
const buildQuery = qb => {
qb.andWhere('user_id = :userId', { userId });
qb.andWhere("user_id = :userId", { userId });
};
const res = await this.service.page({
query: body.query,
@@ -38,45 +38,45 @@ export class GroupController extends CrudController<GroupService> {
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询分组列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询分组列表" })
async list(@Body(ALL) body: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.projectId = projectId;
body.query.userId = userId;
return await super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加分组" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加分组" })
async add(@Body(ALL) bean: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
bean.projectId = projectId;
bean.userId = userId;
return await super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新分组" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新分组" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
delete bean.projectId;
return await super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询分组详情" })
async info(@Query('id') id: number) {
@Post("/info", { description: Constants.per.authOnly, summary: "查询分组详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read");
return await super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除分组" })
async delete(@Query('id') id: number) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除分组" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
return await super.delete(id);
}
@Post('/all', { description: Constants.per.authOnly, summary: "查询所有分组" })
async all(@Query('type') type: string) {
const {projectId,userId} = await this.getProjectUserIdRead();
@Post("/all", { description: Constants.per.authOnly, summary: "查询所有分组" })
async all(@Query("type") type: string) {
const { projectId, userId } = await this.getProjectUserIdRead();
const list: any = await this.service.find({
where: {
projectId,
@@ -1,34 +1,34 @@
import { Constants, isEnterprise } from '@certd/lib-server';
import { Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { In } from 'typeorm';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { UserService } from '../../../modules/sys/authority/service/user-service.js';
import { BasicController } from '../../basic/code-controller.js';
import { RoleService } from '../../../modules/sys/authority/service/role-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { Constants, isEnterprise } from "@certd/lib-server";
import { Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { In } from "typeorm";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { UserService } from "../../../modules/sys/authority/service/user-service.js";
import { BasicController } from "../../basic/code-controller.js";
import { RoleService } from "../../../modules/sys/authority/service/role-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
* 通知
*/
@Provide()
@Controller('/api/basic/user')
@ApiTags(['basic-user'])
@Controller("/api/basic/user")
@ApiTags(["basic-user"])
export class BasicUserController extends BasicController {
@Inject()
service: UserService;
@Inject()
authService: AuthService;
@Inject()
@Inject()
roleService: RoleService;
getService(): UserService {
return this.service;
}
@Post('/getSimpleUserByIds', { description: Constants.per.authOnly, summary: "根据ID列表获取用户简单信息" })
async getSimpleUserByIds(@Body('ids') ids: number[]) {
if(!isEnterprise()){
throw new Error('非企业模式不能获取用户信息');
@Post("/getSimpleUserByIds", { description: Constants.per.authOnly, summary: "根据ID列表获取用户简单信息" })
async getSimpleUserByIds(@Body("ids") ids: number[]) {
if (!isEnterprise()) {
throw new Error("非企业模式不能获取用户信息");
}
const users = await this.service.find({
select: {
@@ -45,10 +45,10 @@ export class BasicUserController extends BasicController {
return this.ok(users);
}
@Post('/getSimpleUsers', {description: Constants.per.authOnly, summary: "获取所有用户简单信息"})
@Post("/getSimpleUsers", { description: Constants.per.authOnly, summary: "获取所有用户简单信息" })
async getSimpleUsers() {
if(!isEnterprise()){
throw new Error('非企业模式不能获取所有用户信息');
if (!isEnterprise()) {
throw new Error("非企业模式不能获取所有用户信息");
}
const users = await this.service.find({
select: {
@@ -62,7 +62,7 @@ export class BasicUserController extends BasicController {
return this.ok(users);
}
@Post('/getSimpleRoles', {description: Constants.per.authOnly, summary: "获取所有角色简单信息"})
@Post("/getSimpleRoles", { description: Constants.per.authOnly, summary: "获取所有角色简单信息" })
async getSimpleRoles() {
const roles = await this.roleService.find({
select: {
@@ -72,5 +72,4 @@ export class BasicUserController extends BasicController {
});
return this.ok(roles);
}
}
@@ -1,16 +1,16 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController } from '@certd/lib-server';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { Constants, CrudController } from "@certd/lib-server";
import { DomainService } from "../../../modules/cert/service/domain-service.js";
import { checkPlus } from '@certd/plus-core';
import { ApiTags } from '@midwayjs/swagger';
import { parseDomainByPsl } from '@certd/plugin-lib';
import { checkPlus } from "@certd/plus-core";
import { ApiTags } from "@midwayjs/swagger";
import { parseDomainByPsl } from "@certd/plugin-lib";
/**
* 授权
*/
@Provide()
@Controller('/api/cert/domain')
@ApiTags(['cert'])
@Controller("/api/cert/domain")
@ApiTags(["cert"])
export class DomainController extends CrudController<DomainService> {
@Inject()
service: DomainService;
@@ -19,7 +19,7 @@ export class DomainController extends CrudController<DomainService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询域名分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询域名分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
@@ -30,7 +30,7 @@ export class DomainController extends CrudController<DomainService> {
const bq = qb => {
if (domain) {
qb.andWhere('domain like :domain', { domain: `%${domain}%` });
qb.andWhere("domain like :domain", { domain: `%${domain}%` });
}
};
@@ -43,7 +43,7 @@ export class DomainController extends CrudController<DomainService> {
return this.ok(pageRet);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询域名列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询域名列表" })
async list(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
@@ -53,7 +53,7 @@ export class DomainController extends CrudController<DomainService> {
return this.ok(list);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加域名" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加域名" })
async add(@Body(ALL) bean: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
bean.projectId = projectId;
@@ -61,7 +61,7 @@ export class DomainController extends CrudController<DomainService> {
return super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新域名" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新域名" })
async update(@Body(ALL) bean: any) {
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
@@ -69,19 +69,19 @@ export class DomainController extends CrudController<DomainService> {
return super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询域名详情" })
async info(@Query('id') id: number) {
@Post("/info", { description: Constants.per.authOnly, summary: "查询域名详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read");
return super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除域名" })
async delete(@Query('id') id: number) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除域名" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
return super.delete(id);
}
@Post('/deleteByIds', { description: Constants.per.authOnly, summary: "批量删除域名" })
@Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除域名" })
async deleteByIds(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
await this.service.delete(body.ids, {
@@ -91,8 +91,7 @@ export class DomainController extends CrudController<DomainService> {
return this.ok();
}
@Post('/import/start', { description: Constants.per.authOnly, summary: "开始域名导入任务" })
@Post("/import/start", { description: Constants.per.authOnly, summary: "开始域名导入任务" })
async importStart(@Body(ALL) body: any) {
checkPlus();
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -101,24 +100,23 @@ export class DomainController extends CrudController<DomainService> {
key,
userId: userId,
projectId: projectId,
}
};
await this.service.startDomainImportTask(req);
return this.ok();
}
@Post('/import/status', { description: Constants.per.authOnly, summary: "查询域名导入任务状态" })
@Post("/import/status", { description: Constants.per.authOnly, summary: "查询域名导入任务状态" })
async importStatus() {
const { projectId, userId } = await this.getProjectUserIdRead();
const req = {
userId: userId,
projectId: projectId,
}
};
const task = await this.service.getDomainImportTaskStatus(req);
return this.ok(task);
}
@Post('/import/delete', { description: Constants.per.authOnly, summary: "删除域名导入任务" })
@Post("/import/delete", { description: Constants.per.authOnly, summary: "删除域名导入任务" })
async importDelete(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
const { key } = body;
@@ -126,12 +124,12 @@ export class DomainController extends CrudController<DomainService> {
userId: userId,
projectId: projectId,
key,
}
};
await this.service.deleteDomainImportTask(req);
return this.ok();
}
@Post('/import/save', { description: Constants.per.authOnly, summary: "保存域名导入任务" })
@Post("/import/save", { description: Constants.per.authOnly, summary: "保存域名导入任务" })
async importSave(@Body(ALL) body: any) {
checkPlus();
const { projectId, userId } = await this.getProjectUserIdRead();
@@ -139,61 +137,59 @@ export class DomainController extends CrudController<DomainService> {
const req = {
userId: userId,
projectId: projectId,
dnsProviderType, dnsProviderAccessId, key
}
dnsProviderType,
dnsProviderAccessId,
key,
};
const item = await this.service.saveDomainImportTask(req);
return this.ok(item);
}
@Post('/sync/expiration/start', { description: Constants.per.authOnly, summary: "开始同步域名过期时间任务" })
@Post("/sync/expiration/start", { description: Constants.per.authOnly, summary: "开始同步域名过期时间任务" })
async syncExpirationStart(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
await this.service.startSyncExpirationTask({
userId: userId,
projectId: projectId,
})
});
return this.ok();
}
@Post('/sync/expiration/status', { description: Constants.per.authOnly, summary: "查询同步域名过期时间任务状态" })
@Post("/sync/expiration/status", { description: Constants.per.authOnly, summary: "查询同步域名过期时间任务状态" })
async syncExpirationStatus(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead();
const status = await this.service.getSyncExpirationTaskStatus({
userId: userId,
projectId: projectId,
})
});
return this.ok(status);
}
@Post('/setting/save', { description: Constants.per.authOnly, summary: "保存域名监控设置" })
@Post("/setting/save", { description: Constants.per.authOnly, summary: "保存域名监控设置" })
async settingSave(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdWrite();
await this.service.monitorSettingSave({
userId: userId,
projectId: projectId,
setting: {...body},
})
setting: { ...body },
});
return this.ok();
}
@Post('/setting/get', { description: Constants.per.authOnly, summary: "查询域名监控设置" })
@Post("/setting/get", { description: Constants.per.authOnly, summary: "查询域名监控设置" })
async settingGet() {
const { projectId, userId } = await this.getProjectUserIdRead();
const setting = await this.service.monitorSettingGet({
userId: userId,
projectId: projectId,
})
});
return this.ok(setting);
}
@Post('/isSubdomain', { description: Constants.per.authOnly, summary: "判断是否为子域名" })
@Post("/isSubdomain", { description: Constants.per.authOnly, summary: "判断是否为子域名" })
async isSubdomain(@Body(ALL) body: any) {
const { domain } = body;
const parsed = parseDomainByPsl(domain)
const mainDomain = parsed.domain || ''
const parsed = parseDomainByPsl(domain);
const mainDomain = parsed.domain || "";
return this.ok(mainDomain !== domain);
}
}
@@ -1,15 +1,15 @@
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { BaseController, Constants } from '@certd/lib-server';
import { CnameRecordService } from '../../../modules/cname/service/cname-record-service.js';
import { CnameProviderService } from '../../../modules/cname/service/cname-provider-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, Constants } from "@certd/lib-server";
import { CnameRecordService } from "../../../modules/cname/service/cname-record-service.js";
import { CnameProviderService } from "../../../modules/cname/service/cname-provider-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
* 授权
*/
@Provide()
@Controller('/api/cname/provider')
@ApiTags(['pipeline-cname'])
@Controller("/api/cname/provider")
@ApiTags(["pipeline-cname"])
export class CnameProviderController extends BaseController {
@Inject()
service: CnameRecordService;
@@ -20,7 +20,7 @@ export class CnameProviderController extends BaseController {
return this.service;
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询CNAME提供商列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询CNAME提供商列表" })
async list(@Body(ALL) body: any) {
const res = await this.providerService.list({});
return this.ok(res);
@@ -1,14 +1,14 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController } from '@certd/lib-server';
import { CnameRecordService } from '../../../modules/cname/service/cname-record-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { Constants, CrudController } from "@certd/lib-server";
import { CnameRecordService } from "../../../modules/cname/service/cname-record-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
* 授权
*/
@Provide()
@Controller('/api/cname/record')
@ApiTags(['pipeline-cname'])
@Controller("/api/cname/record")
@ApiTags(["pipeline-cname"])
export class CnameRecordController extends CrudController<CnameRecordService> {
@Inject()
service: CnameRecordService;
@@ -17,9 +17,9 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询CNAME记录分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询CNAME记录分页列表" })
async page(@Body(ALL) body: any) {
const {userId,projectId} = await this.getProjectUserIdRead();
const { userId, projectId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId;
@@ -28,7 +28,7 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
const bq = qb => {
if (domain) {
qb.andWhere('domain like :domain', { domain: `%${domain}%` });
qb.andWhere("domain like :domain", { domain: `%${domain}%` });
}
};
@@ -41,9 +41,9 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
return this.ok(pageRet);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询CNAME记录列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询CNAME记录列表" })
async list(@Body(ALL) body: any) {
const {userId,projectId} = await this.getProjectUserIdRead();
const { userId, projectId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId;
@@ -51,15 +51,15 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
return this.ok(list);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加CNAME记录" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加CNAME记录" })
async add(@Body(ALL) bean: any) {
const {userId,projectId} = await this.getProjectUserIdWrite();
const { userId, projectId } = await this.getProjectUserIdWrite();
bean.userId = userId;
bean.projectId = projectId;
return super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新CNAME记录" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新CNAME记录" })
async update(@Body(ALL) bean: any) {
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
@@ -67,50 +67,50 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
return super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询CNAME记录详情" })
async info(@Query('id') id: number) {
@Post("/info", { description: Constants.per.authOnly, summary: "查询CNAME记录详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read");
return super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除CNAME记录" })
async delete(@Query('id') id: number) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除CNAME记录" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
return super.delete(id);
}
@Post('/deleteByIds', { description: Constants.per.authOnly, summary: "批量删除CNAME记录" })
@Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除CNAME记录" })
async deleteByIds(@Body(ALL) body: any) {
const {userId,projectId} = await this.getProjectUserIdWrite();
const { userId, projectId } = await this.getProjectUserIdWrite();
await this.service.delete(body.ids, {
userId,
projectId,
});
return this.ok();
}
@Post('/getByDomain', { description: Constants.per.authOnly, summary: "根据域名获取CNAME记录" })
@Post("/getByDomain", { description: Constants.per.authOnly, summary: "根据域名获取CNAME记录" })
async getByDomain(@Body(ALL) body: { domain: string; createOnNotFound: boolean }) {
const {userId,projectId} = await this.getProjectUserIdRead();
const res = await this.service.getByDomain(body.domain, userId,projectId, body.createOnNotFound);
const { userId, projectId } = await this.getProjectUserIdRead();
const res = await this.service.getByDomain(body.domain, userId, projectId, body.createOnNotFound);
return this.ok(res);
}
@Post('/verify', { description: Constants.per.authOnly, summary: "验证CNAME记录" })
@Post("/verify", { description: Constants.per.authOnly, summary: "验证CNAME记录" })
async verify(@Body(ALL) body: { id: number }) {
await this.checkOwner(this.getService(), body.id, "read");
const res = await this.service.verify(body.id);
return this.ok(res);
}
@Post('/resetStatus', { description: Constants.per.authOnly, summary: "重置CNAME记录状态" })
@Post("/resetStatus", { description: Constants.per.authOnly, summary: "重置CNAME记录状态" })
async resetStatus(@Body(ALL) body: { id: number }) {
await this.checkOwner(this.getService(), body.id, "read");
const res = await this.service.resetStatus(body.id);
return this.ok(res);
}
@Post('/import', { description: Constants.per.authOnly, summary: "导入CNAME记录" })
@Post("/import", { description: Constants.per.authOnly, summary: "导入CNAME记录" })
async import(@Body(ALL) body: { domainList: string; cnameProviderId: any }) {
const {userId,projectId} = await this.getProjectUserIdWrite();
const { userId, projectId } = await this.getProjectUserIdWrite();
const res = await this.service.doImport({
userId,
projectId,
@@ -119,5 +119,4 @@ export class CnameRecordController extends CrudController<CnameRecordService> {
});
return this.ok(res);
}
}
@@ -1,11 +1,11 @@
import { Controller, Inject, Post, Provide } from '@midwayjs/core';
import { BaseController, Constants } from '@certd/lib-server';
import { UserService } from '../../../modules/sys/authority/service/user-service.js';
import { RoleService } from '../../../modules/sys/authority/service/role-service.js';
import { PipelineService } from '../../../modules/pipeline/service/pipeline-service.js';
import { HistoryService } from '../../../modules/pipeline/service/history-service.js';
import { CertInfoService } from '../../../modules/monitor/index.js';
import { ApiTags } from '@midwayjs/swagger';
import { Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, Constants } from "@certd/lib-server";
import { UserService } from "../../../modules/sys/authority/service/user-service.js";
import { RoleService } from "../../../modules/sys/authority/service/role-service.js";
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { HistoryService } from "../../../modules/pipeline/service/history-service.js";
import { CertInfoService } from "../../../modules/monitor/index.js";
import { ApiTags } from "@midwayjs/swagger";
export type ChartItem = {
name: string;
@@ -30,8 +30,8 @@ export type UserStatisticCount = {
/**
*/
@Provide()
@Controller('/api/statistic/')
@ApiTags(['dashboard'])
@Controller("/api/statistic/")
@ApiTags(["dashboard"])
export class StatisticController extends BaseController {
@Inject()
userService: UserService;
@@ -46,17 +46,17 @@ export class StatisticController extends BaseController {
@Inject()
certInfoService: CertInfoService;
@Post('/count', { description: Constants.per.authOnly, summary: "查询仪表盘统计数据" })
@Post("/count", { description: Constants.per.authOnly, summary: "查询仪表盘统计数据" })
public async count() {
const {userId,projectId} = await this.getProjectUserIdRead();
const pipelineCount = await this.pipelineService.count({ userId,projectId });
const pipelineStatusCount = await this.pipelineService.statusCount({ userId,projectId });
const pipelineEnableCount = await this.pipelineService.enableCount({ userId,projectId });
const { userId, projectId } = await this.getProjectUserIdRead();
const pipelineCount = await this.pipelineService.count({ userId, projectId });
const pipelineStatusCount = await this.pipelineService.statusCount({ userId, projectId });
const pipelineEnableCount = await this.pipelineService.enableCount({ userId, projectId });
const historyCount = await this.historyService.countPerDay({ userId,projectId, days: 7 });
const expiringList = await this.pipelineService.latestExpiringList({ userId,projectId, count: 5 });
const historyCount = await this.historyService.countPerDay({ userId, projectId, days: 7 });
const expiringList = await this.pipelineService.latestExpiringList({ userId, projectId, count: 5 });
const certCount = await this.certInfoService.count({ userId,projectId });
const certCount = await this.certInfoService.count({ userId, projectId });
const count: UserStatisticCount = {
pipelineCount,
@@ -1,22 +1,22 @@
import { BaseController, Constants } from '@certd/lib-server';
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { ProjectService } from '../../../modules/sys/enterprise/service/project-service.js';
import { ProjectMemberService } from '../../../modules/sys/enterprise/service/project-member-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { BaseController, Constants } from "@certd/lib-server";
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js";
import { ProjectMemberService } from "../../../modules/sys/enterprise/service/project-member-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
*/
@Provide()
@Controller('/api/enterprise/project')
@ApiTags(['enterprise-project'])
@Controller("/api/enterprise/project")
@ApiTags(["enterprise-project"])
export class UserProjectController extends BaseController {
@Inject()
service: ProjectService;
@Inject()
projectMemberService: ProjectMemberService;
@Inject()
authService: AuthService;
@@ -24,54 +24,52 @@ export class UserProjectController extends BaseController {
return this.service;
}
/**
* @param body
* @returns
/**
* @param body
* @returns
*/
@Post('/detail', { description: Constants.per.authOnly, summary: "查询项目详情" })
@Post("/detail", { description: Constants.per.authOnly, summary: "查询项目详情" })
async detail(@Body(ALL) body: any) {
const {projectId} = await this.getProjectUserIdRead();
const res = await this.service.getDetail(projectId,this.getUserId());
const { projectId } = await this.getProjectUserIdRead();
const res = await this.service.getDetail(projectId, this.getUserId());
return this.ok(res);
}
/**
* 我的项目
* @param body
* @returns
* @param body
* @returns
*/
@Post('/list', { description: Constants.per.authOnly, summary: "查询我的项目列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询我的项目列表" })
async list(@Body(ALL) body: any) {
const userId= this.getUserId();
const userId = this.getUserId();
const res = await this.service.getUserProjects(userId);
return this.ok(res);
}
/**
*
*
* @param body 所有项目
* @returns
* @returns
*/
@Post('/all', { description: Constants.per.authOnly, summary: "查询所有项目" })
@Post("/all", { description: Constants.per.authOnly, summary: "查询所有项目" })
async all(@Body(ALL) body: any) {
const userId= this.getUserId();
const userId = this.getUserId();
const res = await this.service.getAllWithStatus(userId);
return this.ok(res);
}
@Post('/applyJoin', { description: Constants.per.authOnly, summary: "申请加入项目" })
@Post("/applyJoin", { description: Constants.per.authOnly, summary: "申请加入项目" })
async applyJoin(@Body(ALL) body: any) {
const userId= this.getUserId();
const userId = this.getUserId();
const res = await this.service.applyJoin({ userId, projectId: body.projectId });
return this.ok(res);
}
@Post('/updateMember', { description: Constants.per.authOnly, summary: "更新项目成员" })
@Post("/updateMember", { description: Constants.per.authOnly, summary: "更新项目成员" })
async updateMember(@Body(ALL) body: any) {
const {projectId} = await this.getProjectUserIdAdmin();
const {status,permission,userId} = body;
const { projectId } = await this.getProjectUserIdAdmin();
const { status, permission, userId } = body;
const member = await this.projectMemberService.findOne({
where: {
projectId,
@@ -79,7 +77,7 @@ export class UserProjectController extends BaseController {
},
});
if (!member) {
throw new Error('成员不存在');
throw new Error("成员不存在");
}
const res = await this.projectMemberService.update({
id: member.id,
@@ -89,17 +87,17 @@ export class UserProjectController extends BaseController {
return this.ok(res);
}
@Post('/approveJoin', { description: Constants.per.authOnly, summary: "审批加入项目申请" })
@Post("/approveJoin", { description: Constants.per.authOnly, summary: "审批加入项目申请" })
async approveJoin(@Body(ALL) body: any) {
const {projectId} = await this.getProjectUserIdAdmin();
const {status,permission,userId} = body;
const res = await this.service.approveJoin({ userId, projectId: projectId,status,permission });
const { projectId } = await this.getProjectUserIdAdmin();
const { status, permission, userId } = body;
const res = await this.service.approveJoin({ userId, projectId: projectId, status, permission });
return this.ok(res);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除项目成员" })
@Post("/delete", { description: Constants.per.authOnly, summary: "删除项目成员" })
async delete(@Body(ALL) body: any) {
const {projectId} = await this.getProjectUserIdAdmin();
const { projectId } = await this.getProjectUserIdAdmin();
await this.projectMemberService.deleteWhere({
projectId,
userId: this.getUserId(),
@@ -107,15 +105,14 @@ export class UserProjectController extends BaseController {
return this.ok();
}
@Post('/leave', { description: Constants.per.authOnly, summary: "离开项目" })
@Post("/leave", { description: Constants.per.authOnly, summary: "离开项目" })
async leave(@Body(ALL) body: any) {
const {projectId} = body
const userId = this.getUserId();
const { projectId } = body;
const userId = this.getUserId();
await this.projectMemberService.deleteWhere({
projectId,
userId,
});
return this.ok();
}
}
@@ -1,4 +1,4 @@
import { CrudController, SysSettingsService,Constants } from "@certd/lib-server";
import { CrudController, SysSettingsService, Constants } from "@certd/lib-server";
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { ProjectMemberEntity } from "../../../modules/sys/enterprise/entity/project-member.js";
import { ProjectMemberService } from "../../../modules/sys/enterprise/service/project-member-service.js";
@@ -9,7 +9,7 @@ import { ApiTags } from "@midwayjs/swagger";
*/
@Provide()
@Controller("/api/enterprise/projectMember")
@ApiTags(['enterprise-project-member'])
@ApiTags(["enterprise-project-member"])
export class ProjectMemberController extends CrudController<ProjectMemberEntity> {
@Inject()
service: ProjectMemberService;
@@ -26,7 +26,7 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
@Post("/page", { description: Constants.per.authOnly, summary: "查询项目成员分页列表" })
async page(@Body(ALL) body: any) {
const {projectId} = await this.getProjectUserIdRead();
const { projectId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.projectId = projectId;
return await super.page(body);
@@ -34,7 +34,7 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
@Post("/list", { description: Constants.per.authOnly, summary: "查询项目成员列表" })
async list(@Body(ALL) body: any) {
const {projectId} = await this.getProjectUserIdRead();
const { projectId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.projectId = projectId;
return super.list(body);
@@ -56,12 +56,12 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
return super.add(bean);
}
@Post("/update", { description: Constants.per.authOnly, summary: "更新项目成员" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新项目成员" })
async update(@Body(ALL) bean: any) {
if (!bean.id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(bean.id)
const projectId = await this.service.getProjectId(bean.id);
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId: projectId,
@@ -77,13 +77,13 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
@Post("/info", { description: Constants.per.authOnly, summary: "查询项目成员详情" })
async info(@Query("id") id: number) {
if (!id) {
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
const projectId = await this.service.getProjectId(id);
await this.projectService.checkReadPermission({
userId: this.getUserId(),
projectId:projectId,
projectId: projectId,
});
return super.info(id);
}
@@ -93,10 +93,10 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
const projectId = await this.service.getProjectId(id);
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId:projectId,
projectId: projectId,
});
return super.delete(id);
}
@@ -107,14 +107,14 @@ export class ProjectMemberController extends CrudController<ProjectMemberEntity>
if (!id) {
throw new Error("id is required");
}
const projectId = await this.service.getProjectId(id)
const projectId = await this.service.getProjectId(id);
await this.projectService.checkAdminPermission({
userId: this.getUserId(),
projectId:projectId,
projectId: projectId,
});
await this.service.delete(id as any);
}
return this.ok({});
}
}
@@ -1,44 +1,43 @@
import { BaseController, Constants } from '@certd/lib-server';
import { Controller, Inject, Post, Provide } from '@midwayjs/core';
import { TransferService } from '../../../modules/sys/enterprise/service/transfer-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { BaseController, Constants } from "@certd/lib-server";
import { Controller, Inject, Post, Provide } from "@midwayjs/core";
import { TransferService } from "../../../modules/sys/enterprise/service/transfer-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
*/
@Provide()
@Controller('/api/enterprise/transfer')
@ApiTags(['enterprise-project'])
@Controller("/api/enterprise/transfer")
@ApiTags(["enterprise-project"])
export class TransferController extends BaseController {
@Inject()
service: TransferService;
getService(): TransferService {
return this.service;
}
/**
* 我自己的资源
* @param body
* @returns
/**
* 我自己的资源
* @param body
* @returns
*/
@Post('/selfResources', { description: Constants.per.authOnly, summary: "查询我自己的资源" })
@Post("/selfResources", { description: Constants.per.authOnly, summary: "查询我自己的资源" })
async selfResources() {
const userId = this.getUserId();
const res = await this.service.getUserResources(userId);
return this.ok(res);
}
/**
* 迁移项目
* @param body
* @returns
/**
* 迁移项目
* @param body
* @returns
*/
@Post('/doTransfer', { description: Constants.per.authOnly, summary: "迁移项目资源" })
@Post("/doTransfer", { description: Constants.per.authOnly, summary: "迁移项目资源" })
async doTransfer() {
const {projectId} = await this.getProjectUserIdRead();
const userId = this.getUserId();
await this.service.transferAll(userId,projectId);
const { projectId } = await this.getProjectUserIdRead();
const userId = this.getUserId();
await this.service.transferAll(userId, projectId);
return this.ok();
}
}
@@ -1,41 +1,41 @@
import { Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { BaseController } from '@certd/lib-server';
import { Constants } from '@certd/lib-server';
import { EmailService } from '../../../modules/basic/service/email-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController } from "@certd/lib-server";
import { Constants } from "@certd/lib-server";
import { EmailService } from "../../../modules/basic/service/email-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
*/
@Provide()
@Controller('/api/mine/email')
@ApiTags(['mine'])
@Controller("/api/mine/email")
@ApiTags(["mine"])
export class EmailController extends BaseController {
@Inject()
emailService: EmailService;
@Post('/test', { description: Constants.per.authOnly, summary: "测试邮件发送" })
public async test(@Body('receiver') receiver) {
@Post("/test", { description: Constants.per.authOnly, summary: "测试邮件发送" })
public async test(@Body("receiver") receiver) {
const userId = super.getUserId();
await this.emailService.test(userId, receiver);
return this.ok({});
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询邮件列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询邮件列表" })
public async list() {
const userId = super.getUserId();
const res = await this.emailService.list(userId);
return this.ok(res);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加邮件" })
public async add(@Body('email') email) {
@Post("/add", { description: Constants.per.authOnly, summary: "添加邮件" })
public async add(@Body("email") email) {
const userId = super.getUserId();
await this.emailService.add(userId, email);
return this.ok({});
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除邮件" })
public async delete(@Body('email') email) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除邮件" })
public async delete(@Body("email") email) {
const userId = super.getUserId();
await this.emailService.delete(userId, email);
return this.ok({});
@@ -5,8 +5,8 @@ import { UserService } from "../../../modules/sys/authority/service/user-service
import { ApiTags } from "@midwayjs/swagger";
@Provide()
@Controller('/api/mine/passkey')
@ApiTags(['mine'])
@Controller("/api/mine/passkey")
@ApiTags(["mine"])
export class MinePasskeyController extends BaseController {
@Inject()
passkeyService: PasskeyService;
@@ -14,56 +14,43 @@ export class MinePasskeyController extends BaseController {
@Inject()
userService: UserService;
@Post('/generateRegistration', { description: Constants.per.authOnly, summary: "生成Passkey注册选项" })
@Post("/generateRegistration", { description: Constants.per.authOnly, summary: "生成Passkey注册选项" })
public async generateRegistration(
@Body(ALL)
body: any,
@RequestIP()
remoteIp: string
) {
const userId = this.getUserId()
const userId = this.getUserId();
const user = await this.userService.info(userId);
if (!user) {
throw new Error('用户不存在');
throw new Error("用户不存在");
}
const options = await this.passkeyService.generateRegistrationOptions(
userId,
user.username,
remoteIp,
this.ctx
);
const options = await this.passkeyService.generateRegistrationOptions(userId, user.username, remoteIp, this.ctx);
return this.ok({
...options,
});
}
@Post('/verifyRegistration', { description: Constants.per.authOnly, summary: "验证Passkey注册" })
@Post("/verifyRegistration", { description: Constants.per.authOnly, summary: "验证Passkey注册" })
public async verifyRegistration(
@Body(ALL)
body: any
) {
const userId = this.getUserId()
const userId = this.getUserId();
const response = body.response;
const challenge = body.challenge;
const deviceName = body.deviceName;
const result = await this.passkeyService.registerPasskey(
userId,
response,
challenge,
deviceName,
this.ctx
);
const result = await this.passkeyService.registerPasskey(userId, response, challenge, deviceName, this.ctx);
return this.ok(result);
}
@Post('/register', { description: Constants.per.authOnly, summary: "注册Passkey" })
@Post("/register", { description: Constants.per.authOnly, summary: "注册Passkey" })
public async registerPasskey(
@Body(ALL)
body: any
@@ -73,30 +60,23 @@ export class MinePasskeyController extends BaseController {
const deviceName = body.deviceName;
const challenge = body.challenge;
const result = await this.passkeyService.registerPasskey(
userId,
response,
challenge,
deviceName,
this.ctx
);
const result = await this.passkeyService.registerPasskey(userId, response, challenge, deviceName, this.ctx);
return this.ok(result);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询Passkey列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询Passkey列表" })
public async getPasskeys() {
const userId = this.getUserId();
const passkeys = await this.passkeyService.find({
select: ['id', 'deviceName', 'registeredAt', 'transports', 'passkeyId' ,'updateTime'],
select: ["id", "deviceName", "registeredAt", "transports", "passkeyId", "updateTime"],
where: { userId },
order: { registeredAt: 'DESC' },
order: { registeredAt: "DESC" },
});
return this.ok(passkeys);
}
@Post('/unbind', { description: Constants.per.authOnly, summary: "解绑Passkey" })
@Post("/unbind", { description: Constants.per.authOnly, summary: "解绑Passkey" })
public async unbindPasskey(@Body(ALL) body: any) {
const userId = this.getUserId();
const passkeyId = body.id;
@@ -106,11 +86,10 @@ export class MinePasskeyController extends BaseController {
});
if (!passkey) {
throw new Error('Passkey不存在');
throw new Error("Passkey不存在");
}
await this.passkeyService.delete([passkey.id]);
return this.ok({});
}
}
@@ -4,14 +4,14 @@ import { UserSettingsService } from "../../../modules/mine/service/user-settings
import { UserTwoFactorSetting } from "../../../modules/mine/service/models.js";
import { merge } from "lodash-es";
import { TwoFactorService } from "../../../modules/mine/service/two-factor-service.js";
import {isPlus} from "@certd/plus-core";
import { isPlus } from "@certd/plus-core";
import { ApiTags } from "@midwayjs/swagger";
/**
*/
@Provide()
@Controller("/api/user/settings/twoFactor")
@ApiTags(['mine'])
@ApiTags(["mine"])
export class UserTwoFactorSettingController extends BaseController {
@Inject()
service: UserSettingsService;
@@ -19,50 +19,48 @@ export class UserTwoFactorSettingController extends BaseController {
@Inject()
twoFactorService: TwoFactorService;
@Post("/get", { description: Constants.per.authOnly, summary: "获取双因子认证设置" })
async get() {
const userId = this.getUserId();
const setting = await this.service.getSetting<UserTwoFactorSetting>(userId,null, UserTwoFactorSetting);
const setting = await this.service.getSetting<UserTwoFactorSetting>(userId, null, UserTwoFactorSetting);
return this.ok(setting);
}
@Post("/save", { description: Constants.per.authOnly, summary: "保存双因子认证设置" })
async save(@Body(ALL) bean: any) {
if (!isPlus()) {
throw new Error('本功能需要开通Certd专业版')
throw new Error("本功能需要开通Certd专业版");
}
const userId = this.getUserId();
const setting = new UserTwoFactorSetting();
merge(setting, bean);
// 禁用时清除
if(!setting.authenticator.enabled){
setting.authenticator.secret = null;
setting.authenticator.verified = false;
if (!setting.authenticator.enabled) {
setting.authenticator.secret = null;
setting.authenticator.verified = false;
}
await this.service.saveSetting(userId,null, setting);
await this.service.saveSetting(userId, null, setting);
return this.ok({});
}
@Post("/authenticator/qrcode", { description: Constants.per.authOnly, summary: "获取验证器二维码" })
async authenticatorQrcode() {
const userId = this.getUserId();
const {qrcode,link,secret} = await this.twoFactorService.getAuthenticatorQrCode(userId);
return this.ok({qrcode,link,secret});
const { qrcode, link, secret } = await this.twoFactorService.getAuthenticatorQrCode(userId);
return this.ok({ qrcode, link, secret });
}
@Post("/authenticator/save", { description: Constants.per.authOnly, summary: "保存验证器设置" })
async authenticatorSave(@Body(ALL) bean: any) {
if (!isPlus()) {
throw new Error('本功能需要开通Certd专业版')
throw new Error("本功能需要开通Certd专业版");
}
const userId = this.getUserId();
await this.twoFactorService.saveAuthenticator({
userId,
verifyCode: bean.verifyCode,
userId,
verifyCode: bean.verifyCode,
});
return this.ok();
}
@@ -73,5 +71,4 @@ export class UserTwoFactorSettingController extends BaseController {
await this.twoFactorService.offAuthenticator(userId);
return this.ok();
}
}
@@ -10,8 +10,8 @@ import { ApiTags } from "@midwayjs/swagger";
/**
*/
@Provide()
@Controller('/api/user/settings')
@ApiTags(['mine'])
@Controller("/api/user/settings")
@ApiTags(["mine"])
export class UserSettingsController extends CrudController<UserSettingsService> {
@Inject()
service: UserSettingsService;
@@ -20,54 +20,54 @@ export class UserSettingsController extends CrudController<UserSettingsService>
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询用户设置分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询用户设置分页列表" })
async page(@Body(ALL) body) {
body.query = body.query ?? {};
body.query.userId = this.getUserId();
return super.page(body);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询用户设置列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询用户设置列表" })
async list(@Body(ALL) body) {
body.query = body.query ?? {};
body.query.userId = this.getUserId();
return super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加用户设置" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加用户设置" })
async add(@Body(ALL) bean) {
bean.userId = this.getUserId();
return super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新用户设置" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新用户设置" })
async update(@Body(ALL) bean) {
await this.service.checkUserId(bean.id, this.getUserId());
delete bean.userId;
return super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询用户设置详情" })
async info(@Query('id') id: number) {
@Post("/info", { description: Constants.per.authOnly, summary: "查询用户设置详情" })
async info(@Query("id") id: number) {
await this.service.checkUserId(id, this.getUserId());
return super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除用户设置" })
async delete(@Query('id') id: number) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除用户设置" })
async delete(@Query("id") id: number) {
await this.service.checkUserId(id, this.getUserId());
return super.delete(id);
}
@Post('/save', { description: Constants.per.authOnly, summary: "保存用户设置" })
@Post("/save", { description: Constants.per.authOnly, summary: "保存用户设置" })
async save(@Body(ALL) bean: UserSettingsEntity) {
bean.userId = this.getUserId();
await this.service.save(bean);
return this.ok({});
}
@Post('/get', { description: Constants.per.authOnly, summary: "获取用户设置" })
async get(@Query('key') key: string) {
const {projectId,userId} = await this.getProjectUserIdRead();
@Post("/get", { description: Constants.per.authOnly, summary: "获取用户设置" })
async get(@Query("key") key: string) {
const { projectId, userId } = await this.getProjectUserIdRead();
const entity = await this.service.getByKey(key, userId, projectId);
return this.ok(entity);
}
@@ -81,14 +81,13 @@ export class UserSettingsController extends CrudController<UserSettingsService>
@Post("/grant/save", { description: Constants.per.authOnly, summary: "保存授权设置" })
async grantSettingsSave(@Body(ALL) bean: UserGrantSetting) {
if (!isPlus()) {
throw new Error('本功能需要开通Certd专业版')
throw new Error("本功能需要开通Certd专业版");
}
const userId = this.getUserId();
const setting = new UserGrantSetting();
merge(setting, bean);
await this.service.saveSetting(userId,null, setting);
await this.service.saveSetting(userId, null, setting);
return this.ok({});
}
}
@@ -13,8 +13,8 @@ import { CertReader } from "@certd/plugin-lib";
/**
*/
@Provide()
@Controller('/api/monitor/cert')
@ApiTags(['cert'])
@Controller("/api/monitor/cert")
@ApiTags(["cert"])
export class CertInfoController extends CrudController<CertInfoService> {
@Inject()
service: CertInfoService;
@@ -30,12 +30,12 @@ export class CertInfoController extends CrudController<CertInfoService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询证书分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询证书分页列表" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.projectId = projectId;
body.query.userId = userId;
const domains = body.query?.domains;
delete body.query.domains;
@@ -49,21 +49,21 @@ export class CertInfoController extends CrudController<CertInfoService> {
query: body.query,
page: body.page,
sort: body.sort,
buildQuery: (bq) => {
buildQuery: bq => {
if (domains) {
bq.andWhere('domains like :domains', { domains: `%${domains}%` });
bq.andWhere("domains like :domains", { domains: `%${domains}%` });
}
if (expiresLeft) {
const willExpire = dayjs().add(DEFAULT_WILL_EXPIRE_DAYS, 'day').valueOf();
const willExpire = dayjs().add(DEFAULT_WILL_EXPIRE_DAYS, "day").valueOf();
if (expiresLeft === "expired") {
bq.andWhere('expires_time < :now', { now: Date.now() });
bq.andWhere("expires_time < :now", { now: Date.now() });
} else if (expiresLeft === "expiring") {
bq.andWhere('expires_time <= :willExpire and expires_time > :now', { willExpire, now: Date.now() });
bq.andWhere("expires_time <= :willExpire and expires_time > :now", { willExpire, now: Date.now() });
} else if (expiresLeft === "noExpired") {
bq.andWhere('expires_time > :willExpire', { willExpire });
bq.andWhere("expires_time > :willExpire", { willExpire });
}
}
}
},
});
const records = res.records;
@@ -79,71 +79,70 @@ export class CertInfoController extends CrudController<CertInfoService> {
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询证书列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询证书列表" })
async list(@Body(ALL) body: any) {
body.query = body.query ?? {};
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.projectId = projectId;
body.query.userId = userId;
return await super.list(body);
}
@Post('/getOptionsByIds', { description: Constants.per.authOnly, summary: "根据ID列表获取证书选项" })
async getOptionsByIds(@Body(ALL) body: {ids:any[]}) {
const { projectId, userId } = await this.getProjectUserIdRead()
@Post("/getOptionsByIds", { description: Constants.per.authOnly, summary: "根据ID列表获取证书选项" })
async getOptionsByIds(@Body(ALL) body: { ids: any[] }) {
const { projectId, userId } = await this.getProjectUserIdRead();
const list = await this.service.list({
query:{
query: {
projectId,
userId,
},
buildQuery: (bq: SelectQueryBuilder<any>) => {
bq.andWhere('id in (:...ids)', { ids: body.ids });
}
})
bq.andWhere("id in (:...ids)", { ids: body.ids });
},
});
const safeList =list.map((item:any) => {
const domainsArr = item.domains? item.domains.split(',') : [];
const safeList = list.map((item: any) => {
const domainsArr = item.domains ? item.domains.split(",") : [];
return {
id: item.id,
domain: item.domain,
domains:domainsArr,
domains: domainsArr,
userId: item.userId,
}
})
};
});
return this.ok(safeList);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加证书" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加证书" })
async add(@Body(ALL) bean: any) {
const { projectId, userId } = await this.getProjectUserIdWrite()
bean.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.projectId = projectId;
bean.userId = userId;
return await super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新证书" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新证书" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.service,bean.id,"write");
await this.checkOwner(this.service, bean.id, "write");
delete bean.userId;
delete bean.projectId;
return await super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询证书详情" })
async info(@Query('id') id: number) {
await this.checkOwner(this.service,id,"read");
@Post("/info", { description: Constants.per.authOnly, summary: "查询证书详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.service, id, "read");
return await super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除证书" })
async delete(@Query('id') id: number) {
await this.checkOwner(this.service,id,"write");
@Post("/delete", { description: Constants.per.authOnly, summary: "删除证书" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.service, id, "write");
return await super.delete(id);
}
@Post('/all', { description: Constants.per.authOnly, summary: "查询所有证书" })
@Post("/all", { description: Constants.per.authOnly, summary: "查询所有证书" })
async all() {
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
const list: any = await this.service.find({
where: {
projectId,
@@ -153,32 +152,30 @@ export class CertInfoController extends CrudController<CertInfoService> {
return this.ok(list);
}
@Post('/getCert', { description: Constants.per.authOnly, summary: "获取证书信息" })
async getCert(@Query('id') id: number) {
await this.checkOwner(this.getService(),id,"read");
@Post("/getCert", { description: Constants.per.authOnly, summary: "获取证书信息" })
async getCert(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read");
const certInfoEntity = await this.service.info(id);
const certInfo = JSON.parse(certInfoEntity.certInfo);
if (certInfo?.crt) {
const certReader = new CertReader(certInfo);
certInfo.detail = certReader.detail
certInfo.detail = certReader.detail;
}
return this.ok(certInfo);
}
@Get('/download', { description: Constants.per.authOnly, summary: "下载证书文件" })
async download(@Query('id') id: number) {
const {userId,projectId} =await this.checkOwner(this.getService(),id,"read");
const certInfo = await this.getService().info(id)
@Get("/download", { description: Constants.per.authOnly, summary: "下载证书文件" })
async download(@Query("id") id: number) {
const { userId, projectId } = await this.checkOwner(this.getService(), id, "read");
const certInfo = await this.getService().info(id);
if (certInfo == null) {
throw new CommonException('file not found');
throw new CommonException("file not found");
}
if (certInfo.userId !== userId) {
throw new CommonException('file not found');
throw new CommonException("file not found");
}
if (projectId && certInfo.projectId !== projectId) {
throw new CommonException('file not found');
throw new CommonException("file not found");
}
// koa send file
// 下载文件的名称
@@ -186,12 +183,12 @@ export class CertInfoController extends CrudController<CertInfoService> {
// 要下载的文件的完整路径
const path = certInfo.certFile;
if (!path) {
throw new CommonException('file not found');
throw new CommonException("file not found");
}
logger.info(`download:${path}`);
// 以流的形式下载文件
this.ctx.attachment(path);
this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.set("Content-Type", "application/octet-stream");
return fs.createReadStream(path);
}
@@ -8,8 +8,8 @@ import { AuthService } from "../../../modules/sys/authority/service/auth-service
/**
*/
@Provide()
@Controller('/api/monitor/job-history')
@ApiTags(['monitor'])
@Controller("/api/monitor/job-history")
@ApiTags(["monitor"])
export class JobHistoryController extends CrudController<JobHistoryService> {
@Inject()
service: JobHistoryService;
@@ -22,12 +22,12 @@ export class JobHistoryController extends CrudController<JobHistoryService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询监控运行历史分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询监控运行历史分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId
body.query.projectId = projectId;
const res = await this.service.page({
query: body.query,
page: body.page,
@@ -36,30 +36,30 @@ export class JobHistoryController extends CrudController<JobHistoryService> {
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询监控运行历史列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询监控运行历史列表" })
async list(@Body(ALL) body: any) {
body.query = body.query ?? {};
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.userId = userId;
body.query.projectId = projectId
body.query.projectId = projectId;
return await super.list(body);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询监控运行历史详情" })
async info(@Query('id') id: number) {
await this.checkOwner(this.service,id,"read");
@Post("/info", { description: Constants.per.authOnly, summary: "查询监控运行历史详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.service, id, "read");
return await super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除监控运行历史" })
async delete(@Query('id') id: number) {
await this.checkOwner(this.service,id,"write");
@Post("/delete", { description: Constants.per.authOnly, summary: "删除监控运行历史" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.service, id, "write");
return await super.delete(id);
}
@Post('/batchDelete', { description: Constants.per.authOnly, summary: "批量删除监控运行历史" })
async batchDelete(@Body('ids') ids: number[]) {
const { projectId, userId } = await this.getProjectUserIdWrite()
await this.service.batchDelete(ids,userId,projectId);
@Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除监控运行历史" })
async batchDelete(@Body("ids") ids: number[]) {
const { projectId, userId } = await this.getProjectUserIdWrite();
await this.service.batchDelete(ids, userId, projectId);
return this.ok();
}
}
@@ -4,15 +4,15 @@ import { AuthService } from "../../../modules/sys/authority/service/auth-service
import { SiteInfoService } from "../../../modules/monitor/service/site-info-service.js";
import { UserSiteMonitorSetting } from "../../../modules/mine/service/models.js";
import { merge } from "lodash-es";
import {SiteIpService} from "../../../modules/monitor/service/site-ip-service.js";
import { SiteIpService } from "../../../modules/monitor/service/site-ip-service.js";
import { utils } from "@certd/basic";
import { ApiTags } from "@midwayjs/swagger";
/**
*/
@Provide()
@Controller('/api/monitor/site')
@ApiTags(['monitor'])
@Controller("/api/monitor/site")
@ApiTags(["monitor"])
export class SiteInfoController extends CrudController<SiteInfoService> {
@Inject()
service: SiteInfoService;
@@ -25,11 +25,11 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询站点监控分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询站点监控分页列表" })
async page(@Body(ALL) body: any) {
body.query = body.query ?? {};
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.projectId = projectId;
body.query.userId = userId;
const certDomains = body.query.certDomains;
const domain = body.query.domain;
@@ -41,34 +41,34 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
query: body.query,
page: body.page,
sort: body.sort,
buildQuery: (bq) => {
buildQuery: bq => {
if (domain) {
bq.andWhere('domain like :domain', { domain: `%${domain}%` });
bq.andWhere("domain like :domain", { domain: `%${domain}%` });
}
if (certDomains) {
bq.andWhere('cert_domains like :cert_domains', { cert_domains: `%${certDomains}%` });
bq.andWhere("cert_domains like :cert_domains", { cert_domains: `%${certDomains}%` });
}
if (name) {
bq.andWhere('name like :name', { name: `%${name}%` });
bq.andWhere("name like :name", { name: `%${name}%` });
}
}
},
});
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询站点监控列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询站点监控列表" })
async list(@Body(ALL) body: any) {
body.query = body.query ?? {};
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.projectId = projectId;
body.query.userId = userId;
return await super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加站点监控" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加站点监控" })
async add(@Body(ALL) bean: any) {
const { projectId, userId } = await this.getProjectUserIdWrite()
bean.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.projectId = projectId;
bean.userId = userId;
const res = await this.service.add(bean);
const entity = await this.service.info(res.id);
@@ -78,9 +78,9 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
return this.ok(res);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新站点监控" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新站点监控" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.service,bean.id,"write");
await this.checkOwner(this.service, bean.id, "write");
delete bean.userId;
delete bean.projectId;
await this.service.update(bean);
@@ -90,89 +90,86 @@ export class SiteInfoController extends CrudController<SiteInfoService> {
}
return this.ok();
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询站点监控详情" })
async info(@Query('id') id: number) {
await this.checkOwner(this.service,id,"read");
@Post("/info", { description: Constants.per.authOnly, summary: "查询站点监控详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.service, id, "read");
return await super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除站点监控" })
async delete(@Query('id') id: number) {
await this.checkOwner(this.service,id,"write");
@Post("/delete", { description: Constants.per.authOnly, summary: "删除站点监控" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.service, id, "write");
return await super.delete(id);
}
@Post('/batchDelete', { description: Constants.per.authOnly, summary: "批量删除站点监控" })
@Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除站点监控" })
async batchDelete(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdWrite()
await this.service.batchDelete(body.ids,userId,projectId);
const { projectId, userId } = await this.getProjectUserIdWrite();
await this.service.batchDelete(body.ids, userId, projectId);
return this.ok();
}
@Post('/check', { description: Constants.per.authOnly, summary: "检查站点监控" })
async check(@Body('id') id: number) {
await this.checkOwner(this.service,id,"read");
@Post("/check", { description: Constants.per.authOnly, summary: "检查站点监控" })
async check(@Body("id") id: number) {
await this.checkOwner(this.service, id, "read");
await this.service.check(id, true, 0);
await utils.sleep(1000);
return this.ok();
}
@Post('/checkAll', { description: Constants.per.authOnly, summary: "检查所有站点监控" })
@Post("/checkAll", { description: Constants.per.authOnly, summary: "检查所有站点监控" })
async checkAll() {
const { projectId, userId } = await this.getProjectUserIdWrite()
this.service.triggerJobOnce(userId,projectId);
const { projectId, userId } = await this.getProjectUserIdWrite();
this.service.triggerJobOnce(userId, projectId);
return this.ok();
}
@Post('/import', { description: Constants.per.authOnly, summary: "导入站点监控" })
@Post("/import", { description: Constants.per.authOnly, summary: "导入站点监控" })
async doImport(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdWrite()
const { projectId, userId } = await this.getProjectUserIdWrite();
await this.service.doImport({
text:body.text,
groupId:body.groupId,
text: body.text,
groupId: body.groupId,
userId,
projectId
})
return this.ok();
}
@Post('/ipCheckChange', { description: Constants.per.authOnly, summary: "修改IP检查设置" })
async ipCheckChange(@Body(ALL) bean: any) {
await this.checkOwner(this.service,bean.id,"read");
await this.service.ipCheckChange({
id: bean.id,
ipCheck: bean.ipCheck
projectId,
});
return this.ok();
}
@Post('/disabledChange', { description: Constants.per.authOnly, summary: "修改禁用状态" })
@Post("/ipCheckChange", { description: Constants.per.authOnly, summary: "修改IP检查设置" })
async ipCheckChange(@Body(ALL) bean: any) {
await this.checkOwner(this.service, bean.id, "read");
await this.service.ipCheckChange({
id: bean.id,
ipCheck: bean.ipCheck,
});
return this.ok();
}
@Post("/disabledChange", { description: Constants.per.authOnly, summary: "修改禁用状态" })
async disabledChange(@Body(ALL) bean: any) {
await this.checkOwner(this.service,bean.id,"write");
await this.checkOwner(this.service, bean.id, "write");
await this.service.disabledChange({
id: bean.id,
disabled: bean.disabled
disabled: bean.disabled,
});
return this.ok();
}
@Post("/setting/get", { description: Constants.per.authOnly, summary: "获取站点监控设置" })
async get() {
const { userId, projectId } = await this.getProjectUserIdRead()
const setting = await this.service.getSetting(userId, projectId)
const { userId, projectId } = await this.getProjectUserIdRead();
const setting = await this.service.getSetting(userId, projectId);
return this.ok(setting);
}
@Post("/setting/save", { description: Constants.per.authOnly, summary: "保存站点监控设置" })
async save(@Body(ALL) bean: any) {
const { userId, projectId} = await this.getProjectUserIdWrite()
const { userId, projectId } = await this.getProjectUserIdWrite();
const setting = new UserSiteMonitorSetting();
merge(setting, bean);
await this.service.saveSetting(userId, projectId,setting);
await this.service.saveSetting(userId, projectId, setting);
return this.ok({});
}
}
@@ -8,8 +8,8 @@ import { ApiTags } from "@midwayjs/swagger";
/**
*/
@Provide()
@Controller('/api/monitor/site/ip')
@ApiTags(['monitor'])
@Controller("/api/monitor/site/ip")
@ApiTags(["monitor"])
export class SiteInfoController extends CrudController<SiteIpService> {
@Inject()
service: SiteIpService;
@@ -22,12 +22,12 @@ export class SiteInfoController extends CrudController<SiteIpService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询站点IP分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询站点IP分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId
body.query.projectId = projectId;
const res = await this.service.page({
query: body.query,
page: body.page,
@@ -36,98 +36,94 @@ export class SiteInfoController extends CrudController<SiteIpService> {
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询站点IP列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询站点IP列表" })
async list(@Body(ALL) body: any) {
body.query = body.query ?? {};
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.userId = userId;
body.query.projectId = projectId
body.query.projectId = projectId;
return await super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加站点IP" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加站点IP" })
async add(@Body(ALL) bean: any) {
const { projectId, userId } = await this.getProjectUserIdWrite()
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.userId = userId;
bean.projectId = projectId
bean.from = "manual"
bean.projectId = projectId;
bean.from = "manual";
const res = await this.service.add(bean);
const siteEntity = await this.siteInfoService.info(bean.siteId);
if(!siteEntity.disabled){
const {domain, httpsPort} = siteEntity;
this.service.check(res.id,domain, httpsPort);
if (!siteEntity.disabled) {
const { domain, httpsPort } = siteEntity;
this.service.check(res.id, domain, httpsPort);
}
return this.ok(res);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新站点IP" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新站点IP" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.service,bean.id,"write");
await this.checkOwner(this.service, bean.id, "write");
delete bean.userId;
delete bean.projectId;
await this.service.update(bean);
const siteEntity = await this.siteInfoService.info(bean.siteId);
if(!siteEntity.disabled){
const {domain, httpsPort} = siteEntity;
this.service.check(siteEntity.id,domain, httpsPort);
if (!siteEntity.disabled) {
const { domain, httpsPort } = siteEntity;
this.service.check(siteEntity.id, domain, httpsPort);
}
return this.ok();
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询站点IP详情" })
async info(@Query('id') id: number) {
await this.checkOwner(this.service,id,"read");
@Post("/info", { description: Constants.per.authOnly, summary: "查询站点IP详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.service, id, "read");
return await super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除站点IP" })
async delete(@Query('id') id: number) {
await this.checkOwner(this.service,id,"write");
@Post("/delete", { description: Constants.per.authOnly, summary: "删除站点IP" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.service, id, "write");
const entity = await this.service.info(id);
const res = await super.delete(id);
await this.service.updateIpCount(entity.siteId)
return res
await this.service.updateIpCount(entity.siteId);
return res;
}
@Post('/check', { description: Constants.per.authOnly, summary: "检查站点IP" })
async check(@Body('id') id: number) {
await this.checkOwner(this.service,id,"read");
@Post("/check", { description: Constants.per.authOnly, summary: "检查站点IP" })
async check(@Body("id") id: number) {
await this.checkOwner(this.service, id, "read");
const entity = await this.service.info(id);
const siteEntity = await this.siteInfoService.info(entity.siteId);
const domain = siteEntity.domain;
const port = siteEntity.httpsPort;
this.service.check(id,domain,port);
this.service.check(id, domain, port);
return this.ok();
}
@Post('/checkAll', { description: Constants.per.authOnly, summary: "检查所有站点IP" })
async checkAll(@Body('siteId') siteId: number) {
await this.getProjectUserIdRead()
@Post("/checkAll", { description: Constants.per.authOnly, summary: "检查所有站点IP" })
async checkAll(@Body("siteId") siteId: number) {
await this.getProjectUserIdRead();
const siteEntity = await this.siteInfoService.info(siteId);
await this.service.syncAndCheck(siteEntity);
return this.ok();
}
@Post('/sync', { description: Constants.per.authOnly, summary: "同步站点IP" })
async sync(@Body('siteId') siteId: number) {
await this.getProjectUserIdWrite()
const entity = await this.siteInfoService.info(siteId)
@Post("/sync", { description: Constants.per.authOnly, summary: "同步站点IP" })
async sync(@Body("siteId") siteId: number) {
await this.getProjectUserIdWrite();
const entity = await this.siteInfoService.info(siteId);
await this.service.sync(entity);
return this.ok();
}
@Post('/import', { description: Constants.per.authOnly, summary: "导入站点IP" })
@Post("/import", { description: Constants.per.authOnly, summary: "导入站点IP" })
async doImport(@Body(ALL) body: any) {
const { userId, projectId } = await this.getProjectUserIdWrite()
const { userId, projectId } = await this.getProjectUserIdWrite();
await this.service.doImport({
text:body.text,
text: body.text,
userId,
siteId:body.siteId,
projectId
})
siteId: body.siteId,
projectId,
});
return this.ok();
}
}
@@ -1,14 +1,14 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController } from '@certd/lib-server';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { OpenKeyService } from '../../../modules/open/service/open-key-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { Constants, CrudController } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { OpenKeyService } from "../../../modules/open/service/open-key-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
*/
@Provide()
@Controller('/api/open/key')
@ApiTags(['open'])
@Controller("/api/open/key")
@ApiTags(["open"])
export class OpenKeyController extends CrudController<OpenKeyService> {
@Inject()
service: OpenKeyService;
@@ -19,9 +19,9 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询开放API密钥分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询开放API密钥分页列表" })
async page(@Body(ALL) body: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.projectId = projectId;
body.query.userId = userId;
@@ -36,13 +36,13 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
private keySecretDesensitization(list: any[]) {
for (const item of list) {
item.keySecret = item.keySecret?.substring(0, 4) + '*********************************' + item.keySecret?.substring(item.keySecret.length - 4);
item.keySecret = item.keySecret?.substring(0, 4) + "*********************************" + item.keySecret?.substring(item.keySecret.length - 4);
}
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询开放API密钥列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询开放API密钥列表" })
async list(@Body(ALL) body: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.projectId = projectId;
body.query.userId = userId;
@@ -51,16 +51,16 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
return this.ok(res);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加开放API密钥" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加开放API密钥" })
async add(@Body(ALL) body: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.projectId = projectId;
body.userId = userId;
const res = await this.service.add(body);
return this.ok(res);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新开放API密钥" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新开放API密钥" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
@@ -68,8 +68,8 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
await this.service.update(bean);
return this.ok();
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询开放API密钥详情" })
async info(@Query('id') id: number) {
@Post("/info", { description: Constants.per.authOnly, summary: "查询开放API密钥详情" })
async info(@Query("id") id: number) {
const info = await this.checkPermission(id);
return this.ok(info);
}
@@ -77,32 +77,31 @@ export class OpenKeyController extends CrudController<OpenKeyService> {
private async checkPermission(id: number) {
const info = await this.service.info(id);
if (!info) {
throw new Error('密钥不存在');
throw new Error("密钥不存在");
}
if (info.scope === 'user'){
await this.checkOwner(this.getService(), id, "write");;
}else{
if (info.scope === "user") {
await this.checkOwner(this.getService(), id, "write");
} else {
await this.checkOwner(this.getService(), id, "read");
}
return info
return info;
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除开放API密钥" })
async delete(@Query('id') id: number) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除开放API密钥" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
return await super.delete(id);
}
@Post('/getApiToken', { description: Constants.per.authOnly, summary: "获取API测试令牌" })
async getApiToken(@Body('id') id: number) {
@Post("/getApiToken", { description: Constants.per.authOnly, summary: "获取API测试令牌" })
async getApiToken(@Body("id") id: number) {
await this.checkPermission(id);
const token = await this.service.getApiToken(id);
return this.ok(token);
}
@Post('/getSecret', { description: Constants.per.authOnly, summary: "获取密钥" })
async getSecret(@Body('id') id: number) {
@Post("/getSecret", { description: Constants.per.authOnly, summary: "获取密钥" })
async getSecret(@Body("id") id: number) {
const info = await this.checkPermission(id);
return this.ok(info.keySecret);
}
@@ -1,16 +1,16 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController } from '@certd/lib-server';
import { AccessService } from '@certd/lib-server';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { AccessDefine } from '@certd/pipeline';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { Constants, CrudController } from "@certd/lib-server";
import { AccessService } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { AccessDefine } from "@certd/pipeline";
import { ApiTags } from "@midwayjs/swagger";
/**
* 授权
*/
@Provide()
@ApiTags(['pipeline-access'])
@Controller('/api/pi/access')
@ApiTags(["pipeline-access"])
@Controller("/api/pi/access")
export class AccessController extends CrudController<AccessService> {
@Inject()
service: AccessService;
@@ -21,18 +21,18 @@ export class AccessController extends CrudController<AccessService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询授权配置分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询授权配置分页列表" })
async page(@Body(ALL) body) {
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
delete body.query.userId;
body.query.userId = userId;
body.query.projectId = projectId;
let name = body.query?.name;
const name = body.query?.name;
delete body.query.name;
const buildQuery = qb => {
if (name) {
qb.andWhere('name like :name', { name: `%${name.trim()}%` });
qb.andWhere("name like :name", { name: `%${name.trim()}%` });
}
};
const res = await this.service.page({
@@ -44,60 +44,60 @@ export class AccessController extends CrudController<AccessService> {
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询授权配置列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询授权配置列表" })
async list(@Body(ALL) body) {
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId;
return super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加授权配置" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加授权配置" })
async add(@Body(ALL) bean) {
const { projectId, userId } = await this.getProjectUserIdWrite()
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.userId = userId;
bean.projectId = projectId;
return super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新授权配置" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新授权配置" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
delete bean.projectId;
return super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询授权配置详情" })
async info(@Query('id') id: number) {
@Post("/info", { description: Constants.per.authOnly, summary: "查询授权配置详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read");
return super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除授权配置" })
async delete(@Query('id') id: number) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除授权配置" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
return super.delete(id);
}
@Post('/define', { description: Constants.per.authOnly, summary: "查询授权插件定义" })
async define(@Query('type') type: string) {
@Post("/define", { description: Constants.per.authOnly, summary: "查询授权插件定义" })
async define(@Query("type") type: string) {
const access = this.service.getDefineByType(type);
return this.ok(access);
}
@Post('/getSecretPlain', { description: Constants.per.authOnly, summary: "获取授权配置明文密钥" })
@Post("/getSecretPlain", { description: Constants.per.authOnly, summary: "获取授权配置明文密钥" })
async getSecretPlain(@Body(ALL) body: { id: number; key: string }) {
const {userId, projectId} = await this.checkOwner(this.getService(), body.id, "read");
const value = await this.service.getById(body.id, userId, projectId);
const { userId, projectId } = await this.checkOwner(this.getService(), body.id, "read");
const value = await this.service.getById(body.id, userId, projectId);
return this.ok(value[body.key]);
}
@Post('/accessTypeDict', { description: Constants.per.authOnly, summary: "查询授权类型字典" })
@Post("/accessTypeDict", { description: Constants.per.authOnly, summary: "查询授权类型字典" })
async getAccessTypeDict() {
let list: AccessDefine[] = this.service.getDefineList();
list = list.sort((a,b) => {
return (a.order??10) - (b.order??10);
list = list.sort((a, b) => {
return (a.order ?? 10) - (b.order ?? 10);
});
const dict = [];
for (const item of list) {
@@ -110,17 +110,17 @@ export class AccessController extends CrudController<AccessService> {
return this.ok(dict);
}
@Post('/simpleInfo', { description: Constants.per.authOnly, summary: "查询授权配置简单信息" })
async simpleInfo(@Query('id') id: number) {
@Post("/simpleInfo", { description: Constants.per.authOnly, summary: "查询授权配置简单信息" })
async simpleInfo(@Query("id") id: number) {
// await this.authService.checkUserIdButAllowAdmin(this.ctx, this.service, id);
// await this.checkOwner(this.getService(), id, "read",true);
const res = await this.service.getSimpleInfo(id);
return this.ok(res);
}
@Post('/getDictByIds', { description: Constants.per.authOnly, summary: "根据ID列表获取授权配置字典" })
async getDictByIds(@Body('ids') ids: number[]) {
const { userId, projectId } = await this.getProjectUserIdRead()
@Post("/getDictByIds", { description: Constants.per.authOnly, summary: "根据ID列表获取授权配置字典" })
async getDictByIds(@Body("ids") ids: number[]) {
const { userId, projectId } = await this.getProjectUserIdRead();
const res = await this.service.getSimpleByIds(ids, userId, projectId);
return this.ok(res);
}
@@ -1,64 +1,60 @@
import { Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { PipelineService } from '../../../modules/pipeline/service/pipeline-service.js';
import { BaseController, Constants, PermissionException } from '@certd/lib-server';
import { StorageService } from '../../../modules/pipeline/service/storage-service.js';
import { Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { BaseController, Constants, PermissionException } from "@certd/lib-server";
import { StorageService } from "../../../modules/pipeline/service/storage-service.js";
import { CertReader } from "@certd/plugin-cert";
import { UserSettingsService } from '../../../modules/mine/service/user-settings-service.js';
import { UserGrantSetting } from '../../../modules/mine/service/models.js';
import { ApiTags } from '@midwayjs/swagger';
import { UserSettingsService } from "../../../modules/mine/service/user-settings-service.js";
import { UserGrantSetting } from "../../../modules/mine/service/models.js";
import { ApiTags } from "@midwayjs/swagger";
@Provide()
@Controller('/api/pi/cert')
@ApiTags(['pipeline-cert'])
@Controller("/api/pi/cert")
@ApiTags(["pipeline-cert"])
export class CertController extends BaseController {
@Inject()
pipelineService: PipelineService;
@Inject()
storeService: StorageService;
@Inject()
userSettingsService: UserSettingsService;
@Post('/get', { description: Constants.per.authOnly, summary: "获取证书" })
async getCert(@Query('id') id: number) {
const {userId} = await this.getProjectUserIdRead()
@Post("/get", { description: Constants.per.authOnly, summary: "获取证书" })
async getCert(@Query("id") id: number) {
const { userId } = await this.getProjectUserIdRead();
const pipleinUserId = await this.pipelineService.getPipelineUserId(id);
if (pipleinUserId !== userId) {
// 如果是管理员,检查用户是否有授权管理员查看
const isAdmin = await this.isAdmin()
const isAdmin = await this.isAdmin();
if (!isAdmin) {
throw new PermissionException();
}
// 是否允许管理员查看
const setting = await this.userSettingsService.getSetting<UserGrantSetting>(pipleinUserId,null, UserGrantSetting, false);
const setting = await this.userSettingsService.getSetting<UserGrantSetting>(pipleinUserId, null, UserGrantSetting, false);
if (setting?.allowAdminViewCerts !== true) {
//不允许管理员查看
throw new PermissionException("该流水线的用户还未授权管理员查看证书,请先让用户在”设置->授权委托“中打开开关");
}
}
const privateVars = await this.storeService.getPipelinePrivateVars(id);
const certInfo = privateVars.cert;
if (certInfo?.crt) {
const certReader = new CertReader(certInfo);
certInfo.detail = certReader.detail
certInfo.detail = certReader.detail;
}
return this.ok(certInfo);
}
@Post('/readCertDetail', { description: Constants.per.authOnly, summary: "读取证书详情" })
async readCertDetail(@Body('crt') crt: string) {
@Post("/readCertDetail", { description: Constants.per.authOnly, summary: "读取证书详情" })
async readCertDetail(@Body("crt") crt: string) {
if (!crt) {
throw new Error('crt is required');
throw new Error("crt is required");
}
const certDetail = CertReader.readCertDetail(crt)
const certDetail = CertReader.readCertDetail(crt);
return this.ok(certDetail);
}
}
@@ -1,26 +1,26 @@
import { ALL, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { DnsProviderService } from '../../../modules/pipeline/service/dns-provider-service.js';
import { BaseController } from '@certd/lib-server';
import { Constants } from '@certd/lib-server';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { DnsProviderService } from "../../../modules/pipeline/service/dns-provider-service.js";
import { BaseController } from "@certd/lib-server";
import { Constants } from "@certd/lib-server";
import { ApiTags } from "@midwayjs/swagger";
/**
* 插件
*/
@Provide()
@Controller('/api/pi/dnsProvider')
@ApiTags(['pipeline-dns-provider'])
@Controller("/api/pi/dnsProvider")
@ApiTags(["pipeline-dns-provider"])
export class DnsProviderController extends BaseController {
@Inject()
service: DnsProviderService;
@Post('/list', { description: Constants.per.authOnly, summary: "查询DNS提供商列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询DNS提供商列表" })
async list(@Query(ALL) query: any) {
const list = this.service.getList();
return this.ok(list);
}
@Post('/dnsProviderTypeDict', { description: Constants.per.authOnly, summary: "查询DNS提供商类型字典" })
@Post("/dnsProviderTypeDict", { description: Constants.per.authOnly, summary: "查询DNS提供商类型字典" })
async getDnsProviderTypeDict() {
const list = this.service.getList();
const dict = [];
@@ -1,27 +1,17 @@
import {ALL, Body, Controller, Inject, Post, Provide} from '@midwayjs/core';
import {AccessGetter, AccessService, BaseController, Constants} from '@certd/lib-server';
import {
AccessRequestHandleReq,
IAccessService,
ITaskPlugin,
newAccess,
newNotification,
NotificationRequestHandleReq,
pluginRegistry,
PluginRequestHandleReq,
TaskInstanceContext,
} from '@certd/pipeline';
import {EmailService} from '../../../modules/basic/service/email-service.js';
import {http, HttpRequestConfig, logger, mergeUtils, utils} from '@certd/basic';
import {NotificationService} from '../../../modules/pipeline/service/notification-service.js';
import {TaskServiceBuilder} from "../../../modules/pipeline/service/getter/task-service-getter.js";
import { cloneDeep } from 'lodash-es';
import { ApiTags } from '@midwayjs/swagger';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { AccessGetter, AccessService, BaseController, Constants } from "@certd/lib-server";
import { AccessRequestHandleReq, IAccessService, ITaskPlugin, newAccess, newNotification, NotificationRequestHandleReq, pluginRegistry, PluginRequestHandleReq, TaskInstanceContext } from "@certd/pipeline";
import { EmailService } from "../../../modules/basic/service/email-service.js";
import { http, HttpRequestConfig, logger, mergeUtils, utils } from "@certd/basic";
import { NotificationService } from "../../../modules/pipeline/service/notification-service.js";
import { TaskServiceBuilder } from "../../../modules/pipeline/service/getter/task-service-getter.js";
import { cloneDeep } from "lodash-es";
import { ApiTags } from "@midwayjs/swagger";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
@Provide()
@Controller('/api/pi/handle')
@ApiTags(['pipeline-handle'])
@Controller("/api/pi/handle")
@ApiTags(["pipeline-handle"])
export class HandleController extends BaseController {
@Inject()
accessService: AccessService;
@@ -38,28 +28,28 @@ export class HandleController extends BaseController {
@Inject()
notificationService: NotificationService;
@Post('/access', { description: Constants.per.authOnly, summary: "处理授权请求" })
@Post("/access", { description: Constants.per.authOnly, summary: "处理授权请求" })
async accessRequest(@Body(ALL) body: AccessRequestHandleReq) {
let {projectId,userId} = await this.getProjectUserIdRead()
if (body.fromType === 'sys') {
let { projectId, userId } = await this.getProjectUserIdRead();
if (body.fromType === "sys") {
//系统级别的请求
const pass = await this.authService.checkPermission(this.ctx, "sys:settings:view");
if (!pass) {
throw new Error('权限不足');
throw new Error("权限不足");
}
projectId = null
userId = 0
projectId = null;
userId = 0;
}
let inputAccess = body.input;
if (body.record.id > 0) {
const oldEntity = await this.accessService.info(body.record.id);
if (oldEntity) {
if (oldEntity.userId !== userId && oldEntity.userId !== this.getUserId()) {
throw new Error('您没有权限使用该授权');
throw new Error("您没有权限使用该授权");
}
if (oldEntity.projectId && oldEntity.projectId !== projectId) {
throw new Error('您没有权限使用该授权(projectId不匹配)');
throw new Error("您没有权限使用该授权(projectId不匹配)");
}
const param: any = {
type: body.typeName,
@@ -69,8 +59,8 @@ export class HandleController extends BaseController {
inputAccess = this.accessService.decryptAccessEntity(param);
}
}
const accessGetter = new AccessGetter(userId,projectId, this.accessService.getById.bind(this.accessService));
const access = await newAccess(body.typeName, inputAccess,accessGetter);
const accessGetter = new AccessGetter(userId, projectId, this.accessService.getById.bind(this.accessService));
const access = await newAccess(body.typeName, inputAccess, accessGetter);
// mergeUtils.merge(access, body.input);
const res = await access.onRequest(body);
@@ -78,7 +68,7 @@ export class HandleController extends BaseController {
return this.ok(res);
}
@Post('/notification', { description: Constants.per.authOnly, summary: "处理通知请求" })
@Post("/notification", { description: Constants.per.authOnly, summary: "处理通知请求" })
async notificationRequest(@Body(ALL) body: NotificationRequestHandleReq) {
const input = body.input;
@@ -94,9 +84,9 @@ export class HandleController extends BaseController {
return this.ok(res);
}
@Post('/plugin', { description: Constants.per.authOnly, summary: "处理插件请求" })
@Post("/plugin", { description: Constants.per.authOnly, summary: "处理插件请求" })
async pluginRequest(@Body(ALL) body: PluginRequestHandleReq) {
const {projectId,userId} = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
const pluginDefine = pluginRegistry.get(body.typeName);
const pluginCls = await pluginDefine.target();
if (pluginCls == null) {
@@ -117,14 +107,14 @@ export class HandleController extends BaseController {
});
};
const taskServiceGetter = this.taskServiceBuilder.create({userId,projectId})
const taskServiceGetter = this.taskServiceBuilder.create({ userId, projectId });
const accessGetter = await taskServiceGetter.get<IAccessService>("accessService")
const accessGetter = await taskServiceGetter.get<IAccessService>("accessService");
//@ts-ignore
const taskCtx: TaskInstanceContext = {
pipeline: undefined,
step: undefined,
define: cloneDeep( pluginDefine.define),
define: cloneDeep(pluginDefine.define),
lastStatus: undefined,
http,
download,
@@ -136,7 +126,7 @@ export class HandleController extends BaseController {
userContext: undefined,
fileStore: undefined,
signal: undefined,
user: {id:userId,role:"user"},
user: { id: userId, role: "user" },
projectId,
// pipelineContext: this.pipelineContext,
// userContext: this.contextFactory.getContext('user', this.options.userId),
@@ -147,7 +137,7 @@ export class HandleController extends BaseController {
// }),
// signal: this.abort.signal,
utils,
serviceGetter:taskServiceGetter
serviceGetter: taskServiceGetter,
};
instance.setCtx(taskCtx);
mergeUtils.merge(plugin, body.input);
@@ -18,8 +18,8 @@ import { ApiTags } from "@midwayjs/swagger";
* 证书
*/
@Provide()
@Controller('/api/pi/history')
@ApiTags(['pipeline-history'])
@Controller("/api/pi/history")
@ApiTags(["pipeline-history"])
export class HistoryController extends CrudController<HistoryService> {
@Inject()
service: HistoryService;
@@ -41,10 +41,10 @@ export class HistoryController extends CrudController<HistoryService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询流水线执行历史分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询流水线执行历史分页列表" })
async page(@Body(ALL) body: any) {
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.projectId = projectId;
const isAdmin = await this.authService.isAdmin(this.ctx);
const publicSettings = await this.sysSettingsService.getPublicSettings();
@@ -64,7 +64,7 @@ export class HistoryController extends CrudController<HistoryService> {
const pipelines = await this.pipelineService.list({
query: pipelineQuery,
buildQuery: qb => {
qb.andWhere('title like :title', { title: `%${pipelineTitle}%` });
qb.andWhere("title like :title", { title: `%${pipelineTitle}%` });
},
});
pipelineIds = pipelines.map(p => p.id);
@@ -88,14 +88,14 @@ export class HistoryController extends CrudController<HistoryService> {
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询流水线执行历史列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询流水线执行历史列表" })
async list(@Body(ALL) body) {
const { projectId, userId } = await this.getProjectUserIdRead()
if (!body){
body = {}
const { projectId, userId } = await this.getProjectUserIdRead();
if (!body) {
body = {};
}
if (projectId){
body.projectId = projectId
if (projectId) {
body.projectId = projectId;
}
const isAdmin = this.authService.isAdmin(this.ctx);
@@ -111,7 +111,7 @@ export class HistoryController extends CrudController<HistoryService> {
};
const withDetail = body.withDetail;
delete body.withDetail;
let select: any = null
let select: any = null;
if (!withDetail) {
select = {
pipeline: true, // 后面这里改成false
@@ -129,9 +129,9 @@ export class HistoryController extends CrudController<HistoryService> {
}
const listRet = await this.getService().list({
query: body,
sort: { prop: 'id', asc: false },
sort: { prop: "id", asc: false },
buildQuery,
select
select,
});
for (const item of listRet) {
@@ -144,92 +144,92 @@ export class HistoryController extends CrudController<HistoryService> {
//@ts-ignore
item.version = json.version;
item.status = json.status.result
item.status = json.status.result;
delete item.pipeline;
}
return this.ok(listRet);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加流水线执行历史" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加流水线执行历史" })
async add(@Body(ALL) bean: PipelineEntity) {
const { projectId, userId } = await this.getProjectUserIdRead()
bean.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdRead();
bean.projectId = projectId;
bean.userId = userId;
return super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新流水线执行历史" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新流水线执行历史" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.getService(), bean.id,"write",true);
await this.checkOwner(this.getService(), bean.id, "write", true);
delete bean.userId;
delete bean.projectId;
return super.update(bean);
}
@Post('/save', { description: Constants.per.authOnly, summary: "保存流水线执行历史" })
@Post("/save", { description: Constants.per.authOnly, summary: "保存流水线执行历史" })
async save(@Body(ALL) bean: HistoryEntity) {
const { projectId,userId } = await this.getProjectUserIdWrite()
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.userId = userId;
bean.projectId = projectId;
if (bean.id > 0) {
//修改
delete bean.projectId;
delete bean.userId;
await this.checkOwner(this.getService(), bean.id,"write",true);
await this.checkOwner(this.getService(), bean.id, "write", true);
}
await this.service.save(bean);
return this.ok(bean.id);
}
@Post('/saveLog', { description: Constants.per.authOnly, summary: "保存流水线执行日志" })
@Post("/saveLog", { description: Constants.per.authOnly, summary: "保存流水线执行日志" })
async saveLog(@Body(ALL) bean: HistoryLogEntity) {
const { projectId,userId } = await this.getProjectUserIdWrite()
const { projectId, userId } = await this.getProjectUserIdWrite();
bean.projectId = projectId;
bean.userId = userId;
if (bean.id > 0) {
//修改
delete bean.projectId;
delete bean.userId;
await this.checkOwner(this.logService, bean.id,"write",true);
await this.checkOwner(this.logService, bean.id, "write", true);
}
await this.logService.save(bean);
return this.ok(bean.id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除流水线执行历史" })
async delete(@Query('id') id: number) {
await this.checkOwner(this.getService(), id,"write",true);
@Post("/delete", { description: Constants.per.authOnly, summary: "删除流水线执行历史" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write", true);
await super.delete(id);
return this.ok();
}
@Post('/deleteByIds', { description: Constants.per.authOnly, summary: "批量删除流水线执行历史" })
@Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除流水线执行历史" })
async deleteByIds(@Body(ALL) body: any) {
let {userId} = await this.checkOwner(this.getService(), body.ids,"write",true);
let { userId } = await this.checkOwner(this.getService(), body.ids, "write", true);
const isAdmin = await this.authService.isAdmin(this.ctx);
userId = isAdmin ? null : userId;
await this.getService().deleteByIds(body.ids, userId);
return this.ok();
}
@Post('/detail', { description: Constants.per.authOnly, summary: "查询流水线执行历史详情" })
async detail(@Query('id') id: number) {
await this.checkOwner(this.getService(), id,"read",true);
@Post("/detail", { description: Constants.per.authOnly, summary: "查询流水线执行历史详情" })
async detail(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read", true);
const detail = await this.service.detail(id);
return this.ok(detail);
}
@Post('/logs', { description: Constants.per.authOnly, summary: "查询流水线执行日志" })
async logs(@Query('id') id: number) {
await this.checkOwner(this.logService, id,"read",true);
@Post("/logs", { description: Constants.per.authOnly, summary: "查询流水线执行日志" })
async logs(@Query("id") id: number) {
await this.checkOwner(this.logService, id, "read", true);
const logInfo = await this.logService.info(id);
return this.ok(logInfo);
}
@Post('/files', { description: Constants.per.authOnly, summary: "查询流水线执行文件" })
async files(@Query('pipelineId') pipelineId: number, @Query('historyId') historyId: number) {
@Post("/files", { description: Constants.per.authOnly, summary: "查询流水线执行文件" })
async files(@Query("pipelineId") pipelineId: number, @Query("historyId") historyId: number) {
const files = await this.getFiles(historyId, pipelineId);
return this.ok(files);
}
@@ -243,24 +243,24 @@ export class HistoryController extends CrudController<HistoryService> {
history = await this.service.getLastHistory(pipelineId);
}
if (history == null) {
throw new CommonException('流水线还未运行过');
throw new CommonException("流水线还未运行过");
}
const {projectId} = await this.getProjectUserIdRead()
const { projectId } = await this.getProjectUserIdRead();
if (projectId) {
//enterprise模式
if(history.projectId !== projectId){
throw new PermissionException("您没有权限下载该流水线证书,请先加入该项目:"+history.projectId);
if (history.projectId !== projectId) {
throw new PermissionException("您没有权限下载该流水线证书,请先加入该项目:" + history.projectId);
}
//有权限下载
}else if (history.userId !== this.getUserId()) {
} else if (history.userId !== this.getUserId()) {
// 如果是管理员,检查用户是否有授权管理员查看
const isAdmin = await this.isAdmin()
const isAdmin = await this.isAdmin();
if (!isAdmin) {
throw new PermissionException();
}
// 是否允许管理员查看
const setting = await this.userSettingsService.getSetting<UserGrantSetting>(history.userId, null, UserGrantSetting, false);
if (setting?.allowAdminViewCerts!==true) {
if (setting?.allowAdminViewCerts !== true) {
//不允许管理员查看
throw new PermissionException("该流水线的用户还未授权管理员下载证书,请先让用户在”设置->授权委托“中打开开关");
}
@@ -269,12 +269,12 @@ export class HistoryController extends CrudController<HistoryService> {
return await this.service.getFiles(history);
}
@Get('/download', { description: Constants.per.authOnly, summary: "下载流水线执行文件" })
async download(@Query('pipelineId') pipelineId: number, @Query('historyId') historyId: number, @Query('fileId') fileId: string) {
@Get("/download", { description: Constants.per.authOnly, summary: "下载流水线执行文件" })
async download(@Query("pipelineId") pipelineId: number, @Query("historyId") historyId: number, @Query("fileId") fileId: string) {
const files = await this.getFiles(historyId, pipelineId);
const file = files.find(f => f.id === fileId);
if (file == null) {
throw new CommonException('file not found');
throw new CommonException("file not found");
}
// koa send file
// 下载文件的名称
@@ -284,7 +284,7 @@ export class HistoryController extends CrudController<HistoryService> {
logger.info(`download:${path}`);
// 以流的形式下载文件
this.ctx.attachment(path);
this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.set("Content-Type", "application/octet-stream");
return fs.createReadStream(path);
}
@@ -1,17 +1,17 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController, ValidateException } from '@certd/lib-server';
import { NotificationService } from '../../../modules/pipeline/service/notification-service.js';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { NotificationDefine } from '@certd/pipeline';
import { checkPlus } from '@certd/plus-core';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { Constants, CrudController, ValidateException } from "@certd/lib-server";
import { NotificationService } from "../../../modules/pipeline/service/notification-service.js";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { NotificationDefine } from "@certd/pipeline";
import { checkPlus } from "@certd/plus-core";
import { ApiTags } from "@midwayjs/swagger";
/**
* 通知
*/
@Provide()
@Controller('/api/pi/notification')
@ApiTags(['pipeline-notification'])
@Controller("/api/pi/notification")
@ApiTags(["pipeline-notification"])
export class NotificationController extends CrudController<NotificationService> {
@Inject()
service: NotificationService;
@@ -22,14 +22,14 @@ export class NotificationController extends CrudController<NotificationService>
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询通知配置分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询通知配置分页列表" })
async page(@Body(ALL) body) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
delete body.query.userId;
body.query.projectId = projectId;
const buildQuery = qb => {
qb.andWhere('user_id = :userId', { userId: userId});
qb.andWhere("user_id = :userId", { userId: userId });
};
const res = await this.service.page({
query: body.query,
@@ -40,24 +40,24 @@ export class NotificationController extends CrudController<NotificationService>
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询通知配置列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询通知配置列表" })
async list(@Body(ALL) body) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId;
return super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加通知配置" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加通知配置" })
async add(@Body(ALL) bean) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
bean.userId = userId;
bean.projectId = projectId;
const type = bean.type;
const define: NotificationDefine = this.service.getDefineByType(type);
if (!define) {
throw new ValidateException('通知类型不存在');
throw new ValidateException("通知类型不存在");
}
if (define.needPlus) {
checkPlus();
@@ -65,18 +65,18 @@ export class NotificationController extends CrudController<NotificationService>
return super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新通知配置" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新通知配置" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.getService(), bean.id,"write");
await this.checkOwner(this.getService(), bean.id, "write");
const old = await this.service.info(bean.id);
if (!old) {
throw new ValidateException('通知配置不存在');
throw new ValidateException("通知配置不存在");
}
if (old.type !== bean.type) {
const type = bean.type;
const define: NotificationDefine = this.service.getDefineByType(type);
if (!define) {
throw new ValidateException('通知类型不存在');
throw new ValidateException("通知类型不存在");
}
if (define.needPlus) {
checkPlus();
@@ -86,25 +86,25 @@ export class NotificationController extends CrudController<NotificationService>
delete bean.projectId;
return super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询通知配置详情" })
async info(@Query('id') id: number) {
await this.checkOwner(this.getService(), id,"read");
@Post("/info", { description: Constants.per.authOnly, summary: "查询通知配置详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read");
return super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除通知配置" })
async delete(@Query('id') id: number) {
await this.checkOwner(this.getService(), id,"write");
@Post("/delete", { description: Constants.per.authOnly, summary: "删除通知配置" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
return super.delete(id);
}
@Post('/define', { description: Constants.per.authOnly, summary: "查询通知插件定义" })
async define(@Query('type') type: string) {
@Post("/define", { description: Constants.per.authOnly, summary: "查询通知插件定义" })
async define(@Query("type") type: string) {
const notification = this.service.getDefineByType(type);
return this.ok(notification);
}
@Post('/getTypeDict', { description: Constants.per.authOnly, summary: "查询通知类型字典" })
@Post("/getTypeDict", { description: Constants.per.authOnly, summary: "查询通知类型字典" })
async getTypeDict() {
const list: any = this.service.getDefineList();
let dict = [];
@@ -125,48 +125,48 @@ export class NotificationController extends CrudController<NotificationService>
return this.ok(dict);
}
@Post('/simpleInfo', { description: Constants.per.authOnly, summary: "查询通知配置简单信息" })
async simpleInfo(@Query('id') id: number) {
const {projectId,userId} = await this.getProjectUserIdRead();
@Post("/simpleInfo", { description: Constants.per.authOnly, summary: "查询通知配置简单信息" })
async simpleInfo(@Query("id") id: number) {
const { projectId, userId } = await this.getProjectUserIdRead();
if (id === 0) {
//获取默认
const res = await this.service.getDefault(userId,projectId);
const res = await this.service.getDefault(userId, projectId);
if (!res) {
throw new ValidateException('默认通知配置不存在');
throw new ValidateException("默认通知配置不存在");
}
const simple = await this.service.getSimpleInfo(res.id);
return this.ok(simple);
}
await this.checkOwner(this.getService(), id,"read",true);
await this.checkOwner(this.getService(), id, "read", true);
const res = await this.service.getSimpleInfo(id);
return this.ok(res);
}
@Post('/getDefaultId', { description: Constants.per.authOnly, summary: "查询默认通知配置ID" })
@Post("/getDefaultId", { description: Constants.per.authOnly, summary: "查询默认通知配置ID" })
async getDefaultId() {
const {projectId,userId} = await this.getProjectUserIdRead();
const res = await this.service.getDefault(userId,projectId);
const { projectId, userId } = await this.getProjectUserIdRead();
const res = await this.service.getDefault(userId, projectId);
return this.ok(res?.id);
}
@Post('/setDefault', { description: Constants.per.authOnly, summary: "设置默认通知配置" })
async setDefault(@Query('id') id: number) {
const {projectId,userId} = await this.getProjectUserIdRead();
await this.checkOwner(this.getService(), id,"write");
const res = await this.service.setDefault(id, userId,projectId);
@Post("/setDefault", { description: Constants.per.authOnly, summary: "设置默认通知配置" })
async setDefault(@Query("id") id: number) {
const { projectId, userId } = await this.getProjectUserIdRead();
await this.checkOwner(this.getService(), id, "write");
const res = await this.service.setDefault(id, userId, projectId);
return this.ok(res);
}
@Post('/getOrCreateDefault', { description: Constants.per.authOnly, summary: "获取或创建默认通知配置" })
async getOrCreateDefault(@Body('email') email: string) {
const {projectId,userId} = await this.getProjectUserIdRead();
const res = await this.service.getOrCreateDefault(email, userId,projectId);
@Post("/getOrCreateDefault", { description: Constants.per.authOnly, summary: "获取或创建默认通知配置" })
async getOrCreateDefault(@Body("email") email: string) {
const { projectId, userId } = await this.getProjectUserIdRead();
const res = await this.service.getOrCreateDefault(email, userId, projectId);
return this.ok(res);
}
@Post('/options', { description: Constants.per.authOnly, summary: "查询通知配置选项" })
@Post("/options", { description: Constants.per.authOnly, summary: "查询通知配置选项" })
async options() {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
const res = await this.service.list({
query: {
userId: userId,
@@ -1,13 +1,12 @@
import { Constants, CrudController, SysSettingsService } from '@certd/lib-server';
import { isPlus } from '@certd/plus-core';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { ApiProperty, ApiTags } from '@midwayjs/swagger';
import { SiteInfoService } from '../../../modules/monitor/index.js';
import { HistoryService } from '../../../modules/pipeline/service/history-service.js';
import { PipelineService } from '../../../modules/pipeline/service/pipeline-service.js';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { PipelineEntity } from '../../../modules/pipeline/entity/pipeline.js';
import { Constants, CrudController, SysSettingsService } from "@certd/lib-server";
import { isPlus } from "@certd/plus-core";
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { ApiProperty, ApiTags } from "@midwayjs/swagger";
import { SiteInfoService } from "../../../modules/monitor/index.js";
import { HistoryService } from "../../../modules/pipeline/service/history-service.js";
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { PipelineEntity } from "../../../modules/pipeline/entity/pipeline.js";
const pipelineExample = `
// 流水线配置示例,实际传送时要去掉注释
@@ -67,50 +66,50 @@ const pipelineExample = `
"notificationId": 0, // 通知ID 0为使用默认通知
}
],
}`
}`;
export class PipelineSaveDTO {
@ApiProperty({ description: 'Id,修改时必传' })
id: number;
userId: number;
@ApiProperty({ description: '标题' })
title: string;
@ApiProperty({ description: '流水线详细配置,json格式的字符串', example: pipelineExample })
content: string;
@ApiProperty({ description: "Id,修改时必传" })
id: number;
userId: number;
@ApiProperty({ description: "标题" })
title: string;
@ApiProperty({ description: "流水线详细配置,json格式的字符串", example: pipelineExample })
content: string;
@ApiProperty({ description: '保留历史版本数量' })
keepHistoryCount: number;
@ApiProperty({ description: '分组ID' })
groupId: number;
@ApiProperty({ description: '备注' })
remark: string;
@ApiProperty({ description: '状态' })
status: string;
@ApiProperty({ description: '是否禁用' })
disabled: boolean;
@ApiProperty({ description: '类型' })
type: string;
webhookKey: string;
@ApiProperty({ description: '来源' })
from: string;
@ApiProperty({ description: '排序' })
order: number;
@ApiProperty({ description: '项目ID' })
projectId: number;
@ApiProperty({ description: '流水线有效期,单位秒' })
validTime: number;
@ApiProperty({ description: '是否增加证书监控' })
addToMonitorEnabled: boolean
@ApiProperty({ description: '增加证书监控的域名,逗号分隔' })
addToMonitorDomains: string
@ApiProperty({ description: "保留历史版本数量" })
keepHistoryCount: number;
@ApiProperty({ description: "分组ID" })
groupId: number;
@ApiProperty({ description: "备注" })
remark: string;
@ApiProperty({ description: "状态" })
status: string;
@ApiProperty({ description: "是否禁用" })
disabled: boolean;
@ApiProperty({ description: "类型" })
type: string;
webhookKey: string;
@ApiProperty({ description: "来源" })
from: string;
@ApiProperty({ description: "排序" })
order: number;
@ApiProperty({ description: "项目ID" })
projectId: number;
@ApiProperty({ description: "流水线有效期,单位秒" })
validTime: number;
@ApiProperty({ description: "是否增加证书监控" })
addToMonitorEnabled: boolean;
@ApiProperty({ description: "增加证书监控的域名,逗号分隔" })
addToMonitorDomains: string;
}
/**
* 证书
*/
@Provide()
@ApiTags(['pipeline'])
@Controller('/api/pi/pipeline')
@ApiTags(["pipeline"])
@Controller("/api/pi/pipeline")
export class PipelineController extends CrudController<PipelineService> {
@Inject()
service: PipelineService;
@@ -124,19 +123,18 @@ export class PipelineController extends CrudController<PipelineService> {
@Inject()
siteInfoService: SiteInfoService;
getService() {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询流水线分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询流水线分页列表" })
async page(@Body(ALL) body) {
const isAdmin = await this.authService.isAdmin(this.ctx);
const publicSettings = await this.sysSettingsService.getPublicSettings();
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
let onlyOther = false
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.projectId = projectId;
let onlyOther = false;
if (isAdmin) {
if (publicSettings.managerOtherUserPipeline) {
//管理员管理 其他用户
@@ -157,14 +155,14 @@ export class PipelineController extends CrudController<PipelineService> {
const buildQuery = qb => {
if (title) {
qb.andWhere('(title like :title or content like :content)', { title: `%${title}%`, content: `%${title}%` });
qb.andWhere("(title like :title or content like :content)", { title: `%${title}%`, content: `%${title}%` });
}
if (onlyOther) {
qb.andWhere('user_id != :userId', { userId: this.getUserId() });
qb.andWhere("user_id != :userId", { userId: this.getUserId() });
}
};
if (!body.sort || !body.sort?.prop) {
body.sort = { prop: 'order', asc: false };
body.sort = { prop: "order", asc: false };
}
const pageRet = await this.getService().page({
@@ -176,31 +174,30 @@ export class PipelineController extends CrudController<PipelineService> {
return this.ok(pageRet);
}
@Post('/getSimpleByIds', { description: Constants.per.authOnly, summary: "根据ID列表获取流水线简单信息" })
@Post("/getSimpleByIds", { description: Constants.per.authOnly, summary: "根据ID列表获取流水线简单信息" })
async getSimpleById(@Body(ALL) body) {
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
const ret = await this.getService().getSimplePipelines(body.ids, userId, projectId);
return this.ok(ret);
}
@Post('/add', { description: Constants.per.authOnly })
@Post("/add", { description: Constants.per.authOnly })
async add(@Body(ALL) bean: PipelineEntity) {
return await this.save(bean as any);
}
@Post('/update', { description: Constants.per.authOnly })
async update(@Body(ALL) bean:PipelineEntity) {
await this.checkOwner(this.getService(), bean.id,"write",true);
await this.service.update(bean as any);
return this.ok({});
@Post("/update", { description: Constants.per.authOnly })
async update(@Body(ALL) bean: PipelineEntity) {
await this.checkOwner(this.getService(), bean.id, "write", true);
await this.service.update(bean as any);
return this.ok({});
}
@Post('/save', { description: Constants.per.authOnly, summary: '新增/更新流水线' })
@Post("/save", { description: Constants.per.authOnly, summary: "新增/更新流水线" })
async save(@Body() bean: PipelineSaveDTO) {
const { userId ,projectId} = await this.getProjectUserIdWrite()
const { userId, projectId } = await this.getProjectUserIdWrite();
if (bean.id > 0) {
const {userId,projectId} = await this.checkOwner(this.getService(), bean.id,"write",true);
const { userId, projectId } = await this.checkOwner(this.getService(), bean.id, "write", true);
bean.userId = userId;
bean.projectId = projectId;
} else {
@@ -210,7 +207,7 @@ export class PipelineController extends CrudController<PipelineService> {
if (!this.isAdmin()) {
// 非管理员用户 不允许设置流水线有效期
delete bean.validTime
delete bean.validTime;
}
const { version } = await this.service.save(bean as any);
@@ -229,63 +226,62 @@ export class PipelineController extends CrudController<PipelineService> {
return this.ok({ id: bean.id, version: version });
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除流水线" })
async delete(@Query('id') id: number) {
await this.checkOwner(this.getService(), id,"write",true);
@Post("/delete", { description: Constants.per.authOnly, summary: "删除流水线" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write", true);
await this.service.delete(id);
return this.ok({});
}
@Post('/disabled', { description: Constants.per.authOnly, summary: "禁用流水线" })
@Post("/disabled", { description: Constants.per.authOnly, summary: "禁用流水线" })
async disabled(@Body(ALL) bean) {
await this.checkOwner(this.getService(), bean.id,"write",true);
await this.checkOwner(this.getService(), bean.id, "write", true);
delete bean.userId;
delete bean.projectId;
await this.service.disabled(bean.id, bean.disabled);
return this.ok({});
}
@Post('/detail', { description: Constants.per.authOnly, summary: "查询流水线详情" })
async detail(@Query('id') id: number) {
await this.checkOwner(this.getService(), id,"read",true);
@Post("/detail", { description: Constants.per.authOnly, summary: "查询流水线详情" })
async detail(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read", true);
const detail = await this.service.detail(id);
return this.ok(detail);
}
@Post('/trigger', { description: Constants.per.authOnly, summary: "触发流水线执行" })
async trigger(@Query('id') id: number, @Query('stepId') stepId?: string) {
await this.checkOwner(this.getService(), id,"write",true);
@Post("/trigger", { description: Constants.per.authOnly, summary: "触发流水线执行" })
async trigger(@Query("id") id: number, @Query("stepId") stepId?: string) {
await this.checkOwner(this.getService(), id, "write", true);
await this.service.trigger(id, stepId, true);
return this.ok({});
}
@Post('/cancel', { description: Constants.per.authOnly, summary: "取消流水线执行" })
async cancel(@Query('historyId') historyId: number) {
await this.checkOwner(this.historyService, historyId,"write",true);
@Post("/cancel", { description: Constants.per.authOnly, summary: "取消流水线执行" })
async cancel(@Query("historyId") historyId: number) {
await this.checkOwner(this.historyService, historyId, "write", true);
await this.service.cancel(historyId);
return this.ok({});
}
@Post('/count', { description: Constants.per.authOnly, summary: "查询流水线数量" })
@Post("/count", { description: Constants.per.authOnly, summary: "查询流水线数量" })
async count() {
const { userId } = await this.getProjectUserIdRead()
const { userId } = await this.getProjectUserIdRead();
const count = await this.service.count({ userId: userId });
return this.ok({ count });
}
private async checkPermissionCall(callback:any){
let { projectId ,userId} = await this.getProjectUserIdWrite()
if(projectId){
return await callback({userId,projectId});
private async checkPermissionCall(callback: any) {
let { projectId, userId } = await this.getProjectUserIdWrite();
if (projectId) {
return await callback({ userId, projectId });
}
const isAdmin = await this.authService.isAdmin(this.ctx);
userId = isAdmin ? undefined : userId;
return await callback({userId});
return await callback({ userId });
}
@Post('/batchDelete', { description: Constants.per.authOnly, summary: "批量删除流水线" })
async batchDelete(@Body('ids') ids: number[]) {
@Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除流水线" })
async batchDelete(@Body("ids") ids: number[]) {
// let { projectId ,userId} = await this.getProjectUserIdWrite()
// if(projectId){
// await this.service.batchDelete(ids, null,projectId);
@@ -295,16 +291,14 @@ export class PipelineController extends CrudController<PipelineService> {
// userId = isAdmin ? undefined : userId;
// await this.service.batchDelete(ids, userId);
// return this.ok({});
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchDelete(ids, userId,projectId);
})
return this.ok({})
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchDelete(ids, userId, projectId);
});
return this.ok({});
}
@Post('/batchUpdateGroup', { description: Constants.per.authOnly, summary: "批量更新流水线分组" })
async batchUpdateGroup(@Body('ids') ids: number[], @Body('groupId') groupId: number) {
@Post("/batchUpdateGroup", { description: Constants.per.authOnly, summary: "批量更新流水线分组" })
async batchUpdateGroup(@Body("ids") ids: number[], @Body("groupId") groupId: number) {
// let { projectId ,userId} = await this.getProjectUserIdWrite()
// if(projectId){
// await this.service.batchUpdateGroup(ids, groupId, null,projectId);
@@ -314,15 +308,14 @@ export class PipelineController extends CrudController<PipelineService> {
// const isAdmin = await this.authService.isAdmin(this.ctx);
// userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateGroup(ids, groupId, userId);
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchUpdateGroup(ids, groupId, userId,projectId);
})
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateGroup(ids, groupId, userId, projectId);
});
return this.ok({});
}
@Post('/batchUpdateTrigger', { description: Constants.per.authOnly, summary: "批量更新流水线触发器" })
async batchUpdateTrigger(@Body('ids') ids: number[], @Body('trigger') trigger: any) {
@Post("/batchUpdateTrigger", { description: Constants.per.authOnly, summary: "批量更新流水线触发器" })
async batchUpdateTrigger(@Body("ids") ids: number[], @Body("trigger") trigger: any) {
// let { projectId ,userId} = await this.getProjectUserIdWrite()
// if(projectId){
// await this.service.batchUpdateTrigger(ids, trigger, null,projectId);
@@ -332,54 +325,53 @@ export class PipelineController extends CrudController<PipelineService> {
// const isAdmin = await this.authService.isAdmin(this.ctx);
// userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateTrigger(ids, trigger, userId);
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchUpdateTrigger(ids, trigger, userId,projectId);
})
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateTrigger(ids, trigger, userId, projectId);
});
return this.ok({});
}
@Post('/batchUpdateNotification', { description: Constants.per.authOnly, summary: "批量更新流水线通知" })
async batchUpdateNotification(@Body('ids') ids: number[], @Body('notification') notification: any) {
@Post("/batchUpdateNotification", { description: Constants.per.authOnly, summary: "批量更新流水线通知" })
async batchUpdateNotification(@Body("ids") ids: number[], @Body("notification") notification: any) {
// const isAdmin = await this.authService.isAdmin(this.ctx);
// const userId = isAdmin ? undefined : this.getUserId();
// await this.service.batchUpdateNotifications(ids, notification, userId);
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchUpdateNotifications(ids, notification, userId,projectId);
})
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateNotifications(ids, notification, userId, projectId);
});
return this.ok({});
}
@Post('/batchUpdateCertApplyOptions', { description: Constants.per.authOnly, summary: "批量更新证书申请任务配置" })
async batchUpdateCertApplyOptions(@Body('ids') ids: number[], @Body('options') options: any) {
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchUpdateCertApplyOptions(ids, options, userId,projectId);
})
@Post("/batchUpdateCertApplyOptions", { description: Constants.per.authOnly, summary: "批量更新证书申请任务配置" })
async batchUpdateCertApplyOptions(@Body("ids") ids: number[], @Body("options") options: any) {
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchUpdateCertApplyOptions(ids, options, userId, projectId);
});
return this.ok({});
}
@Post('/batchRerun', { description: Constants.per.authOnly, summary: "批量重新运行流水线" })
async batchRerun(@Body('ids') ids: number[], @Body('force') force: boolean) {
await this.checkPermissionCall(async ({userId,projectId})=>{
await this.service.batchRerun(ids, force,userId,projectId);
})
@Post("/batchRerun", { description: Constants.per.authOnly, summary: "批量重新运行流水线" })
async batchRerun(@Body("ids") ids: number[], @Body("force") force: boolean) {
await this.checkPermissionCall(async ({ userId, projectId }) => {
await this.service.batchRerun(ids, force, userId, projectId);
});
return this.ok({});
}
@Post('/batchTransfer', { description: Constants.per.authOnly, summary: "批量迁移流水线" })
async batchTransfer(@Body('ids') ids: number[], @Body('toProjectId') toProjectId: number) {
await this.checkPermissionCall(async ({})=>{
@Post("/batchTransfer", { description: Constants.per.authOnly, summary: "批量迁移流水线" })
async batchTransfer(@Body("ids") ids: number[], @Body("toProjectId") toProjectId: number) {
await this.checkPermissionCall(async ({}) => {
await this.service.batchTransfer(ids, toProjectId);
})
});
return this.ok({});
}
@Post('/refreshWebhookKey', { description: Constants.per.authOnly, summary: "刷新Webhook密钥" })
async refreshWebhookKey(@Body('id') id: number) {
await this.checkOwner(this.getService(), id,"write",true);
@Post("/refreshWebhookKey", { description: Constants.per.authOnly, summary: "刷新Webhook密钥" })
async refreshWebhookKey(@Body("id") id: number) {
await this.checkOwner(this.getService(), id, "write", true);
const res = await this.service.refreshWebhookKey(id);
return this.ok({
webhookKey: res,
});
}
}
@@ -1,15 +1,15 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController } from '@certd/lib-server';
import { AuthService } from '../../../modules/sys/authority/service/auth-service.js';
import { PipelineGroupService } from '../../../modules/pipeline/service/pipeline-group-service.js';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { Constants, CrudController } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { PipelineGroupService } from "../../../modules/pipeline/service/pipeline-group-service.js";
import { ApiTags } from "@midwayjs/swagger";
/**
* 通知
*/
@Provide()
@Controller('/api/pi/pipeline/group')
@ApiTags(['pipeline-group'])
@Controller("/api/pi/pipeline/group")
@ApiTags(["pipeline-group"])
export class PipelineGroupController extends CrudController<PipelineGroupService> {
@Inject()
service: PipelineGroupService;
@@ -20,14 +20,14 @@ export class PipelineGroupController extends CrudController<PipelineGroupService
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询流水线分组分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询流水线分组分页列表" })
async page(@Body(ALL) body: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
delete body.query.userId;
body.query.projectId = projectId;
const buildQuery = qb => {
qb.andWhere('user_id = :userId', { userId: userId });
qb.andWhere("user_id = :userId", { userId: userId });
};
const res = await this.service.page({
query: body.query,
@@ -38,45 +38,45 @@ export class PipelineGroupController extends CrudController<PipelineGroupService
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询流水线分组列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询流水线分组列表" })
async list(@Body(ALL) body: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId;
return await super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加流水线分组" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加流水线分组" })
async add(@Body(ALL) bean: any) {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
bean.userId = userId;
bean.projectId = projectId;
return await super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新流水线分组" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新流水线分组" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
delete bean.projectId;
return await super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询流水线分组详情" })
async info(@Query('id') id: number) {
@Post("/info", { description: Constants.per.authOnly, summary: "查询流水线分组详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read");
return await super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除流水线分组" })
async delete(@Query('id') id: number) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除流水线分组" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
return await super.delete(id);
}
@Post('/all', { description: Constants.per.authOnly, summary: "查询所有流水线分组" })
@Post("/all", { description: Constants.per.authOnly, summary: "查询所有流水线分组" })
async all() {
const {projectId,userId} = await this.getProjectUserIdRead();
const { projectId, userId } = await this.getProjectUserIdRead();
const list: any = await this.service.find({
where: {
userId: userId,
@@ -1,16 +1,16 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { BaseController, Constants } from '@certd/lib-server';
import { PluginService } from '../../../modules/plugin/service/plugin-service.js';
import { PluginConfigService } from '../../../modules/plugin/service/plugin-config-service.js';
import {pluginGroups} from "@certd/pipeline";
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { BaseController, Constants } from "@certd/lib-server";
import { PluginService } from "../../../modules/plugin/service/plugin-service.js";
import { PluginConfigService } from "../../../modules/plugin/service/plugin-config-service.js";
import { pluginGroups } from "@certd/pipeline";
import { ApiTags } from "@midwayjs/swagger";
/**
* 插件
*/
@Provide()
@Controller('/api/pi/plugin')
@ApiTags(['pipeline-plugin'])
@Controller("/api/pi/plugin")
@ApiTags(["pipeline-plugin"])
export class PluginController extends BaseController {
@Inject()
service: PluginService;
@@ -18,39 +18,39 @@ export class PluginController extends BaseController {
@Inject()
pluginConfigService: PluginConfigService;
@Post('/list', { description: Constants.per.authOnly, summary: "查询插件列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询插件列表" })
async list(@Query(ALL) query: any) {
const list = await this.service.getEnabledBuiltInList();
return this.ok(list);
}
@Post('/groups', { description: Constants.per.authOnly, summary: "查询插件分组" })
@Post("/groups", { description: Constants.per.authOnly, summary: "查询插件分组" })
async groups(@Query(ALL) query: any) {
const group = await this.service.getEnabledBuildInGroup();
return this.ok(group);
}
@Post('/groupsList', { description: Constants.per.authOnly, summary: "查询插件分组列表" })
@Post("/groupsList", { description: Constants.per.authOnly, summary: "查询插件分组列表" })
async groupsList(@Query(ALL) query: any) {
const groups = pluginGroups
const groupsList:any = []
const groups = pluginGroups;
const groupsList: any = [];
for (const key in groups) {
const group = {
...groups[key]
}
delete group.plugins
groupsList.push(group)
...groups[key],
};
delete group.plugins;
groupsList.push(group);
}
return this.ok(groupsList);
}
@Post('/getDefineByType', { description: Constants.per.authOnly, summary: "根据类型获取插件定义" })
async getDefineByType(@Body('type') type: string) {
@Post("/getDefineByType", { description: Constants.per.authOnly, summary: "根据类型获取插件定义" })
async getDefineByType(@Body("type") type: string) {
const define = await this.service.getDefineByType(type);
return this.ok(define);
}
@Post('/config', { description: Constants.per.authOnly, summary: "获取插件配置" })
@Post("/config", { description: Constants.per.authOnly, summary: "获取插件配置" })
async config(@Body(ALL) body: { id?: number; name?: string; type: string }) {
const config = await this.pluginConfigService.getPluginConfig(body);
return this.ok(config);
@@ -1,16 +1,16 @@
import { Constants, CrudController } from '@certd/lib-server';
import { DomainParser } from '@certd/plugin-cert';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from '@midwayjs/core';
import { Constants, CrudController } from "@certd/lib-server";
import { DomainParser } from "@certd/plugin-cert";
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { SubDomainService } from "../../../modules/pipeline/service/sub-domain-service.js";
import { TaskServiceBuilder } from '../../../modules/pipeline/service/getter/task-service-getter.js';
import { ApiTags } from '@midwayjs/swagger';
import { TaskServiceBuilder } from "../../../modules/pipeline/service/getter/task-service-getter.js";
import { ApiTags } from "@midwayjs/swagger";
/**
* 子域名托管
*/
@Provide()
@Controller('/api/pi/subDomain')
@ApiTags(['pipeline-subdomain'])
@Controller("/api/pi/subDomain")
@ApiTags(["pipeline-subdomain"])
export class SubDomainController extends CrudController<SubDomainService> {
@Inject()
service: SubDomainService;
@@ -22,25 +22,24 @@ export class SubDomainController extends CrudController<SubDomainService> {
return this.service;
}
@Post('/parseDomain', { description: Constants.per.authOnly, summary: "解析域名" })
async parseDomain(@Body("fullDomain") fullDomain:string) {
const {projectId,userId} = await this.getProjectUserIdRead();
@Post("/parseDomain", { description: Constants.per.authOnly, summary: "解析域名" })
async parseDomain(@Body("fullDomain") fullDomain: string) {
const { projectId, userId } = await this.getProjectUserIdRead();
const taskService = this.taskServiceBuilder.create({ userId: userId, projectId: projectId });
const subDomainGetter = await taskService.getSubDomainsGetter();
const domainParser = new DomainParser(subDomainGetter)
const domain = await domainParser.parse(fullDomain)
const domainParser = new DomainParser(subDomainGetter);
const domain = await domainParser.parse(fullDomain);
return this.ok(domain);
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询子域名分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询子域名分页列表" })
async page(@Body(ALL) body) {
const {userId,projectId} = await this.getProjectUserIdRead();
const { userId, projectId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
delete body.query.userId;
body.query.projectId = projectId;
const buildQuery = qb => {
qb.andWhere('user_id = :userId', { userId: userId });
qb.andWhere("user_id = :userId", { userId: userId });
};
const res = await this.service.page({
query: body.query,
@@ -51,45 +50,45 @@ export class SubDomainController extends CrudController<SubDomainService> {
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询子域名列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询子域名列表" })
async list(@Body(ALL) body) {
const {userId,projectId} = await this.getProjectUserIdRead();
const { userId, projectId } = await this.getProjectUserIdRead();
body.query = body.query ?? {};
body.query.userId = userId;
body.query.projectId = projectId;
return super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加子域名" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加子域名" })
async add(@Body(ALL) bean) {
const {userId,projectId} = await this.getProjectUserIdRead();
const { userId, projectId } = await this.getProjectUserIdRead();
bean.userId = userId;
bean.projectId = projectId;
return super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新子域名" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新子域名" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.getService(), bean.id, "write");
delete bean.userId;
delete bean.projectId;
return super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询子域名详情" })
async info(@Query('id') id: number) {
@Post("/info", { description: Constants.per.authOnly, summary: "查询子域名详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "read");
return super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除子域名" })
async delete(@Query('id') id: number) {
@Post("/delete", { description: Constants.per.authOnly, summary: "删除子域名" })
async delete(@Query("id") id: number) {
await this.checkOwner(this.getService(), id, "write");
return super.delete(id);
}
@Post('/batchDelete', { description: Constants.per.authOnly, summary: "批量删除子域名" })
async batchDelete(@Body('ids') ids: number[]) {
const {userId,projectId} = await this.getProjectUserIdWrite();
@Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除子域名" })
async batchDelete(@Body("ids") ids: number[]) {
const { userId, projectId } = await this.getProjectUserIdWrite();
await this.service.batchDelete(ids, userId, projectId);
return this.ok({});
}
@@ -1,15 +1,15 @@
import {ALL, Body, Controller, Inject, Post, Provide, Query} from '@midwayjs/core';
import {Constants, CrudController} from '@certd/lib-server';
import { TemplateService } from '../../../modules/pipeline/service/template-service.js';
import { checkPlus } from '@certd/plus-core';
import { ApiTags } from '@midwayjs/swagger';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { Constants, CrudController } from "@certd/lib-server";
import { TemplateService } from "../../../modules/pipeline/service/template-service.js";
import { checkPlus } from "@certd/plus-core";
import { ApiTags } from "@midwayjs/swagger";
/**
* 流水线模版
*/
@Provide()
@Controller('/api/pi/template')
@ApiTags(['pipeline-template'])
@Controller("/api/pi/template")
@ApiTags(["pipeline-template"])
export class TemplateController extends CrudController<TemplateService> {
@Inject()
service: TemplateService;
@@ -18,17 +18,15 @@ export class TemplateController extends CrudController<TemplateService> {
return this.service;
}
@Post('/page', { description: Constants.per.authOnly, summary: "查询流水线模版分页列表" })
@Post("/page", { description: Constants.per.authOnly, summary: "查询流水线模版分页列表" })
async page(@Body(ALL) body) {
body.query = body.query ?? {};
delete body.query.userId;
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.projectId = projectId;
const buildQuery = qb => {
qb.andWhere('user_id = :userId', { userId: userId });
qb.andWhere("user_id = :userId", { userId: userId });
};
const res = await this.service.page({
query: body.query,
@@ -39,63 +37,63 @@ export class TemplateController extends CrudController<TemplateService> {
return this.ok(res);
}
@Post('/list', { description: Constants.per.authOnly, summary: "查询流水线模版列表" })
@Post("/list", { description: Constants.per.authOnly, summary: "查询流水线模版列表" })
async list(@Body(ALL) body) {
body.query = body.query ?? {};
const { projectId, userId } = await this.getProjectUserIdRead()
body.query.projectId = projectId
body.query.userId = userId
const { projectId, userId } = await this.getProjectUserIdRead();
body.query.projectId = projectId;
body.query.userId = userId;
return super.list(body);
}
@Post('/add', { description: Constants.per.authOnly, summary: "添加流水线模版" })
@Post("/add", { description: Constants.per.authOnly, summary: "添加流水线模版" })
async add(@Body(ALL) bean) {
const { projectId, userId } = await this.getProjectUserIdRead()
const { projectId, userId } = await this.getProjectUserIdRead();
bean.userId = userId;
bean.projectId = projectId
checkPlus()
bean.projectId = projectId;
checkPlus();
return super.add(bean);
}
@Post('/update', { description: Constants.per.authOnly, summary: "更新流水线模版" })
@Post("/update", { description: Constants.per.authOnly, summary: "更新流水线模版" })
async update(@Body(ALL) bean) {
await this.checkOwner(this.service, bean.id, "write");
delete bean.userId;
delete bean.projectId;
return super.update(bean);
}
@Post('/info', { description: Constants.per.authOnly, summary: "查询流水线模版详情" })
async info(@Query('id') id: number) {
await this.checkOwner(this.service, id, "read");
@Post("/info", { description: Constants.per.authOnly, summary: "查询流水线模版详情" })
async info(@Query("id") id: number) {
await this.checkOwner(this.service, id, "read");
return super.info(id);
}
@Post('/delete', { description: Constants.per.authOnly, summary: "删除流水线模版" })
async delete(@Query('id') id: number) {
const { userId ,projectId } = await this.getProjectUserIdWrite()
await this.service.batchDelete([id], userId,projectId);
@Post("/delete", { description: Constants.per.authOnly, summary: "删除流水线模版" })
async delete(@Query("id") id: number) {
const { userId, projectId } = await this.getProjectUserIdWrite();
await this.service.batchDelete([id], userId, projectId);
return this.ok({});
}
@Post('/batchDelete', { description: Constants.per.authOnly, summary: "批量删除流水线模版" })
async batchDelete(@Body('ids') ids: number[]) {
const { userId ,projectId } = await this.getProjectUserIdWrite()
await this.service.batchDelete(ids, userId,projectId);
@Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除流水线模版" })
async batchDelete(@Body("ids") ids: number[]) {
const { userId, projectId } = await this.getProjectUserIdWrite();
await this.service.batchDelete(ids, userId, projectId);
return this.ok({});
}
@Post('/detail', { description: Constants.per.authOnly, summary: "查询流水线模版详情" })
async detail(@Query('id') id: number) {
const { userId ,projectId } = await this.getProjectUserIdRead()
const detail = await this.service.detail(id, userId,projectId);
@Post("/detail", { description: Constants.per.authOnly, summary: "查询流水线模版详情" })
async detail(@Query("id") id: number) {
const { userId, projectId } = await this.getProjectUserIdRead();
const detail = await this.service.detail(id, userId, projectId);
return this.ok(detail);
}
@Post('/createPipelineByTemplate', { description: Constants.per.authOnly, summary: "根据模版创建流水线" })
@Post("/createPipelineByTemplate", { description: Constants.per.authOnly, summary: "根据模版创建流水线" })
async createPipelineByTemplate(@Body(ALL) body: any) {
const { userId ,projectId } = await this.getProjectUserIdWrite()
const { userId, projectId } = await this.getProjectUserIdWrite();
body.userId = userId;
body.projectId = projectId
checkPlus()
body.projectId = projectId;
checkPlus();
const res = await this.service.createPipelineByTemplate(body);
return this.ok(res);
}