diff --git a/packages/ui/certd-client/src/locales/langs/en-US/certd/mine.ts b/packages/ui/certd-client/src/locales/langs/en-US/certd/mine.ts
index a66719dc0..31afc672d 100644
--- a/packages/ui/certd-client/src/locales/langs/en-US/certd/mine.ts
+++ b/packages/ui/certd-client/src/locales/langs/en-US/certd/mine.ts
@@ -13,14 +13,14 @@ export default {
inputVerifyCode: "Please enter the verification code",
myInfo: "My Information",
user: {
- greeting: "Hello",
- profile: "Account Info",
- logout: "Logout",
- setting: {
- grantSetting: "Grant Settings",
- saveSuccess: "Save Success",
- allowAdminViewCerts: "Allow Admin view and download Certs",
- allowAdminViewCertsHelper: "Allow admin view and download all certificates",
- },
- },
+ greeting: "Hello",
+ profile: "Account Info",
+ logout: "Logout",
+ setting: {
+ grantSetting: "Grant Settings",
+ saveSuccess: "Save Success",
+ allowAdminViewCerts: "Allow Admin view and download Certs",
+ allowAdminViewCertsHelper: "Allow admin view and download all certificates",
+ },
+ },
};
diff --git a/packages/ui/certd-server/app.js b/packages/ui/certd-server/app.js
index 060add6d9..23173f248 100644
--- a/packages/ui/certd-server/app.js
+++ b/packages/ui/certd-server/app.js
@@ -1,8 +1,8 @@
// 获取框架
-const WebFramework = require('@midwayjs/koa').Framework;
-const { Bootstrap } = require('@midwayjs/bootstrap');
+const WebFramework = require("@midwayjs/koa").Framework;
+const { Bootstrap } = require("@midwayjs/bootstrap");
-const DirectoryFileDetector = require('@midwayjs/core').DirectoryFileDetector;
+const DirectoryFileDetector = require("@midwayjs/core").DirectoryFileDetector;
const baseDir = process.cwd();
const customFileDetector = new DirectoryFileDetector({
@@ -12,7 +12,7 @@ const customFileDetector = new DirectoryFileDetector({
module.exports = async () => {
// 加载框架并执行
await Bootstrap.configure({
- ignore: ["**/plugins/**","/plugins/","plugins","dist/plugins","/dist/plugins","dist\\plugins","dist/plugins"],
+ ignore: ["**/plugins/**", "/plugins/", "plugins", "dist/plugins", "/dist/plugins", "dist\\plugins", "dist/plugins"],
moduleDetector: customFileDetector,
}).run();
// 获取依赖注入容器
diff --git a/packages/ui/certd-server/before-build.js b/packages/ui/certd-server/before-build.js
index 4632200ff..dde8c87b0 100644
--- a/packages/ui/certd-server/before-build.js
+++ b/packages/ui/certd-server/before-build.js
@@ -1,22 +1,22 @@
-import fs from 'fs';
+import fs from "fs";
//瘦身
-const filePath = './node_modules/typeorm/platform/PlatformTools.js';
+const filePath = "./node_modules/typeorm/platform/PlatformTools.js";
const find = `const cli_highlight_1 = require("cli-highlight");`;
-const rep = 'const cli_highlight_1 ={highlight: (str) => { return str }};';
+const rep = "const cli_highlight_1 ={highlight: (str) => { return str }};";
// 在 filePath 找到 find那一行 用 rep 替换
function slimming(filePath, find, rep) {
- fs.readFile(filePath, 'utf8', function (err, data) {
+ fs.readFile(filePath, "utf8", function (err, data) {
if (err) {
return console.log(err);
}
var result = data.replace(find, rep);
- fs.writeFile(filePath, result, 'utf8', function (err) {
+ fs.writeFile(filePath, result, "utf8", function (err) {
if (err) return console.log(err);
});
});
}
slimming(filePath, find, rep);
-slimming("./tsconfig.json",`"sourceMap": true,`, `"sourceMap": false,`)
-slimming("./tsconfig.json",`"inlineSourceMap": true,`, `"inlineSourceMap": false,`)
+slimming("./tsconfig.json", `"sourceMap": true,`, `"sourceMap": false,`);
+slimming("./tsconfig.json", `"inlineSourceMap": true,`, `"inlineSourceMap": false,`);
diff --git a/packages/ui/certd-server/bootstrap.js b/packages/ui/certd-server/bootstrap.js
index 6abeb8f23..6cdd899aa 100644
--- a/packages/ui/certd-server/bootstrap.js
+++ b/packages/ui/certd-server/bootstrap.js
@@ -1,4 +1,4 @@
-import { Bootstrap } from '@midwayjs/bootstrap';
+import { Bootstrap } from "@midwayjs/bootstrap";
await Bootstrap.configure({
- ignore: ["**/plugins/**","/plugins/","plugins","dist/plugins","/dist/plugins","dist\\plugins"]
- }).run();
+ ignore: ["**/plugins/**", "/plugins/", "plugins", "dist/plugins", "/dist/plugins", "dist\\plugins"],
+}).run();
diff --git a/packages/ui/certd-server/db/transform.js b/packages/ui/certd-server/db/transform.js
index 4e6aa799a..606529c9d 100644
--- a/packages/ui/certd-server/db/transform.js
+++ b/packages/ui/certd-server/db/transform.js
@@ -1,4 +1,4 @@
-import fs from 'fs';
+import fs from "fs";
/**
* ## sqlite与postgres不同点
* 1.
@@ -27,56 +27,55 @@ import fs from 'fs';
*/
function transformPG() {
// 读取文件列表
- const sqliteFiles = fs.readdirSync('./migration/');
- const pgFiles = fs.readdirSync('./migration-pg/');
+ const sqliteFiles = fs.readdirSync("./migration/");
+ const pgFiles = fs.readdirSync("./migration-pg/");
//找出pg里面没有的文件
const notFiles = sqliteFiles.filter(file => !pgFiles.includes(file));
for (const notFile of notFiles) {
//开始转换
- const sqliteSql = fs.readFileSync(`./migration/${notFile}`, 'utf-8');
- let pgSql = sqliteSql.replaceAll(/AUTOINCREMENT/g, 'GENERATED BY DEFAULT AS IDENTITY');
- pgSql = pgSql.replaceAll(/datetime/g, 'timestamp');
- pgSql = pgSql.replaceAll(/boolean DEFAULT \(0\)/g, 'boolean DEFAULT (false)');
- pgSql = pgSql.replaceAll(/boolean DEFAULT \(1\)/g, 'boolean DEFAULT (true)');
- pgSql = pgSql.replaceAll(/boolean.*NOT NULL DEFAULT \(0\)/g, 'boolean NOT NULL DEFAULT (false)');
- pgSql = pgSql.replaceAll(/boolean.*NOT NULL DEFAULT \(1\)/g, 'boolean NOT NULL DEFAULT (true)');
- pgSql = pgSql.replaceAll(/integer/g, 'bigint');
- pgSql = pgSql.replaceAll(/INTEGER/g, 'bigint');
- pgSql = pgSql.replaceAll(/last_insert_rowid\(\)/g, 'LASTVAL()');
+ const sqliteSql = fs.readFileSync(`./migration/${notFile}`, "utf-8");
+ let pgSql = sqliteSql.replaceAll(/AUTOINCREMENT/g, "GENERATED BY DEFAULT AS IDENTITY");
+ pgSql = pgSql.replaceAll(/datetime/g, "timestamp");
+ pgSql = pgSql.replaceAll(/boolean DEFAULT \(0\)/g, "boolean DEFAULT (false)");
+ pgSql = pgSql.replaceAll(/boolean DEFAULT \(1\)/g, "boolean DEFAULT (true)");
+ pgSql = pgSql.replaceAll(/boolean.*NOT NULL DEFAULT \(0\)/g, "boolean NOT NULL DEFAULT (false)");
+ pgSql = pgSql.replaceAll(/boolean.*NOT NULL DEFAULT \(1\)/g, "boolean NOT NULL DEFAULT (true)");
+ pgSql = pgSql.replaceAll(/integer/g, "bigint");
+ pgSql = pgSql.replaceAll(/INTEGER/g, "bigint");
+ pgSql = pgSql.replaceAll(/last_insert_rowid\(\)/g, "LASTVAL()");
fs.writeFileSync(`./migration-pg/${notFile}`, pgSql);
}
if (notFiles.length > 0) {
- console.log('sqlite->pg 转换完成');
+ console.log("sqlite->pg 转换完成");
- throw new Error('sqlite->pg 转换完成,有更新,需要测试pg');
+ throw new Error("sqlite->pg 转换完成,有更新,需要测试pg");
} else {
- console.log('sql无需更新');
+ console.log("sql无需更新");
}
}
function transformMysql() {
// 读取文件列表
- const sqliteFiles = fs.readdirSync('./migration/');
- const pgFiles = fs.readdirSync('./migration-mysql/');
+ const sqliteFiles = fs.readdirSync("./migration/");
+ const pgFiles = fs.readdirSync("./migration-mysql/");
//找出pg里面没有的文件
const notFiles = sqliteFiles.filter(file => !pgFiles.includes(file));
for (const notFile of notFiles) {
//开始转换
- const sqliteSql = fs.readFileSync(`./migration/${notFile}`, 'utf-8');
- let pgSql = sqliteSql.replaceAll(/AUTOINCREMENT/g, 'AUTO_INCREMENT');
- pgSql = pgSql.replaceAll(/datetime/g, 'timestamp');
+ const sqliteSql = fs.readFileSync(`./migration/${notFile}`, "utf-8");
+ let pgSql = sqliteSql.replaceAll(/AUTOINCREMENT/g, "AUTO_INCREMENT");
+ pgSql = pgSql.replaceAll(/datetime/g, "timestamp");
//DEFAULT (xxx) 替换成 DEFAULT xxx
- pgSql = pgSql.replaceAll(/DEFAULT \(([^)]*)\)/g, 'DEFAULT $1');
- pgSql = pgSql.replaceAll(/integer/g, 'bigint');
- pgSql = pgSql.replaceAll(/INTEGER/g, 'bigint');
- pgSql = pgSql.replaceAll(/last_insert_rowid\(\)/g, 'LAST_INSERT_ID()');
+ pgSql = pgSql.replaceAll(/DEFAULT \(([^)]*)\)/g, "DEFAULT $1");
+ pgSql = pgSql.replaceAll(/integer/g, "bigint");
+ pgSql = pgSql.replaceAll(/INTEGER/g, "bigint");
+ pgSql = pgSql.replaceAll(/last_insert_rowid\(\)/g, "LAST_INSERT_ID()");
//text 改成longtext
- pgSql = pgSql.replaceAll(/text/g, 'longtext');
+ pgSql = pgSql.replaceAll(/text/g, "longtext");
//双引号 替换成反引号
- pgSql = pgSql.replaceAll(/"/g, '`');
+ pgSql = pgSql.replaceAll(/"/g, "`");
-
//提取所有的 create table 的表格name
const tableNames = pgSql.match(/CREATE TABLE `([^`]*)`/g);
if (tableNames && tableNames.length > 0) {
@@ -88,21 +87,19 @@ CREATE TABLE `cd_audit_log`
*/
//提取表名
const tableName = item.match(/`([^`]*)`/)[1];
- pgSql += `\nALTER TABLE \`${tableName}\` ENGINE = InnoDB;`
+ pgSql += `\nALTER TABLE \`${tableName}\` ENGINE = InnoDB;`;
}
}
-
-
fs.writeFileSync(`./migration-mysql/${notFile}`, pgSql);
}
if (notFiles.length > 0) {
- console.log('sqlite->mysql 转换完成');
+ console.log("sqlite->mysql 转换完成");
- throw new Error('sqlite->mysql 转换完成,有更新,需要测试mysql');
+ throw new Error("sqlite->mysql 转换完成,有更新,需要测试mysql");
} else {
- console.log('sql无需更新');
+ console.log("sql无需更新");
}
}
diff --git a/packages/ui/certd-server/export-plugin-yaml.js b/packages/ui/certd-server/export-plugin-yaml.js
index eeca20c7a..9b1f38254 100644
--- a/packages/ui/certd-server/export-plugin-yaml.js
+++ b/packages/ui/certd-server/export-plugin-yaml.js
@@ -4,17 +4,16 @@ import path, { join } from "path";
import fs from "fs";
import { pathToFileURL } from "node:url";
import * as yaml from "js-yaml";
-import { AbstractTaskPlugin, BaseAccess, BaseNotification} from "@certd/pipeline";
-import { BaseAddon} from "@certd/lib-server";
+import { AbstractTaskPlugin, BaseAccess, BaseNotification } from "@certd/pipeline";
+import { BaseAddon } from "@certd/lib-server";
import { dnsProviderRegistry } from "@certd/plugin-cert";
-import { pluginRegistry ,accessRegistry,notificationRegistry,pluginGroups} from "@certd/pipeline";
+import { pluginRegistry, accessRegistry, notificationRegistry, pluginGroups } from "@certd/pipeline";
function scanDir(dir) {
const files = fs.readdirSync(dir);
const result = [];
// 扫描目录及子目录
for (const file of files) {
-
const filePath = join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
@@ -26,111 +25,110 @@ function scanDir(dir) {
result.push(filePath);
}
}
- return result
+ return result;
}
export default async function loadModules(dir) {
const files = scanDir(dir);
- const modules = {}
+ const modules = {};
for (const file of files) {
- if(file === "dist/plugins/index.js" || file === "dist\\plugins\\index.js"){
- continue
+ if (file === "dist/plugins/index.js" || file === "dist\\plugins\\index.js") {
+ continue;
}
- const content = fs.readFileSync(file, 'utf8')
- if(content.includes(" abstract ")){
- continue
+ const content = fs.readFileSync(file, "utf8");
+ if (content.includes(" abstract ")) {
+ continue;
}
- const lines = content.split('\n')
- let allExport = true
+ const lines = content.split("\n");
+ let allExport = true;
for (let line of lines) {
- line = line.trim()
+ line = line.trim();
if (!line || line.startsWith("//")) {
- continue
+ continue;
}
- if(!line.startsWith("export ")){
- allExport = false
- break
+ if (!line.startsWith("export ")) {
+ allExport = false;
+ break;
}
}
if (allExport) {
- continue
+ continue;
}
try {
// 转换为 file:// URL(Windows 必需)
- const moduleUrl = pathToFileURL(file).href
- const module = await import(moduleUrl)
+ const moduleUrl = pathToFileURL(file).href;
+ const module = await import(moduleUrl);
// 如果模块有默认导出,优先使用
- modules[file] = module.default || module
+ modules[file] = module.default || module;
} catch (err) {
- console.error(`加载模块 ${file} 失败:`, err)
+ console.error(`加载模块 ${file} 失败:`, err);
}
}
return modules;
}
-function isPrototypeOf(value,cls){
- return cls.prototype.isPrototypeOf(value.prototype)
+function isPrototypeOf(value, cls) {
+ return cls.prototype.isPrototypeOf(value.prototype);
}
-async function genMetadata(){
- const modules = await loadModules('./dist/plugins');
+async function genMetadata() {
+ const modules = await loadModules("./dist/plugins");
fs.rmSync("./metadata", { recursive: true });
fs.mkdirSync("./metadata", { recursive: true });
for (const key in modules) {
- const module = modules[key]
- const entry = Object.entries(module)
- if (entry.length >1) {
- console.log(`[warning] 文件 ${key} 导出了 ${entry.length} 个对象: ${entry.map(([name, value]) => name).join(", ")}`)
+ const module = modules[key];
+ const entry = Object.entries(module);
+ if (entry.length > 1) {
+ console.log(`[warning] 文件 ${key} 导出了 ${entry.length} 个对象: ${entry.map(([name, value]) => name).join(", ")}`);
}
for (const [name, value] of entry) {
//如果有define属性
- if(value.define){
+ if (value.define) {
//那么就是插件
- let location = key.substring(4)
- location = location.substring(0, location.length - 3)
- location = location.replaceAll("\\","/")
- location += ".js"
- location = `${location}` // 从modules/plugin/plugin-service 加载 ../../plugins目录下的文件
+ let location = key.substring(4);
+ location = location.substring(0, location.length - 3);
+ location = location.replaceAll("\\", "/");
+ location += ".js";
+ location = `${location}`; // 从modules/plugin/plugin-service 加载 ../../plugins目录下的文件
const pluginDefine = {
- ...value.define
+ ...value.define,
+ };
+ let subType = "";
+ if (pluginDefine.accessType) {
+ pluginDefine.pluginType = "dnsProvider";
+ } else if (isPrototypeOf(value, AbstractTaskPlugin)) {
+ pluginDefine.pluginType = "deploy";
+ } else if (isPrototypeOf(value, BaseNotification)) {
+ pluginDefine.pluginType = "notification";
+ } else if (isPrototypeOf(value, BaseAccess)) {
+ pluginDefine.pluginType = "access";
+ } else if (isPrototypeOf(value, BaseAddon)) {
+ pluginDefine.pluginType = "addon";
+ subType = "_" + pluginDefine.addonType;
+ } else {
+ console.log(`[warning] 未知的插件类型:${pluginDefine.name}`);
}
- let subType = ""
- if(pluginDefine.accessType){
- pluginDefine.pluginType = "dnsProvider"
- }else if(isPrototypeOf(value,AbstractTaskPlugin)){
- pluginDefine.pluginType = "deploy"
- }else if(isPrototypeOf(value,BaseNotification)){
- pluginDefine.pluginType = "notification"
- }else if(isPrototypeOf(value,BaseAccess)){
- pluginDefine.pluginType = "access"
- }else if(isPrototypeOf(value,BaseAddon)){
- pluginDefine.pluginType = "addon"
- subType = "_"+pluginDefine.addonType
- }else{
- console.log(`[warning] 未知的插件类型:${pluginDefine.name}`)
- }
- pluginDefine.type = "builtIn"
-
- const filePath = path.join(`./metadata/${pluginDefine.pluginType}${subType}_${pluginDefine.name}.yaml`)
+ pluginDefine.type = "builtIn";
- pluginDefine.scriptFilePath = location
- console.log(location)
- const data = yaml.dump(pluginDefine)
- fs.writeFileSync(filePath,data ,'utf8')
+ const filePath = path.join(`./metadata/${pluginDefine.pluginType}${subType}_${pluginDefine.name}.yaml`);
+
+ pluginDefine.scriptFilePath = location;
+ console.log(location);
+ const data = yaml.dump(pluginDefine);
+ fs.writeFileSync(filePath, data, "utf8");
}
}
}
}
-
async function genPluginMd() {
const plugins = {
access: [],
deploy: [],
dnsProvider: [],
- notification: []
+ notification: [],
};
plugins.access = accessRegistry.getDefineList();
@@ -138,24 +136,23 @@ async function genPluginMd() {
plugins.dnsProvider = dnsProviderRegistry.getDefineList();
plugins.notification = notificationRegistry.getDefineList();
-
-// function genMd(list) {
-// let mdContent = `
-//
-//
-// | 序号 | 名称 | 说明 |
-//
-//
-//
-// `;
-// let i = 0;
-// for (const x of list) {
-// i++
-// mdContent += ` | ${i}. | ${x.title} | ${x.desc||''} |
`;
-// }
-// mdContent += `
`;
-// return mdContent;
-// }
+ // function genMd(list) {
+ // let mdContent = `
+ //
+ //
+ // | 序号 | 名称 | 说明 |
+ //
+ //
+ //
+ // `;
+ // let i = 0;
+ // for (const x of list) {
+ // i++
+ // mdContent += ` | ${i}. | ${x.title} | ${x.desc||''} |
`;
+ // }
+ // mdContent += `
`;
+ // return mdContent;
+ // }
// function genMd(list) {
// let mdContent = ``;
@@ -174,14 +171,14 @@ async function genPluginMd() {
`;
let i = 0;
for (const x of list) {
- i++
- const desc = x.desc||''
- mdContent += `| ${i}.| **${x.title}** | ${desc.replaceAll("\n"," ")} | \n`;
+ i++;
+ const desc = x.desc || "";
+ mdContent += `| ${i}.| **${x.title}** | ${desc.replaceAll("\n", " ")} | \n`;
}
return mdContent;
}
- function addTableStyle(){
+ function addTableStyle() {
return `
- `
+ `;
}
let mdContent = "";
mdContent = "# 授权列表\n";
mdContent += genMd(plugins.access);
- mdContent += addTableStyle()
+ mdContent += addTableStyle();
fs.writeFileSync("../../../docs/guide/plugins/access.md", mdContent);
mdContent = "# DNS提供商\n";
mdContent += genMd(plugins.dnsProvider);
- mdContent += addTableStyle()
+ mdContent += addTableStyle();
fs.writeFileSync("../../../docs/guide/plugins/dns-provider.md", mdContent);
-
mdContent = "# 通知插件\n";
mdContent += genMd(plugins.notification);
- mdContent += addTableStyle()
+ mdContent += addTableStyle();
fs.writeFileSync("../../../docs/guide/plugins/notification.md", mdContent);
-
mdContent = "# 任务插件\n";
- mdContent += `共 \`${plugins.deploy.length}\` 款任务插件 \n`
- let index =0
+ mdContent += `共 \`${plugins.deploy.length}\` 款任务插件 \n`;
+ let index = 0;
for (const key in pluginGroups) {
- index++
+ index++;
const group = pluginGroups[key];
mdContent += `## ${index}. ${group.title}\n`;
mdContent += genMd(group.plugins);
}
- mdContent += addTableStyle()
+ mdContent += addTableStyle();
fs.writeFileSync("../../../docs/guide/plugins/deploy.md", mdContent);
-
}
-
-
// import why from 'why-is-node-running'
// setTimeout(() => why(), 100); // 延迟打印原因
-async function main(){
- await genMetadata()
- console.log("genMetadata success")
+async function main() {
+ await genMetadata();
+ console.log("genMetadata success");
// 获取args genmd
- const args = process.argv.slice(2)
- if(!args.includes("docoff")){
- await genPluginMd()
- console.log("genPluginMd success")
+ const args = process.argv.slice(2);
+ if (!args.includes("docoff")) {
+ await genPluginMd();
+ console.log("genPluginMd success");
}
- process.exit()
+ process.exit();
}
-
-main()
-
+main();
diff --git a/packages/ui/certd-server/jest.config.js b/packages/ui/certd-server/jest.config.js
index c5bd388a7..b118c449c 100644
--- a/packages/ui/certd-server/jest.config.js
+++ b/packages/ui/certd-server/jest.config.js
@@ -1,6 +1,6 @@
module.exports = {
- preset: 'ts-jest',
- testEnvironment: 'node',
- testPathIgnorePatterns: ['/test/fixtures'],
- coveragePathIgnorePatterns: ['/test/'],
-};
\ No newline at end of file
+ preset: "ts-jest",
+ testEnvironment: "node",
+ testPathIgnorePatterns: ["/test/fixtures"],
+ coveragePathIgnorePatterns: ["/test/"],
+};
diff --git a/packages/ui/certd-server/src/config/config.default.ts b/packages/ui/certd-server/src/config/config.default.ts
index c75db5614..192a42b3c 100644
--- a/packages/ui/certd-server/src/config/config.default.ts
+++ b/packages/ui/certd-server/src/config/config.default.ts
@@ -1,32 +1,32 @@
-import { MidwayConfig } from '@midwayjs/core';
+import { MidwayConfig } from "@midwayjs/core";
// import { join } from 'path';
// import { dirname } from 'node:path';
// import { fileURLToPath } from 'node:url';
// // const __filename = fileURLToPath(import.meta.url);
// const __dirname = dirname(fileURLToPath(import.meta.url));
-import { FlywayHistory, setFlywayLogger } from '@certd/midway-flyway-js';
-import { UserEntity } from '../modules/sys/authority/entity/user.js';
-import { PipelineEntity } from '../modules/pipeline/entity/pipeline.js';
+import { FlywayHistory, setFlywayLogger } from "@certd/midway-flyway-js";
+import { UserEntity } from "../modules/sys/authority/entity/user.js";
+import { PipelineEntity } from "../modules/pipeline/entity/pipeline.js";
//import { logger } from '../utils/logger';
// load .env file in process.cwd
-import { loadDotEnv, mergeConfig } from './loader.js';
-import { libServerEntities } from '@certd/lib-server';
-import { commercialEntities } from '@certd/commercial-core';
-import { tmpdir } from 'node:os';
-import { DefaultUploadFileMimeType, uploadWhiteList } from '@midwayjs/upload';
-import path from 'path';
-import { logger } from '@certd/basic';
+import { loadDotEnv, mergeConfig } from "./loader.js";
+import { libServerEntities } from "@certd/lib-server";
+import { commercialEntities } from "@certd/commercial-core";
+import { tmpdir } from "node:os";
+import { DefaultUploadFileMimeType, uploadWhiteList } from "@midwayjs/upload";
+import path from "path";
+import { logger } from "@certd/basic";
-const env = process.env.NODE_ENV || 'development';
+const env = process.env.NODE_ENV || "development";
const development = {
midwayLogger: {
default: {
- dir: './logs',
+ dir: "./logs",
},
// ...
},
- keys: 'certd',
+ keys: "certd",
koa: {
hostname: "::",
port: 7001,
@@ -34,8 +34,8 @@ const development = {
https: {
enabled: true,
port: 7002,
- key: './data/ssl/cert.key',
- cert: './data/ssl/cert.crt',
+ key: "./data/ssl/cert.key",
+ cert: "./data/ssl/cert.crt",
},
staticFile: {
usePrecompiledGzip: true,
@@ -44,11 +44,11 @@ const development = {
gzip: true,
dirs: {
default: {
- prefix: '/',
- dir: 'public',
+ prefix: "/",
+ dir: "public",
alias: {
- '/': '/index.html',
- '\\': '/index.html',
+ "/": "/index.html",
+ "\\": "/index.html",
},
maxFiles: 200,
},
@@ -77,14 +77,14 @@ const development = {
/**
* 单数据库实例
*/
- type: 'better-sqlite3',
- database: './data/db.sqlite',
+ type: "better-sqlite3",
+ database: "./data/db.sqlite",
synchronize: false, // 如果第一次使用,不存在表,有同步的需求可以写 true
logging: false,
highlightSql: false,
// 配置实体模型 或者 entities: '/entity',
- entities: ['**/modules/**/entity/*.js', ...libServerEntities, ...commercialEntities, PipelineEntity, FlywayHistory, UserEntity],
+ entities: ["**/modules/**/entity/*.js", ...libServerEntities, ...commercialEntities, PipelineEntity, FlywayHistory, UserEntity],
},
},
},
@@ -92,7 +92,7 @@ const development = {
* 自动升级数据库脚本
*/
flyway: {
- scriptDir: './db/migration',
+ scriptDir: "./db/migration",
},
auth: {
@@ -101,24 +101,24 @@ const development = {
},
},
certd: {
- fileRootDir: './data/files',
+ fileRootDir: "./data/files",
},
system: {
resetAdminPasswd: false,
},
plus: {
- serverBaseUrls: ['http://127.0.0.1:11007'],
+ serverBaseUrls: ["http://127.0.0.1:11007"],
},
upload: {
// mode: UploadMode, 默认为file,即上传到服务器临时目录,可以配置为 stream
- mode: 'file',
+ mode: "file",
// fileSize: string, 最大上传文件大小,默认为 10mb
- fileSize: '10mb',
+ fileSize: "10mb",
whitelist: uploadWhiteList, //文件扩展名白名单
mimeTypeWhiteList: DefaultUploadFileMimeType, //文件MIME类型白名单
// whitelist: uploadWhiteList.filter(ext => ext !== '.pdf'),
// tmpdir: string,上传的文件临时存储路径
- tmpdir: path.join(tmpdir(), 'certd-upload-files'),
+ tmpdir: path.join(tmpdir(), "certd-upload-files"),
// cleanTimeout: number,上传的文件在临时目录中多久之后自动删除,默认为 5 分钟
cleanTimeout: 5 * 60 * 1000,
// base64: boolean,设置原始body是否是base64格式,默认为false,一般用于腾讯云的兼容
@@ -128,113 +128,113 @@ const development = {
},
agent: {
enabled: false,
- contactText: '',
- contactLink: '',
+ contactText: "",
+ contactLink: "",
},
swagger: {
isGenerateTagForController: false,
routerFilter: (url: string) => {
- return url.startsWith('/api/sys');
+ return url.startsWith("/api/sys");
},
tags: [
{
- name: 'addon',
- description: '插件管理'
+ name: "addon",
+ description: "插件管理",
},
{
- name: 'basic-group',
- description: '基础分组管理'
+ name: "basic-group",
+ description: "基础分组管理",
},
{
- name: 'basic-user',
- description: '基础用户管理'
+ name: "basic-user",
+ description: "基础用户管理",
},
{
- name: 'cert',
- description: '证书管理'
+ name: "cert",
+ description: "证书管理",
},
{
- name: 'pipeline-cname',
- description: 'CNAME配置管理'
+ name: "pipeline-cname",
+ description: "CNAME配置管理",
},
{
- name: 'dashboard',
- description: '仪表板统计'
+ name: "dashboard",
+ description: "仪表板统计",
},
{
- name: 'enterprise-project',
- description: '企业项目管理'
+ name: "enterprise-project",
+ description: "企业项目管理",
},
{
- name: 'enterprise-project-member',
- description: '企业项目成员管理'
+ name: "enterprise-project-member",
+ description: "企业项目成员管理",
},
{
- name: 'mine',
- description: '个人中心'
+ name: "mine",
+ description: "个人中心",
},
{
- name: 'monitor',
- description: '监控管理'
+ name: "monitor",
+ description: "监控管理",
},
{
- name: 'open',
- description: '开放API KEY管理'
+ name: "open",
+ description: "开放API KEY管理",
},
{
- name: 'pipeline-access',
- description: '流水线授权配置'
+ name: "pipeline-access",
+ description: "流水线授权配置",
},
{
- name: 'pipeline-cert',
- description: '流水线证书'
+ name: "pipeline-cert",
+ description: "流水线证书",
},
{
- name: 'pipeline-dns-provider',
- description: '流水线DNS提供商'
+ name: "pipeline-dns-provider",
+ description: "流水线DNS提供商",
},
{
- name: 'pipeline-handle',
- description: '插件请求处理'
+ name: "pipeline-handle",
+ description: "插件请求处理",
},
{
- name: 'pipeline-history',
- description: '流水线执行历史'
+ name: "pipeline-history",
+ description: "流水线执行历史",
},
{
- name: 'pipeline-notification',
- description: '流水线通知配置'
+ name: "pipeline-notification",
+ description: "流水线通知配置",
},
{
- name: 'pipeline-plugin',
- description: '流水线插件'
+ name: "pipeline-plugin",
+ description: "流水线插件",
},
{
- name: 'pipeline-subdomain',
- description: '流水线子域名'
+ name: "pipeline-subdomain",
+ description: "流水线子域名",
},
{
- name: 'pipeline-template',
- description: '流水线模版'
+ name: "pipeline-template",
+ description: "流水线模版",
},
{
- name: 'pipeline-group',
- description: '流水线分组'
+ name: "pipeline-group",
+ description: "流水线分组",
},
{
- name: 'pipeline',
- description: '流水线管理'
+ name: "pipeline",
+ description: "流水线管理",
},
{
- name: 'openapi',
- description: '开放API'
+ name: "openapi",
+ description: "开放API",
},
- ]
- }
+ ],
+ },
} as MidwayConfig;
loadDotEnv();
-mergeConfig(development, 'development');
+mergeConfig(development, "development");
mergeConfig(development, env);
diff --git a/packages/ui/certd-server/src/config/loader.ts b/packages/ui/certd-server/src/config/loader.ts
index 97052b09b..915b1f7a4 100644
--- a/packages/ui/certd-server/src/config/loader.ts
+++ b/packages/ui/certd-server/src/config/loader.ts
@@ -1,25 +1,25 @@
-import path from 'path';
-import * as _ from 'lodash-es';
-import yaml from 'js-yaml';
-import fs from 'fs';
-import { logger } from '@certd/basic';
+import path from "path";
+import * as _ from "lodash-es";
+import yaml from "js-yaml";
+import fs from "fs";
+import { logger } from "@certd/basic";
function parseEnv(defaultConfig: any) {
const config = {};
for (const key in process.env) {
let keyName = key;
- if (!keyName.startsWith('certd_')) {
+ if (!keyName.startsWith("certd_")) {
continue;
}
- keyName = keyName.replace('certd_', '');
- const configKey = keyName.replaceAll('_', '.');
+ keyName = keyName.replace("certd_", "");
+ const configKey = keyName.replaceAll("_", ".");
const oldValue = _.get(defaultConfig, configKey);
let value: any = process.env[key];
- if (typeof oldValue === 'boolean') {
- value = value === 'true';
+ if (typeof oldValue === "boolean") {
+ value = value === "true";
} else if (Number.isInteger(oldValue)) {
value = parseInt(value, 10);
- } else if (typeof oldValue === 'number') {
+ } else if (typeof oldValue === "number") {
value = parseFloat(value);
}
_.set(config, configKey, value);
@@ -27,12 +27,12 @@ function parseEnv(defaultConfig: any) {
return config;
}
-export function load(config, env = '') {
+export function load(config, env = "") {
// Get document, or throw exception on error
- logger.info('load config', env);
+ logger.info("load config", env);
const yamlPath = path.join(process.cwd(), `.env.${env}.yaml`);
if (fs.existsSync(yamlPath)) {
- const doc = yaml.load(fs.readFileSync(yamlPath, 'utf8'));
+ const doc = yaml.load(fs.readFileSync(yamlPath, "utf8"));
return _.merge(doc, parseEnv(config));
}
return parseEnv(config);
@@ -40,7 +40,7 @@ export function load(config, env = '') {
export function mergeConfig(config: any, envType: string) {
_.merge(config, load(config, envType));
- const keys = _.get(config, 'auth.jwt.secret');
+ const keys = _.get(config, "auth.jwt.secret");
if (keys) {
config.keys = keys;
}
@@ -48,9 +48,9 @@ export function mergeConfig(config: any, envType: string) {
}
export function loadDotEnv() {
- const envStr = fs.readFileSync('.env').toString();
- envStr.split('\n').forEach(line => {
- const [key, value] = line.trim().split('=');
+ const envStr = fs.readFileSync(".env").toString();
+ envStr.split("\n").forEach(line => {
+ const [key, value] = line.trim().split("=");
const oldValue = process.env[key];
if (!oldValue) {
process.env[key] = value;
diff --git a/packages/ui/certd-server/src/configuration-cache.ts b/packages/ui/certd-server/src/configuration-cache.ts
index 7788bd7a8..e447213ad 100644
--- a/packages/ui/certd-server/src/configuration-cache.ts
+++ b/packages/ui/certd-server/src/configuration-cache.ts
@@ -1,5 +1,5 @@
export function shouldSetDefaultNoCache(path: string, cacheControl?: string) {
- if(path === '/' || path === '/index.html' ){
+ if (path === "/" || path === "/index.html") {
//首页不管怎样都不要缓存
return true;
}
@@ -7,5 +7,5 @@ export function shouldSetDefaultNoCache(path: string, cacheControl?: string) {
return false;
}
// api也不要缓存,如果他本身有设置缓存除外
- return path.startsWith('/api');
+ return path.startsWith("/api");
}
diff --git a/packages/ui/certd-server/src/configuration.test.ts b/packages/ui/certd-server/src/configuration.test.ts
index cc9147e33..40785ca41 100644
--- a/packages/ui/certd-server/src/configuration.test.ts
+++ b/packages/ui/certd-server/src/configuration.test.ts
@@ -14,8 +14,8 @@ describe("shouldSetDefaultNoCache", () => {
it("keeps explicit cache headers from file responses", () => {
assert.equal(shouldSetDefaultNoCache("/", "public,max-age=259200"), true);
- assert.equal(shouldSetDefaultNoCache("/index.html", "public,max-age=259200"), true);
- assert.equal(shouldSetDefaultNoCache("/api/basic/file/download", "public,max-age=259200"), false);
+ assert.equal(shouldSetDefaultNoCache("/index.html", "public,max-age=259200"), true);
+ assert.equal(shouldSetDefaultNoCache("/api/basic/file/download", "public,max-age=259200"), false);
});
it("ignores non-html and non-api paths", () => {
diff --git a/packages/ui/certd-server/src/configuration.ts b/packages/ui/certd-server/src/configuration.ts
index 86fd259eb..8eaaef70c 100644
--- a/packages/ui/certd-server/src/configuration.ts
+++ b/packages/ui/certd-server/src/configuration.ts
@@ -1,33 +1,33 @@
-import { App, Configuration } from '@midwayjs/core';
-import * as koa from '@midwayjs/koa';
-import { IMidwayKoaContext, NextFunction } from '@midwayjs/koa';
-import * as orm from '@midwayjs/typeorm';
-import * as cache from '@midwayjs/cache';
-import * as validate from '@midwayjs/validate';
-import * as info from '@midwayjs/info';
-import * as staticFile from '@midwayjs/static-file';
-import * as cron from './modules/cron/index.js';
-import * as flyway from '@certd/midway-flyway-js';
-import cors from '@koa/cors';
-import { GlobalExceptionMiddleware } from './middleware/global-exception.js';
-import { PreviewMiddleware } from './middleware/preview.js';
-import { AuthorityMiddleware } from './middleware/authority.js';
-import { logger } from '@certd/basic';
-import { ResetPasswdMiddleware } from './middleware/reset-passwd/middleware.js';
-import DefaultConfig from './config/config.default.js';
-import * as libServer from '@certd/lib-server';
-import * as commercial from '@certd/commercial-core';
-import * as upload from '@midwayjs/upload';
-import { setLogger } from '@certd/acme-client';
-import {HiddenMiddleware} from "./middleware/hidden.js";
-import { shouldSetDefaultNoCache } from './configuration-cache.js';
+import { App, Configuration } from "@midwayjs/core";
+import * as koa from "@midwayjs/koa";
+import { IMidwayKoaContext, NextFunction } from "@midwayjs/koa";
+import * as orm from "@midwayjs/typeorm";
+import * as cache from "@midwayjs/cache";
+import * as validate from "@midwayjs/validate";
+import * as info from "@midwayjs/info";
+import * as staticFile from "@midwayjs/static-file";
+import * as cron from "./modules/cron/index.js";
+import * as flyway from "@certd/midway-flyway-js";
+import cors from "@koa/cors";
+import { GlobalExceptionMiddleware } from "./middleware/global-exception.js";
+import { PreviewMiddleware } from "./middleware/preview.js";
+import { AuthorityMiddleware } from "./middleware/authority.js";
+import { logger } from "@certd/basic";
+import { ResetPasswdMiddleware } from "./middleware/reset-passwd/middleware.js";
+import DefaultConfig from "./config/config.default.js";
+import * as libServer from "@certd/lib-server";
+import * as commercial from "@certd/commercial-core";
+import * as upload from "@midwayjs/upload";
+import { setLogger } from "@certd/acme-client";
+import { HiddenMiddleware } from "./middleware/hidden.js";
+import { shouldSetDefaultNoCache } from "./configuration-cache.js";
// import * as swagger from '@midwayjs/swagger';
//@ts-ignore
// process.env.UV_THREADPOOL_SIZE = 2
-process.on('uncaughtException', error => {
- console.error('未捕获的异常:', error);
+process.on("uncaughtException", error => {
+ console.error("未捕获的异常:", error);
// 在这里可以添加日志记录、发送错误通知等操作
- if(error?.message?.includes('address family not supported')){
+ if (error?.message?.includes("address family not supported")) {
logger.error("您的服务器不支持监听IPV6格式的地址(::),请配置环境变量: certd_koa_hostname=0.0.0.0");
}
});
@@ -48,9 +48,7 @@ process.on('uncaughtException', error => {
@Configuration({
detectorOptions: {
- ignore: [
- '**/plugins/**'
- ]
+ ignore: ["**/plugins/**"],
},
imports: [
koa,
@@ -69,7 +67,7 @@ process.on('uncaughtException', error => {
// },
{
component: info,
- enabledEnvironment: ['local'],
+ enabledEnvironment: ["local"],
},
],
importConfigs: [
@@ -79,13 +77,12 @@ process.on('uncaughtException', error => {
],
})
export class MainConfiguration {
- @App('koa')
+ @App("koa")
app: koa.Application;
async onReady() {
// 设置flyway logger
-
// add middleware
// this.app.useMiddleware([ReportMiddleware]);
// add filter
@@ -93,7 +90,7 @@ export class MainConfiguration {
//跨域
this.app.use(
cors({
- origin: '*',
+ origin: "*",
})
);
//
@@ -126,8 +123,8 @@ export class MainConfiguration {
await next();
const path = ctx.path;
// 如果是首页则强制设置为不缓存
- if (shouldSetDefaultNoCache(path, ctx.response.get('Cache-Control')) ) {
- ctx.response.set('Cache-Control', 'public,max-age=0');
+ if (shouldSetDefaultNoCache(path, ctx.response.get("Cache-Control"))) {
+ ctx.response.set("Cache-Control", "public,max-age=0");
}
});
@@ -136,6 +133,6 @@ export class MainConfiguration {
logger.info(text);
});
- logger.info('当前环境:', this.app.getEnv()); // prod
+ logger.info("当前环境:", this.app.getEnv()); // prod
}
}
diff --git a/packages/ui/certd-server/src/controller/basic/app-controller.ts b/packages/ui/certd-server/src/controller/basic/app-controller.ts
index cf8aaf93a..6b79ecea4 100644
--- a/packages/ui/certd-server/src/controller/basic/app-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/app-controller.ts
@@ -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 {
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);
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");
}
}
diff --git a/packages/ui/certd-server/src/controller/basic/code-controller.ts b/packages/ui/certd-server/src/controller/basic/code-controller.ts
index 6ac3ade59..8025cf3c2 100644
--- a/packages/ui/certd-server/src/controller/basic/code-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/code-controller.ts
@@ -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);
}
-
}
diff --git a/packages/ui/certd-server/src/controller/basic/file-controller.ts b/packages/ui/certd-server/src/controller/basic/file-controller.ts
index 47ffe94fd..566824964 100644
--- a/packages/ui/certd-server/src/controller/basic/file-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/file-controller.ts
@@ -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[], @Fields() fields: any, @Query('autoSave') autoSave: string) {
- console.log('files', files, fields);
+ @Post("/upload", { description: Constants.per.authOnly })
+ async upload(@Files() files: UploadFileInfo[], @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);
diff --git a/packages/ui/certd-server/src/controller/basic/health-controller.ts b/packages/ui/certd-server/src/controller/basic/health-controller.ts
index 11aabee79..4b290c81b 100644
--- a/packages/ui/certd-server/src/controller/basic/health-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/health-controller.ts
@@ -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 {
- return this.ok('ok')
+ return this.ok("ok");
}
- @Get('/readiness', { description: Constants.per.guest })
+ @Get("/readiness", { description: Constants.per.guest })
async readiness(): Promise {
- return this.ok('ok')
+ return this.ok("ok");
}
-
}
diff --git a/packages/ui/certd-server/src/controller/basic/home-controller.ts b/packages/ui/certd-server/src/controller/basic/home-controller.ts
index 99f619264..02786a540 100644
--- a/packages/ui/certd-server/src/controller/basic/home-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/home-controller.ts
@@ -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 {
- logger.info('当前环境:', this.environmentService.getCurrentEnvironment()); // prod
- return 'Hello Midwayjs!';
+ logger.info("当前环境:", this.environmentService.getCurrentEnvironment()); // prod
+ return "Hello Midwayjs!";
}
}
diff --git a/packages/ui/certd-server/src/controller/basic/login/forgot-password-controller.ts b/packages/ui/certd-server/src/controller/basic/login/forgot-password-controller.ts
index 8ad6f42de..25b3c520d 100644
--- a/packages/ui/certd-server/src/controller/basic/login/forgot-password-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/login/forgot-password-controller.ts
@@ -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();
}
}
diff --git a/packages/ui/certd-server/src/controller/basic/login/login-controller.ts b/packages/ui/certd-server/src/controller/basic/login/login-controller.ts
index db5969b8f..a80eeb036 100644
--- a/packages/ui/certd-server/src/controller/basic/login/login-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/login/login-controller.ts
@@ -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);
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();
}
diff --git a/packages/ui/certd-server/src/controller/basic/login/oauth-controller.ts b/packages/ui/certd-server/src/controller/basic/login/oauth-controller.ts
index f312a1847..0882fedec 100644
--- a/packages/ui/certd-server/src/controller/basic/login/oauth-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/login/oauth-controller.ts
@@ -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);
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) {
-
- checkPlus()
+ @Get("/callback/:type", { description: Constants.per.guest })
+ public async callback(@Param("type") type: string, @Query() query: Record) {
+ checkPlus();
//处理登录回调
const oauthProvider = await this.getOauthProvider(type);
@@ -133,13 +127,13 @@ export class ConnectController extends BaseController {
const installInfo = await this.sysSettingsService.getSetting(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;
}
}
diff --git a/packages/ui/certd-server/src/controller/basic/login/register-controller.ts b/packages/ui/certd-server/src/controller/basic/login/register-controller.ts
index 063c55dbb..586f9c308 100644
--- a/packages/ui/certd-server/src/controller/basic/login/register-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/login/register-controller.ts
@@ -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({
diff --git a/packages/ui/certd-server/src/controller/basic/root-controller.ts b/packages/ui/certd-server/src/controller/basic/root-controller.ts
index cda4f3806..200a73114 100644
--- a/packages/ui/certd-server/src/controller/basic/root-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/root-controller.ts
@@ -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 {
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: /";
}
}
}
diff --git a/packages/ui/certd-server/src/controller/basic/settings-controller.ts b/packages/ui/certd-server/src/controller/basic/settings-controller.ts
index 3984919ce..ebee0ecb4 100644
--- a/packages/ui/certd-server/src/controller/basic/settings-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/settings-controller.ts
@@ -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);
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,
},
});
}
diff --git a/packages/ui/certd-server/src/controller/basic/unhidden-controller.ts b/packages/ui/certd-server/src/controller/basic/unhidden-controller.ts
index dae436072..2ebdd9126 100644
--- a/packages/ui/certd-server/src/controller/basic/unhidden-controller.ts
+++ b/packages/ui/certd-server/src/controller/basic/unhidden-controller.ts
@@ -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 = `
@@ -19,48 +19,47 @@ const unhiddenHtml = `