Compare commits

...

5 Commits

Author SHA1 Message Date
meilin.huang
12f8cf0111 feat: 资源密码加密处理&登录密码加密加强等 2022-08-02 21:44:01 +08:00
meilin.huang
daa2ef5203 feat: 数据库支持选中数据生成insert语句 2022-07-27 15:36:56 +08:00
meilin.huang
1e3e183930 feat: 优化机器脚本添加参数的前端交互 2022-07-26 18:32:45 +08:00
meilin.huang
366563a0fe fix: sql文件字段名调整 2022-07-24 18:54:23 +08:00
meilin.huang
577802e5ad fix: 定时任务问题修复 2022-07-24 15:37:13 +08:00
47 changed files with 590 additions and 162 deletions

View File

@@ -13,7 +13,7 @@
"countup.js": "^2.0.7",
"cropperjs": "^1.5.11",
"echarts": "^5.3.3",
"element-plus": "^2.2.10",
"element-plus": "^2.2.12",
"jsencrypt": "^3.2.1",
"jsoneditor": "^9.9.0",
"lodash": "^4.17.21",
@@ -21,7 +21,7 @@
"nprogress": "^0.2.0",
"screenfull": "^5.1.0",
"sortablejs": "^1.13.0",
"sql-formatter": "^7.0.3",
"sql-formatter": "^8.2.0",
"vue": "^3.2.37",
"vue-clipboard3": "^1.0.1",
"vue-router": "^4.1.2",

View File

@@ -41,7 +41,15 @@
v-model.trim="form.password"
placeholder="请输入密码,修改操作可不填"
autocomplete="new-password"
></el-input>
>
<template v-if="form.id && form.id != 0" #suffix>
<el-popover @hide="pwd = ''" placement="right" title="原密码" :width="200" trigger="click" :content="pwd">
<template #reference>
<el-link @click="getDbPwd" :underline="false" type="primary" class="mr5">原密码</el-link>
</template>
</el-popover>
</template>
</el-input>
</el-form-item>
<el-form-item prop="params" label="连接参数:">
<el-input v-model="form.params" placeholder="其他连接参数,形如: key1=value1&key2=value2"></el-input>
@@ -142,6 +150,8 @@ export default defineComponent({
enableSshTunnel: null,
sshTunnelMachineId: null,
},
// 原密码
pwd: '',
btnLoading: false,
rules: {
projectId: [
@@ -262,6 +272,10 @@ export default defineComponent({
state.allDatabases = await dbApi.getAllDatabase.request(reqForm);
};
const getDbPwd = async () => {
state.pwd = await dbApi.getDbPwd.request({ id: state.form.id });
};
const btnOk = async () => {
if (!state.form.id) {
notBlank(state.form.password, '新增操作,密码不可为空');
@@ -304,6 +318,7 @@ export default defineComponent({
...toRefs(state),
dbForm,
getAllDatabase,
getDbPwd,
changeDatabase,
getSshTunnelMachines,
changeProject,

View File

@@ -46,7 +46,7 @@
<el-table-column prop="username" label="用户名" min-width="100"></el-table-column>
<el-table-column min-width="115" prop="creator" label="创建账号"></el-table-column>
<el-table-column min-width="160" prop="createTime" label="创建时间">
<el-table-column min-width="160" prop="createTime" label="创建时间" show-overflow-tooltip>
<template #default="scope">
{{ $filters.dateFormat(scope.row.createTime) }}
</template>

View File

@@ -152,6 +152,10 @@
<el-tooltip class="box-item" effect="dark" content="commit" placement="top">
<el-link @click="onCommit" class="ml5" type="success" icon="check" :underline="false"></el-link>
</el-tooltip>
<el-tooltip class="box-item" effect="dark" content="生成insert sql" placement="top">
<el-link @click="onGenerateInsertSql" type="success" class="ml20" :underline="false">gi</el-link>
</el-tooltip>
</el-row>
<el-row class="mt5">
<el-input
@@ -161,9 +165,14 @@
size="small"
>
<template #prepend>
<el-popover trigger="click" :width="270" placement="right">
<el-popover v-model:visible="dt.selectColumnPopoverVisible" :width="320" placement="right">
<template #reference>
<el-link type="success" :underline="false">选择列</el-link>
<el-link
@click="dt.selectColumnPopoverVisible = !dt.selectColumnPopoverVisible"
type="success"
:underline="false"
>选择列</el-link
>
</template>
<el-table
:data="getColumns4Map(dt.name)"
@@ -174,6 +183,7 @@
onConditionRowClick(event, dt);
}
"
style="cursor: pointer"
>
<el-table-column property="columnName" label="列名" show-overflow-tooltip> </el-table-column>
<el-table-column property="columnComment" label="备注" show-overflow-tooltip> </el-table-column>
@@ -233,6 +243,34 @@
</el-tab-pane>
</el-tabs>
</el-container>
<el-dialog v-model="conditionDialog.visible" :title="conditionDialog.title" width="420px">
<el-row>
<el-col :span="5">
<el-select v-model="conditionDialog.condition">
<el-option label="=" value="="> </el-option>
<el-option label="LIKE" value="LIKE"> </el-option>
<el-option label=">" value=">"> </el-option>
<el-option label=">=" value=">="> </el-option>
<el-option label="<" value="<"> </el-option>
<el-option label="<=" value="<="> </el-option>
</el-select>
</el-col>
<el-col :span="19">
<el-input v-model="conditionDialog.value" :placeholder="conditionDialog.placeholder" />
</el-col>
</el-row>
<template #footer>
<span class="dialog-footer">
<el-button @click="onCancelCondition">取消</el-button>
<el-button type="primary" @click="onConfirmCondition">确定</el-button>
</span>
</template>
</el-dialog>
<el-dialog @close="genSqlDialog.visible = false" v-model="genSqlDialog.visible" title="SQL" width="1000px">
<el-input v-model="genSqlDialog.sql" type="textarea" rows="20" />
</el-dialog>
</div>
</template>
@@ -313,6 +351,20 @@ export default defineComponent({
left: '',
top: '',
},
selectColumnPopoverVisible: false,
conditionDialog: {
title: '',
placeholder: '',
columnRow: null,
dataTab: null,
visible: false,
condition: '=',
value: null,
},
genSqlDialog: {
visible: false,
sql: '',
},
cmOptions: {
tabSize: 4,
mode: 'text/x-sql',
@@ -677,6 +729,7 @@ export default defineComponent({
columnNames: [],
pageNum: 1,
count: 0,
selectColumnPopoverVisible: false,
};
tab.columnNames = await getColumnNames(tableName);
state.dataTabs[tableName] = tab;
@@ -716,24 +769,36 @@ export default defineComponent({
* 条件查询,点击列信息后显示输入对应的值
*/
const onConditionRowClick = (event: any, dataTab: any) => {
dataTab.selectColumnPopoverVisible = false;
const row = event[0];
ElMessageBox.prompt(`请输入 [${row.columnName}] 的值`, '查询条件', {
confirmButtonText: '确定',
cancelButtonText: '取消',
inputPlaceholder: `${row.columnType} ${row.columnComment}`,
})
.then(({ value }) => {
if (!value) {
value = '';
}
let condition = dataTab.condition;
if (condition) {
condition += ` AND `;
}
condition += `${row.columnName} = `;
dataTab.condition = condition + wrapColumnValue(row, value);
})
.catch(() => {});
state.conditionDialog.title = `请输入 [${row.columnName}] 的值`;
state.conditionDialog.placeholder = `${row.columnType} ${row.columnComment}`;
state.conditionDialog.columnRow = row;
state.conditionDialog.dataTab = dataTab;
state.conditionDialog.visible = true;
};
// 确认条件
const onConfirmCondition = () => {
const conditionDialog = state.conditionDialog;
const dataTab = state.conditionDialog.dataTab as any;
let condition = dataTab.condition;
if (condition) {
condition += ` AND `;
}
const row = conditionDialog.columnRow as any;
condition += `${row.columnName} ${conditionDialog.condition} `;
dataTab.condition = condition + wrapColumnValue(row, conditionDialog.value);
onCancelCondition();
};
const onCancelCondition = () => {
state.conditionDialog.visible = false;
state.conditionDialog.title = ``;
state.conditionDialog.placeholder = ``;
state.conditionDialog.value = null;
state.conditionDialog.columnRow = null;
state.conditionDialog.dataTab = null;
};
const onRefresh = async (tableName: string) => {
@@ -793,10 +858,10 @@ export default defineComponent({
const getDefaultSelectSql = (tableName: string, where: string = '', orderBy: string = '', pageNum: number = 1) => {
const baseSql = `SELECT * FROM ${tableName} ${where ? 'WHERE ' + where : ''} ${orderBy ? orderBy : ''}`;
if (state.dbType == 'mysql') {
return `${baseSql} LIMIT ${(pageNum - 1) * state.defalutLimit}, ${state.defalutLimit};`
return `${baseSql} LIMIT ${(pageNum - 1) * state.defalutLimit}, ${state.defalutLimit};`;
}
if (state.dbType == 'postgres') {
return `${baseSql} OFFSET ${(pageNum - 1) * state.defalutLimit} LIMIT ${state.defalutLimit};`
return `${baseSql} OFFSET ${(pageNum - 1) * state.defalutLimit} LIMIT ${state.defalutLimit};`;
}
return baseSql;
};
@@ -963,6 +1028,38 @@ export default defineComponent({
});
};
const onGenerateInsertSql = async () => {
const queryTab = isQueryTab();
const datas = queryTab ? state.queryTab.selectionDatas : state.dataTabs[state.activeName].selectionDatas;
isTrue(datas && datas.length > 0, '请先选择要生成insert语句的数据');
const tableName = state.nowTableName;
const columns: any = await getColumns(tableName);
const sqls = [];
for (let data of datas) {
let colNames = [];
let values = [];
for (let column of columns) {
const colName = column.columnName;
colNames.push(colName);
values.push(wrapValueByType(data[colName]));
}
sqls.push(`INSERT INTO ${tableName} (${colNames.join(', ')}) VALUES(${values.join(', ')})`);
}
state.genSqlDialog.sql = sqls.join(';\n') + ';';
state.genSqlDialog.visible = true;
};
const wrapValueByType = (val: any) => {
if (val == null) {
return 'NULL';
}
if (typeof val == 'number') {
return val;
}
return `'${val}'`;
};
/**
* 是否为查询tab
*/
@@ -1121,6 +1218,8 @@ export default defineComponent({
getColumnTip,
getColumns4Map,
onConditionRowClick,
onConfirmCondition,
onCancelCondition,
changeSqlTemplate,
deleteSql,
saveSql,
@@ -1137,6 +1236,7 @@ export default defineComponent({
onDataSelectionChange,
onDeleteData,
onTableSortChange,
onGenerateInsertSql,
showExecBtns,
closeExecBtns,
};

View File

@@ -5,6 +5,7 @@ export const dbApi = {
dbs: Api.create("/dbs", 'get'),
saveDb: Api.create("/dbs", 'post'),
getAllDatabase: Api.create("/dbs/databases", 'post'),
getDbPwd: Api.create("/dbs/{id}/pwd", 'get'),
deleteDb: Api.create("/dbs/{id}", 'delete'),
dumpDb: Api.create("/dbs/{id}/dump", 'post'),
tableInfos: Api.create("/dbs/{id}/t-infos", 'get'),

View File

@@ -57,7 +57,7 @@
</el-row>
</el-dialog>
<el-dialog :title="tree.title" v-model="tree.visible" :close-on-click-modal="false" width="680px">
<el-dialog :title="tree.title" v-model="tree.visible" :close-on-click-modal="false" width="50%">
<el-progress
v-if="uploadProgressShow"
style="width: 90%; margin-left: 20px"

View File

@@ -35,7 +35,15 @@
v-model.trim="form.password"
placeholder="请输入密码,修改操作可不填"
autocomplete="new-password"
></el-input>
>
<template v-if="form.id && form.id != 0" #suffix>
<el-popover @hide="pwd = ''" placement="right" title="原密码" :width="200" trigger="click" :content="pwd">
<template #reference>
<el-link @click="getPwd" :underline="false" type="primary" class="mr5">原密码</el-link>
</template>
</el-popover>
</template>
</el-input>
</el-form-item>
<el-form-item v-if="form.authMethod == 2" prop="password" label="秘钥:">
<el-input type="textarea" :rows="3" v-model="form.password" placeholder="请将私钥文件内容拷贝至此,修改操作可不填"></el-input>
@@ -115,6 +123,7 @@ export default defineComponent({
enableSshTunnel: null,
sshTunnelMachineId: null,
},
pwd: '',
btnLoading: false,
rules: {
projectId: [
@@ -187,6 +196,10 @@ export default defineComponent({
return state.sshTunnelMachineList.find((x: any) => x.id == machineId);
};
const getPwd = async () => {
state.pwd = await machineApi.getMachinePwd.request({ id: state.form.id });
};
const changeProject = (projectId: number) => {
for (let p of state.projects as any) {
if (p.id == projectId) {
@@ -238,6 +251,7 @@ export default defineComponent({
...toRefs(state),
machineForm,
getSshTunnelMachines,
getPwd,
changeProject,
btnOk,
cancel,

View File

@@ -42,7 +42,7 @@
</template>
</el-table-column>
<el-table-column prop="name" label="名称" min-width="140" show-overflow-tooltip></el-table-column>
<el-table-column prop="ip" label="ip:port" min-width="140">
<el-table-column prop="ip" label="ip:port" min-width="150">
<template #default="scope">
<el-link :disabled="scope.row.status == -1" @click="showMachineStats(scope.row)" type="primary" :underline="false">{{
`${scope.row.ip}:${scope.row.port}`

View File

@@ -9,7 +9,7 @@
:destroy-on-close="true"
width="800px"
>
<el-form :model="form" ref="mockDataForm" label-width="70px">
<el-form :model="form" ref="scriptForm" label-width="70px">
<el-form-item prop="method" label="名称">
<el-input v-model.trim="form.name" placeholder="请输入名称"></el-input>
</el-form-item>
@@ -24,8 +24,19 @@
</el-select>
</el-form-item>
<el-form-item prop="params" label="参数">
<el-input v-model="form.params" placeholder="参数数组json若无可不填"></el-input>
<el-row style="margin-left: 30px; margin-bottom: 5px">
<el-button @click="onAddParam" size="small" type="success">新增占位符参数</el-button>
</el-row>
<el-form-item :key="param" v-for="(param, index) in params" prop="params" :label="`参数${index + 1}`">
<el-row>
<el-col :span="6"><el-input v-model="param.model" placeholder="内容中用{{.model}}替换"></el-input></el-col>
<el-divider :span="1" direction="vertical" border-style="dashed" />
<el-col :span="6"><el-input v-model="param.name" placeholder="字段名"></el-input></el-col>
<el-divider :span="1" direction="vertical" border-style="dashed" />
<el-col :span="6"><el-input v-model="param.placeholder" placeholder="字段说明"></el-input></el-col>
<el-divider :span="1" direction="vertical" border-style="dashed" />
<el-col :span="3"><el-button @click="onDeleteParam(index)" size="small" type="danger">删除</el-button></el-col>
</el-row>
</el-form-item>
<el-form-item prop="script" label="内容" id="content">
@@ -84,41 +95,59 @@ export default defineComponent({
},
setup(props: any, { emit }) {
const { isCommon, machineId } = toRefs(props);
const mockDataForm: any = ref(null);
const scriptForm: any = ref(null);
const state = reactive({
dialogVisible: false,
submitDisabled: false,
params: [] as any,
form: {
id: null,
name: '',
machineId: 0,
description: '',
script: '',
params: null,
params: '',
type: null,
},
btnLoading: false,
});
watch(props, (newValue) => {
state.dialogVisible = newValue.visible;
if (!newValue.visible) {
return;
}
if (newValue.data) {
state.form = { ...newValue.data };
if (state.form.params) {
state.params = JSON.parse(state.form.params);
}
} else {
state.form = {} as any;
state.form.script = '';
}
state.dialogVisible = newValue.visible;
});
const onAddParam = () => {
state.params.push({ name: '', model: '', placeholder: '' });
};
const onDeleteParam = (idx: number) => {
state.params.splice(idx, 1);
};
const btnOk = () => {
state.form.machineId = isCommon.value ? 9999999 : (machineId.value as any);
console.log('machineid:', machineId);
mockDataForm.value.validate((valid: any) => {
scriptForm.value.validate((valid: any) => {
if (valid) {
notEmpty(state.form.name, '名称不能为空');
notEmpty(state.form.description, '描述不能为空');
notEmpty(state.form.script, '内容不能为空');
if (state.params) {
state.form.params = JSON.stringify(state.params);
}
machineApi.saveScript.request(state.form).then(
() => {
ElMessage.success('保存成功');
@@ -139,12 +168,15 @@ export default defineComponent({
const cancel = () => {
emit('update:visible', false);
emit('cancel');
state.params = [];
};
return {
...toRefs(state),
enums,
mockDataForm,
onAddParam,
onDeleteParam,
scriptForm,
btnOk,
cancel,
};

View File

@@ -196,8 +196,11 @@ export default defineComponent({
// 如果存在参数,则弹窗输入参数后执行
if (script.params) {
state.scriptParamsDialog.paramsFormItem = JSON.parse(script.params);
state.scriptParamsDialog.visible = true;
return;
console.log(state.scriptParamsDialog.paramsFormItem);
if (state.scriptParamsDialog.paramsFormItem && state.scriptParamsDialog.paramsFormItem.length > 0) {
state.scriptParamsDialog.visible = true;
return;
}
}
run(script);

View File

@@ -3,6 +3,7 @@ import Api from '@/common/Api';
export const machineApi = {
// 获取权限列表
list: Api.create("/machines", 'get'),
getMachinePwd: Api.create("/machines/{id}/pwd", 'get'),
info: Api.create("/machines/{id}/sysinfo", 'get'),
stats: Api.create("/machines/{id}/stats", 'get'),
process: Api.create("/machines/{id}/process", 'get'),

View File

@@ -61,7 +61,6 @@ import { mongoApi } from './api';
import { projectApi } from '../project/api.ts';
import { machineApi } from '../machine/api.ts';
import { ElMessage } from 'element-plus';
import { RsaEncrypt } from '@/common/rsa';
export default defineComponent({
name: 'MongoEdit',
@@ -181,7 +180,7 @@ export default defineComponent({
mongoForm.value.validate(async (valid: boolean) => {
if (valid) {
const reqForm = { ...state.form };
reqForm.uri = await RsaEncrypt(reqForm.uri);
// reqForm.uri = await RsaEncrypt(reqForm.uri);
mongoApi.saveMongo.request(reqForm).then(() => {
ElMessage.success('保存成功');
emit('val-change', state.form);

View File

@@ -34,7 +34,14 @@
v-model.trim="form.password"
placeholder="请输入密码, 修改操作可不填"
autocomplete="new-password"
></el-input>
><template v-if="form.id && form.id != 0" #suffix>
<el-popover @hide="pwd = ''" placement="right" title="原密码" :width="200" trigger="click" :content="pwd">
<template #reference>
<el-link @click="getPwd" :underline="false" type="primary" class="mr5">原密码</el-link>
</template>
</el-popover>
</template></el-input
>
</el-form-item>
<el-form-item prop="db" label="库号:" required>
<el-input v-model.number="form.db" placeholder="请输入库号"></el-input>
@@ -116,6 +123,7 @@ export default defineComponent({
enableSshTunnel: null,
sshTunnelMachineId: null,
},
pwd: '',
btnLoading: false,
rules: {
projectId: [
@@ -183,6 +191,10 @@ export default defineComponent({
state.envs = await projectApi.projectEnvs.request({ projectId });
};
const getPwd = async () => {
state.pwd = await redisApi.getRedisPwd.request({ id: state.form.id });
};
const changeProject = (projectId: number) => {
for (let p of state.projects as any) {
if (p.id == projectId) {
@@ -234,6 +246,7 @@ export default defineComponent({
...toRefs(state),
redisForm,
getSshTunnelMachines,
getPwd,
changeProject,
changeEnv,
btnOk,

View File

@@ -2,6 +2,7 @@ import Api from '@/common/Api';
export const redisApi = {
redisList : Api.create("/redis", 'get'),
getRedisPwd: Api.create("/redis/{id}/pwd", 'get'),
redisInfo: Api.create("/redis/{id}/info", 'get'),
clusterInfo: Api.create("/redis/{id}/cluster-info", 'get'),
saveRedis: Api.create("/redis", 'post'),

View File

@@ -633,10 +633,10 @@ echarts@^5.3.3:
tslib "2.3.0"
zrender "5.3.2"
element-plus@^2.2.10:
version "2.2.10"
resolved "https://registry.npmmirror.com/element-plus/-/element-plus-2.2.10.tgz#0b06a006b67b7ad3d5f071545a910782f9ba471b"
integrity sha512-hJ+LlbRN3POu4Idl1LXB+SHSWdi+wwmdsoDXdQT2ynGuwzZsMYiusOooYXyEsPlrizeLibdnNGNDx4TIjXQvUg==
element-plus@^2.2.12:
version "2.2.12"
resolved "https://registry.npmmirror.com/element-plus/-/element-plus-2.2.12.tgz#b6c4e298e02ba9b904d70daa54def27b2de8c43c"
integrity sha512-g/hIHj3b+dND2R3YRvyvCJtJhQvR7lWvXqhJaoxaQmajjNWedoe4rttxG26fOSv9YCC2wN4iFDcJHs70YFNgrA==
dependencies:
"@ctrl/tinycolor" "^3.4.1"
"@element-plus/icons-vue" "^2.0.6"
@@ -652,7 +652,7 @@ element-plus@^2.2.10:
lodash-es "^4.17.21"
lodash-unified "^1.0.2"
memoize-one "^6.0.0"
normalize-wheel-es "^1.1.2"
normalize-wheel-es "^1.2.0"
enquirer@^2.3.5:
version "2.3.6"
@@ -1351,10 +1351,10 @@ normalize-path@^3.0.0, normalize-path@~3.0.0:
resolved "https://registry.npm.taobao.org/normalize-path/download/normalize-path-3.0.0.tgz"
integrity sha1-Dc1p/yOhybEf0JeDFmRKA4ghamU=
normalize-wheel-es@^1.1.2:
version "1.1.2"
resolved "https://registry.npmmirror.com/normalize-wheel-es/-/normalize-wheel-es-1.1.2.tgz"
integrity sha512-scX83plWJXYH1J4+BhAuIHadROzxX0UBF3+HuZNY2Ks8BciE7tSTQ+5JhTsvzjaO0/EJdm4JBGrfObKxFf3Png==
normalize-wheel-es@^1.2.0:
version "1.2.0"
resolved "https://registry.npmmirror.com/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz#0fa2593d619f7245a541652619105ab076acf09e"
integrity sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==
nprogress@^0.2.0:
version "0.2.0"
@@ -1593,10 +1593,10 @@ sourcemap-codec@^1.4.4:
resolved "https://registry.npm.taobao.org/sourcemap-codec/download/sourcemap-codec-1.4.8.tgz"
integrity sha1-6oBL2UhXQC5pktBaOO8a41qatMQ=
sql-formatter@^7.0.3:
version "7.0.3"
resolved "https://registry.npmmirror.com/sql-formatter/-/sql-formatter-7.0.3.tgz"
integrity sha512-E9zotLB0dy9ZZhs1sY4ZqzSzJGF2uC4Vzj0mEzXJC9rlE+Jjmz6t64qT2dzm/IPQosYvZknDbBOrWkygIJz67A==
sql-formatter@^8.2.0:
version "8.2.0"
resolved "https://registry.npmmirror.com/sql-formatter/-/sql-formatter-8.2.0.tgz#2b664f02bb6b7bb6fcad1346e850b8f583303469"
integrity sha512-5hQOSOk8jfhPkNgUmpm+9Fn2aaLWcf4vKL/dIvUN5q9rsamKHSyN/gL79xpkETNOyL+Zv5BMQfA7z9Rmz/DJJg==
dependencies:
argparse "^2.0.1"

View File

@@ -25,10 +25,13 @@ server:
filepath: ./static/config.js
jwt:
key: mykey
# jwt key不设置默认使用随机字符串
key:
# 过期时间单位分钟
expire-time: 1440
# 资源密码aes加密key
aes:
key: 1111111111111111
mysql:
host: localhost:3306
username: root

View File

@@ -3,23 +3,23 @@ module mayfly-go
go 1.18
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible // jwt
github.com/gin-gonic/gin v1.8.1
github.com/go-redis/redis/v8 v8.11.5
github.com/go-sql-driver/mysql v1.6.0
github.com/golang-jwt/jwt/v4 v4.4.2
github.com/gorilla/websocket v1.5.0
github.com/lib/pq v1.10.6
github.com/mojocn/base64Captcha v1.3.5 //
github.com/pkg/sftp v1.13.5
github.com/robfig/cron/v3 v3.0.1 //
github.com/sirupsen/logrus v1.8.1
github.com/sirupsen/logrus v1.9.0
github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2
go.mongodb.org/mongo-driver v1.9.1 // mongo
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // ssh
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa // ssh
gopkg.in/yaml.v3 v3.0.1
// gorm
gorm.io/driver/mysql v1.3.4
gorm.io/gorm v1.23.5
gorm.io/driver/mysql v1.3.5
gorm.io/gorm v1.23.8
)
require (
@@ -34,7 +34,7 @@ require (
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.4 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/kr/fs v0.1.0 // indirect
@@ -52,7 +52,7 @@ require (
golang.org/x/image v0.0.0-20220302094943-723b81ca9867 // indirect
golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 // indirect
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 // indirect
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
google.golang.org/protobuf v1.28.0 // indirect

View File

@@ -0,0 +1,32 @@
package utils
import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/config"
)
// 使用config.yml的aes.key进行密码加密
func PwdAesEncrypt(password string) string {
if password == "" {
return ""
}
aes := config.Conf.Aes
if aes == nil {
return password
}
encryptPwd, err := aes.EncryptBase64([]byte(password))
biz.ErrIsNilAppendErr(err, "密码加密失败: %s")
return encryptPwd
}
// 使用config.yml的aes.key进行密码解密
func PwdAesDecrypt(encryptPwd string) string {
aes := config.Conf.Aes
if aes == nil {
return encryptPwd
}
decryptPwd, err := aes.DecryptBase64(encryptPwd)
biz.ErrIsNilAppendErr(err, "密码解密失败: %s")
// 解密后的密码
return string(decryptPwd)
}

View File

@@ -9,8 +9,8 @@ const (
MongoConnExpireTime = 30 * time.Minute
/**** 开发测试使用 ****/
// MachineConnExpireTime = 20 * time.Second
// DbConnExpireTime = 20 * time.Second
// RedisConnExpireTime = 20 * time.Second
// MongoConnExpireTime = 20 * time.Second
// MachineConnExpireTime = 4 * time.Minute
// DbConnExpireTime = 2 * time.Minute
// RedisConnExpireTime = 2 * time.Minute
// MongoConnExpireTime = 2 * time.Minute
)

View File

@@ -61,6 +61,14 @@ func (d *Db) Save(rc *ctx.ReqCtx) {
d.DbApp.Save(db)
}
// 获取数据库实例密码,由于数据库是加密存储,故提供该接口展示原文密码
func (d *Db) GetDbPwd(rc *ctx.ReqCtx) {
dbId := GetDbId(rc.GinCtx)
dbEntity := d.DbApp.GetById(dbId, "Password")
dbEntity.PwdDecrypt()
rc.ResData = dbEntity.Password
}
// 获取数据库实例的所有数据库名
func (d *Db) GetDatabaseNames(rc *ctx.ReqCtx) {
form := &form.DbForm{}

View File

@@ -72,6 +72,14 @@ func (m *Machine) SaveMachine(rc *ctx.ReqCtx) {
m.MachineApp.Save(me)
}
// 获取机器实例密码,由于数据库是加密存储,故提供该接口展示原文密码
func (m *Machine) GetMachinePwd(rc *ctx.ReqCtx) {
mid := GetMachineId(rc.GinCtx)
me := m.MachineApp.GetById(mid, "Password")
me.PwdDecrypt()
rc.ResData = me.Password
}
func (m *Machine) ChangeStatus(rc *ctx.ReqCtx) {
g := rc.GinCtx
id := uint64(ginx.PathParamInt(g, "machineId"))

View File

@@ -38,10 +38,6 @@ func (m *Mongo) Save(rc *ctx.ReqCtx) {
mongo := new(entity.Mongo)
utils.Copy(mongo, form)
// 解密uri并使用解密后的赋值
originUri, err := utils.DefaultRsaDecrypt(form.Uri, true)
biz.ErrIsNilAppendErr(err, "解密uri错误: %s")
mongo.Uri = originUri
mongo.SetBaseInfo(rc.LoginAccount)
m.MongoApp.Save(mongo)

View File

@@ -52,6 +52,14 @@ func (r *Redis) Save(rc *ctx.ReqCtx) {
r.RedisApp.Save(redis)
}
// 获取redis实例密码由于数据库是加密存储故提供该接口展示原文密码
func (r *Redis) GetRedisPwd(rc *ctx.ReqCtx) {
rid := uint64(ginx.PathParamInt(rc.GinCtx, "id"))
re := r.RedisApp.GetById(rid, "Password")
re.PwdDecrypt()
rc.ResData = re.Password
}
func (r *Redis) DeleteRedis(rc *ctx.ReqCtx) {
r.RedisApp.Delete(uint64(ginx.PathParamInt(rc.GinCtx, "id")))
}

View File

@@ -97,6 +97,7 @@ func (d *dbAppImpl) Save(dbEntity *entity.Db) {
if dbEntity.Id == 0 {
biz.NotEmpty(dbEntity.Password, "密码不能为空")
biz.IsTrue(err != nil, "该数据库实例已存在")
dbEntity.PwdEncrypt()
d.dbRepo.Insert(dbEntity)
return
}
@@ -129,6 +130,7 @@ func (d *dbAppImpl) Save(dbEntity *entity.Db) {
d.dbSqlRepo.DeleteBy(&entity.DbSql{DbId: dbId, Db: v.(string)})
}
dbEntity.PwdEncrypt()
d.dbRepo.Update(dbEntity)
}
@@ -180,10 +182,12 @@ func (da *dbAppImpl) GetDbInstance(id uint64, db string) *DbInstance {
return load.(*DbInstance)
}
}
biz.IsTrue(mutex.TryLock(), "有数据库实例在连接中...请稍后重试")
mutex.Lock()
defer mutex.Unlock()
d := da.GetById(id)
// 密码解密
d.PwdDecrypt()
biz.NotNil(d, "数据库信息不存在")
biz.IsTrue(strings.Contains(d.Database, db), "未配置该库的操作权限")
@@ -258,10 +262,9 @@ func GetDbConn(d *entity.Db, db string) (*sql.DB, error) {
// SSH Conect
if d.EnableSshTunnel == 1 && d.SshTunnelMachineId != 0 {
sshTunnelMachine := MachineApp.GetSshTunnelMachine(d.SshTunnelMachineId)
defer machine.CloseSshTunnelMachine(d.SshTunnelMachineId, 0)
if d.Type == entity.DbTypeMysql {
mysql.RegisterDialContext(d.Network, func(ctx context.Context, addr string) (net.Conn, error) {
return MachineApp.GetSshTunnelMachine(d.SshTunnelMachineId).GetDialConn("tcp", addr)
return sshTunnelMachine.GetDialConn("tcp", addr)
})
} else if d.Type == entity.DbTypePostgres {
_, err := pq.DialOpen(&PqSqlDialer{sshTunnelMachine: sshTunnelMachine}, getDsn(d, db))

View File

@@ -69,11 +69,13 @@ func (m *machineAppImpl) Save(me *entity.Machine) {
}
// 关闭连接
machine.DeleteCli(me.Id)
me.PwdEncrypt()
m.machineRepo.UpdateById(me)
} else {
biz.IsTrue(err != nil, "该机器信息已存在")
// 新增机器,默认启用状态
me.Status = entity.MachineStatusEnable
me.PwdEncrypt()
m.machineRepo.Create(me)
}
}
@@ -123,6 +125,7 @@ func (m *machineAppImpl) GetById(id uint64, cols ...string) *entity.Machine {
func (m *machineAppImpl) GetCli(id uint64) *machine.Cli {
cli, err := machine.GetCli(id, func(machineId uint64) *entity.Machine {
machine := m.GetById(machineId)
machine.PwdDecrypt()
biz.IsTrue(machine.Status == entity.MachineStatusEnable, "该机器已被停用")
return machine
})
@@ -133,6 +136,7 @@ func (m *machineAppImpl) GetCli(id uint64) *machine.Cli {
func (m *machineAppImpl) GetSshTunnelMachine(id uint64) *machine.SshTunnelMachine {
sshTunnel, err := machine.GetSshTunnelMachine(id, func(machineId uint64) *entity.Machine {
machine := m.GetById(machineId)
machine.PwdDecrypt()
biz.IsTrue(machine.Status == entity.MachineStatusEnable, "该机器已被停用")
return machine
})

View File

@@ -80,6 +80,7 @@ func (r *redisAppImpl) Save(re *entity.Redis) {
if re.Id == 0 {
biz.IsTrue(err != nil, "该库已存在")
re.PwdEncrypt()
r.redisRepo.Insert(re)
} else {
// 如果存在该库,则校验修改的库是否为该库
@@ -88,6 +89,7 @@ func (r *redisAppImpl) Save(re *entity.Redis) {
}
// 先关闭数据库连接
CloseRedis(re.Id)
re.PwdEncrypt()
r.redisRepo.Update(re)
}
}
@@ -110,6 +112,7 @@ func (r *redisAppImpl) GetRedisInstance(id uint64) *RedisInstance {
}
// 缓存不存在则回调获取redis信息
re := r.GetById(id)
re.PwdDecrypt()
biz.NotNil(re, "redis信息不存在")
redisMode := re.Mode

View File

@@ -2,6 +2,7 @@ package entity
import (
"fmt"
"mayfly-go/internal/common/utils"
"mayfly-go/pkg/model"
)
@@ -27,9 +28,9 @@ type Db struct {
}
// 获取数据库连接网络, 若没有使用ssh隧道则直接返回。否则返回拼接的网络需要注册至指定dial
func (d Db) GetNetwork() string {
func (d *Db) GetNetwork() string {
network := d.Network
if d.EnableSshTunnel == -1 {
if d.EnableSshTunnel == 0 || d.EnableSshTunnel == -1 {
if network == "" {
return "tcp"
} else {
@@ -39,6 +40,16 @@ func (d Db) GetNetwork() string {
return fmt.Sprintf("%s+ssh:%d", d.Type, d.SshTunnelMachineId)
}
func (d *Db) PwdEncrypt() {
// 密码替换为加密后的密码
d.Password = utils.PwdAesEncrypt(d.Password)
}
func (d *Db) PwdDecrypt() {
// 密码替换为解密后的密码
d.Password = utils.PwdAesDecrypt(d.Password)
}
const (
DbTypeMysql = "mysql"
DbTypePostgres = "postgres"

View File

@@ -1,6 +1,7 @@
package entity
import (
"mayfly-go/internal/common/utils"
"mayfly-go/pkg/model"
)
@@ -26,3 +27,13 @@ const (
MachineAuthMethodPassword int8 = 1 // 密码登录
MachineAuthMethodPublicKey int8 = 2 // 公钥免密登录
)
func (m *Machine) PwdEncrypt() {
// 密码替换为加密后的密码
m.Password = utils.PwdAesEncrypt(m.Password)
}
func (m *Machine) PwdDecrypt() {
// 密码替换为解密后的密码
m.Password = utils.PwdAesDecrypt(m.Password)
}

View File

@@ -1,6 +1,7 @@
package entity
import (
"mayfly-go/internal/common/utils"
"mayfly-go/pkg/model"
)
@@ -24,3 +25,13 @@ const (
RedisModeStandalone = "standalone"
RedisModeCluster = "cluster"
)
func (r *Redis) PwdEncrypt() {
// 密码替换为加密后的密码
r.Password = utils.PwdAesEncrypt(r.Password)
}
func (r *Redis) PwdDecrypt() {
// 密码替换为解密后的密码
r.Password = utils.PwdAesDecrypt(r.Password)
}

View File

@@ -5,11 +5,11 @@ import (
"io"
"mayfly-go/internal/devops/domain/entity"
"mayfly-go/pkg/global"
"mayfly-go/pkg/scheduler"
"mayfly-go/pkg/utils"
"net"
"os"
"sync"
"time"
"golang.org/x/crypto/ssh"
)
@@ -31,30 +31,29 @@ type CheckSshTunnelMachineHasUseFunc func(uint64) bool
func startCheckUse() {
global.Log.Info("开启定时检测ssh隧道机器是否还有被使用")
heartbeat := time.Duration(10) * time.Minute
tick := time.NewTicker(heartbeat)
go func() {
for range tick.C {
func() {
if !mutex.TryLock() {
return
}
defer mutex.Unlock()
// 遍历隧道机器,都未被使用将会被关闭
for mid, sshTunnelMachine := range sshTunnelMachines {
global.Log.Debugf("开始定时检查ssh隧道机器[%d]是否还有被使用...", mid)
for _, checkUseFunc := range checkSshTunnelMachineHasUseFuncs {
// 如果一个在使用则返回不关闭,不继续后续检查
if checkUseFunc(mid) {
return
}
}
// 都未被使用,则关闭
sshTunnelMachine.Close()
}
}()
// 每十分钟检查一次隧道机器是否还有被使用
scheduler.AddFun("@every 10m", func() {
if !mutex.TryLock() {
return
}
}()
defer mutex.Unlock()
// 遍历隧道机器,都未被使用将会被关闭
for mid, sshTunnelMachine := range sshTunnelMachines {
global.Log.Debugf("开始定时检查ssh隧道机器[%d]是否还有被使用...", mid)
hasUse := false
for _, checkUseFunc := range checkSshTunnelMachineHasUseFuncs {
// 如果一个在使用则返回不关闭,不继续后续检查
if checkUseFunc(mid) {
hasUse = true
break
}
}
if !hasUse {
// 都未被使用,则关闭
sshTunnelMachine.Close()
}
}
})
}
// 添加ssh隧道机器检测是否使用函数
@@ -129,7 +128,10 @@ func (stm *SshTunnelMachine) Close() {
if stm.SshClient != nil {
global.Log.Infof("ssh隧道机器[%d]未被使用, 关闭隧道...", stm.machineId)
stm.SshClient.Close()
err := stm.SshClient.Close()
if err != nil {
global.Log.Errorf("关闭ssh隧道机器[%d]发生错误: %s", stm.machineId, err.Error())
}
}
delete(sshTunnelMachines, stm.machineId)
}

View File

@@ -76,7 +76,7 @@ func NewLogicSshWsSession(cols, rows int, cli *Cli, wsConn *websocket.Conn) (*Lo
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := sshSession.RequestPty("xterm", rows, cols, modes); err != nil {
if err := sshSession.RequestPty("xterm-256color", rows, cols, modes); err != nil {
return nil, err
}
// Start remote shell

View File

@@ -1,27 +0,0 @@
package scheduler
func init() {
SaveMachineMonitor()
}
func SaveMachineMonitor() {
AddFun("@every 60s", func() {
// for _, m := range models.GetNeedMonitorMachine() {
// m := m
// go func() {
// cli, err := machine.GetCli(uint64(utils.GetInt4Map(m, "id")))
// if err != nil {
// mlog.Log.Error("获取客户端失败:", err.Error())
// return
// }
// mm := cli.GetMonitorInfo()
// if mm != nil {
// err := model.Insert(mm)
// if err != nil {
// mlog.Log.Error("保存机器监控信息失败: ", err.Error())
// }
// }
// }()
// }
})
}

View File

@@ -20,8 +20,7 @@ func InitDbRouter(router *gin.RouterGroup) {
}
// 获取所有数据库列表
db.GET("", func(c *gin.Context) {
rc := ctx.NewReqCtxWithGin(c)
rc.Handle(d.Dbs)
ctx.NewReqCtxWithGin(c).Handle(d.Dbs)
})
saveDb := ctx.NewLogInfo("保存数据库信息").WithSave(true)
@@ -31,11 +30,16 @@ func InitDbRouter(router *gin.RouterGroup) {
Handle(d.Save)
})
// 获取数据库实例的所有数据库名
db.POST("databases", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).
Handle(d.GetDatabaseNames)
})
db.GET(":dbId/pwd", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(d.GetDbPwd)
})
deleteDb := ctx.NewLogInfo("删除数据库信息").WithSave(true)
db.DELETE(":dbId", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).

View File

@@ -20,6 +20,10 @@ func InitMachineRouter(router *gin.RouterGroup) {
ctx.NewReqCtxWithGin(c).Handle(m.Machines)
})
machines.GET(":machineId/pwd", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(m.GetMachinePwd)
})
machines.GET(":machineId/stats", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(m.MachineStats)
})

View File

@@ -26,6 +26,10 @@ func InitRedisRouter(router *gin.RouterGroup) {
ctx.NewReqCtxWithGin(c).WithLog(save).Handle(rs.Save)
})
redis.GET(":id/pwd", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(rs.GetRedisPwd)
})
delRedis := ctx.NewLogInfo("删除redis信息").WithSave(true)
redis.DELETE(":id", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).WithLog(delRedis).Handle(rs.DeleteRedis)

View File

@@ -38,8 +38,10 @@ func (a *Account) Login(rc *ctx.ReqCtx) {
originPwd, err := utils.DefaultRsaDecrypt(loginForm.Password, true)
biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
account := &entity.Account{Username: loginForm.Username, Password: utils.Md5(originPwd)}
biz.ErrIsNil(a.AccountApp.GetAccount(account, "Id", "Username", "Status", "LastLoginTime", "LastLoginIp"), "用户名或密码错误")
account := &entity.Account{Username: loginForm.Username}
err = a.AccountApp.GetAccount(account, "Id", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp")
biz.ErrIsNil(err, "用户名或密码错误")
biz.IsTrue(utils.CheckPwdHash(originPwd, account.Password), "用户名或密码错误")
biz.IsTrue(account.IsEnable(), "该账号不可用")
// 校验密码强度是否符合
@@ -86,8 +88,11 @@ func (a *Account) ChangePassword(rc *ctx.ReqCtx) {
originOldPwd, err := utils.DefaultRsaDecrypt(form.OldPassword, true)
biz.ErrIsNilAppendErr(err, "解密旧密码错误: %s")
account := &entity.Account{Username: form.Username, Password: utils.Md5(originOldPwd)}
biz.ErrIsNil(a.AccountApp.GetAccount(account, "Id", "Username", "Status"), "旧密码不正确")
account := &entity.Account{Username: form.Username}
err = a.AccountApp.GetAccount(account, "Id", "Username", "Password", "Status")
biz.ErrIsNil(err, "旧密码错误")
biz.IsTrue(utils.CheckPwdHash(originOldPwd, account.Password), "旧密码错误")
biz.IsTrue(account.IsEnable(), "该账号不可用")
originNewPwd, err := utils.DefaultRsaDecrypt(form.NewPassword, true)
biz.ErrIsNilAppendErr(err, "解密新密码错误: %s")
@@ -95,7 +100,7 @@ func (a *Account) ChangePassword(rc *ctx.ReqCtx) {
updateAccount := new(entity.Account)
updateAccount.Id = account.Id
updateAccount.Password = utils.Md5(originNewPwd)
updateAccount.Password = utils.PwdHash(originNewPwd)
a.AccountApp.Update(updateAccount)
// 赋值loginAccount 主要用于记录操作日志,因为操作日志保存请求上下文没有该信息不保存日志
@@ -176,7 +181,7 @@ func (a *Account) UpdateAccount(rc *ctx.ReqCtx) {
if updateAccount.Password != "" {
biz.IsTrue(CheckPasswordLever(updateAccount.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
updateAccount.Password = utils.Md5(updateAccount.Password)
updateAccount.Password = utils.PwdHash(updateAccount.Password)
}
a.AccountApp.Update(updateAccount)
}

View File

@@ -43,7 +43,7 @@ func (a *accountAppImpl) GetPageList(condition *entity.Account, pageParam *model
func (a *accountAppImpl) Create(account *entity.Account) {
biz.IsTrue(a.GetAccount(&entity.Account{Username: account.Username}) != nil, "该账号用户名已存在")
// 默认密码为账号用户名
account.Password = utils.Md5(account.Username)
account.Password = utils.PwdHash(account.Username)
account.Status = entity.AccountEnableStatus
a.accountRepo.Insert(account)
}

View File

@@ -30,8 +30,8 @@ CREATE TABLE `t_db` (
`database` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '数据库,空格分割多个数据库',
`params` varchar(125) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '其他连接参数',
`network` varchar(20) COLLATE utf8mb4_bin DEFAULT NULL,
`enableSshTunnel` tinyint(2) DEFAULT NULL COMMENT '是否启用ssh隧道',
`sshTunnelMachineId` bigint(20) DEFAULT NULL COMMENT 'ssh隧道的机器id',
`enable_ssh_tunnel` tinyint(2) DEFAULT NULL COMMENT '是否启用ssh隧道',
`ssh_tunnel_machine_id` bigint(20) DEFAULT NULL COMMENT 'ssh隧道的机器id',
`project_id` bigint(20) DEFAULT NULL,
`project` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL,
`env_id` bigint(20) DEFAULT NULL COMMENT '环境id',
@@ -111,8 +111,8 @@ CREATE TABLE `t_machine` (
`username` varchar(12) COLLATE utf8mb4_bin NOT NULL,
`auth_method` tinyint(2) NULL DEFAULT NULL COMMENT '1.密码登录2.publickey登录',
`password` varchar(3200) COLLATE utf8mb4_bin DEFAULT NULL,
`enableSshTunnel` tinyint(2) DEFAULT NULL COMMENT '是否启用ssh隧道',
`sshTunnelMachineId` bigint(20) DEFAULT NULL COMMENT 'ssh隧道的机器id',
`enable_ssh_tunnel` tinyint(2) DEFAULT NULL COMMENT '是否启用ssh隧道',
`ssh_tunnel_machine_id` bigint(20) DEFAULT NULL COMMENT 'ssh隧道的机器id',
`status` tinyint(2) NOT NULL COMMENT '状态: 1:启用; -1:禁用',
`remark` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
`need_monitor` tinyint(2) DEFAULT NULL,
@@ -263,8 +263,8 @@ CREATE TABLE `t_redis` (
`password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
`db` int(32) DEFAULT NULL,
`mode` varchar(32) DEFAULT NULL,
`enableSshTunnel` tinyint(2) DEFAULT NULL COMMENT '是否启用ssh隧道',
`sshTunnelMachineId` bigint(20) DEFAULT NULL COMMENT 'ssh隧道的机器id',
`enable_ssh_tunnel` tinyint(2) DEFAULT NULL COMMENT '是否启用ssh隧道',
`ssh_tunnel_machine_id` bigint(20) DEFAULT NULL COMMENT 'ssh隧道的机器id',
`remark` varchar(125) DEFAULT NULL,
`project_id` bigint(20) DEFAULT NULL,
`project` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
@@ -670,8 +670,8 @@ CREATE TABLE `t_mongo` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(36) COLLATE utf8mb4_bin NOT NULL COMMENT '名称',
`uri` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '连接uri',
`enableSshTunnel` tinyint(2) DEFAULT NULL COMMENT '是否启用ssh隧道',
`sshTunnelMachineId` bigint(20) DEFAULT NULL COMMENT 'ssh隧道的机器id',
`enable_ssh_tunnel` tinyint(2) DEFAULT NULL COMMENT '是否启用ssh隧道',
`ssh_tunnel_machine_id` bigint(20) DEFAULT NULL COMMENT 'ssh隧道的机器id',
`project_id` bigint(20) NOT NULL,
`project` varchar(36) COLLATE utf8mb4_bin DEFAULT NULL,
`env_id` bigint(20) DEFAULT NULL,

27
server/pkg/config/aes.go Normal file
View File

@@ -0,0 +1,27 @@
package config
import (
"fmt"
"mayfly-go/pkg/utils"
"mayfly-go/pkg/utils/assert"
)
type Aes struct {
Key string `yaml:"key"`
}
// 编码并base64
func (a *Aes) EncryptBase64(data []byte) (string, error) {
return utils.AesEncryptBase64(data, []byte(a.Key))
}
// base64解码后再aes解码
func (a *Aes) DecryptBase64(data string) ([]byte, error) {
return utils.AesDecryptBase64(data, []byte(a.Key))
}
func (j *Aes) Valid() {
aesKeyLen := len(j.Key)
assert.IsTrue(aesKeyLen == 16 || aesKeyLen == 24 || aesKeyLen == 32,
fmt.Sprintf("config.yml之 [aes.key] 长度需为16、24、32位长度, 当前为%d位", aesKeyLen))
}

View File

@@ -40,6 +40,7 @@ type Config struct {
App *App `yaml:"app"`
Server *Server `yaml:"server"`
Jwt *Jwt `yaml:"jwt"`
Aes *Aes `yaml:"aes"`
Redis *Redis `yaml:"redis"`
Mysql *Mysql `yaml:"mysql"`
Log *Log `yaml:"log"`
@@ -49,14 +50,7 @@ type Config struct {
func (c *Config) Valid() {
assert.IsTrue(c.Jwt != nil, "配置文件的[jwt]信息不能为空")
c.Jwt.Valid()
}
// 获取执行可执行文件时,指定的启动参数
func getStartConfig() *CmdConfigParam {
configFilePath := flag.String("e", "./config.yml", "配置文件路径,默认为可执行文件目录")
flag.Parse()
// 获取配置文件绝对路径
path, _ := filepath.Abs(*configFilePath)
sc := &CmdConfigParam{ConfigFilePath: path}
return sc
if c.Aes != nil {
c.Aes.Valid()
}
}

View File

@@ -8,6 +8,5 @@ type Jwt struct {
}
func (j *Jwt) Valid() {
assert.IsTrue(j.Key != "", "config.yml之 [jwt.key] 不能为空")
assert.IsTrue(j.ExpireTime != 0, "config.yml之 [jwt.expire-time] 不能为空")
}

View File

@@ -5,10 +5,12 @@ import (
"mayfly-go/pkg/biz"
"mayfly-go/pkg/config"
"mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/golang-jwt/jwt/v4"
)
var (
@@ -25,7 +27,11 @@ func CreateToken(userId uint64, username string) string {
"username": username,
"exp": time.Now().Add(time.Minute * time.Duration(ExpTime)).Unix(),
})
// 如果jwt key为空则随机生成字符串
if JwtKey == "" {
JwtKey = utils.RandString(32)
global.Log.Infof("config.yml未配置jwt.key, 随机生成key为: %s", JwtKey)
}
// 使用自定义字符串加密 and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte(JwtKey))
biz.ErrIsNil(err, "token创建失败")

View File

@@ -6,6 +6,10 @@ import (
"github.com/robfig/cron/v3"
)
func init() {
Start()
}
var cronService = cron.New()
func Start() {

View File

@@ -2,6 +2,8 @@ package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
@@ -10,6 +12,8 @@ import (
"encoding/hex"
"encoding/pem"
"errors"
"golang.org/x/crypto/bcrypt"
)
// md5
@@ -19,6 +23,17 @@ func Md5(str string) string {
return hex.EncodeToString(h.Sum(nil))
}
// bcrypt加密密码
func PwdHash(password string) string {
bytes, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes)
}
// 检查密码是否一致
func CheckPwdHash(password, hash string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
// 系统统一RSA秘钥对
var RsaPair []string
@@ -130,3 +145,84 @@ func GetRsaPrivateKey() (string, error) {
RsaPair = append(RsaPair, publicKey)
return privateKey, nil
}
//AesEncrypt 加密
func AesEncrypt(data []byte, key []byte) ([]byte, error) {
//创建加密实例
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//判断加密快的大小
blockSize := block.BlockSize()
//填充
encryptBytes := pkcs7Padding(data, blockSize)
//初始化加密数据接收切片
crypted := make([]byte, len(encryptBytes))
//使用cbc加密模式
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
//执行加密
blockMode.CryptBlocks(crypted, encryptBytes)
return crypted, nil
}
//AesDecrypt 解密
func AesDecrypt(data []byte, key []byte) ([]byte, error) {
//创建实例
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//获取块的大小
blockSize := block.BlockSize()
//使用cbc
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
//初始化解密数据接收切片
crypted := make([]byte, len(data))
//执行解密
blockMode.CryptBlocks(crypted, data)
//去除填充
crypted, err = pkcs7UnPadding(crypted)
if err != nil {
return nil, err
}
return crypted, nil
}
// aes加密 后 再base64
func AesEncryptBase64(data []byte, key []byte) (string, error) {
res, err := AesEncrypt(data, key)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(res), nil
}
// base64解码后再 aes解码
func AesDecryptBase64(data string, key []byte) ([]byte, error) {
dataByte, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return nil, err
}
return AesDecrypt(dataByte, key)
}
//pkcs7Padding 填充
func pkcs7Padding(data []byte, blockSize int) []byte {
//判断缺少几位长度。最少1最多 blockSize
padding := blockSize - len(data)%blockSize
//补足位数。把切片[]byte{byte(padding)}复制padding个
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
//pkcs7UnPadding 填充的反向操作
func pkcs7UnPadding(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, errors.New("加密字符串错误!")
}
//获取填充的个数
unPadding := int(data[length-1])
return data[:(length - unPadding)], nil
}

25
server/pkg/utils/rand.go Normal file
View File

@@ -0,0 +1,25 @@
package utils
import (
"math/rand"
"time"
)
const randChar = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// 生成随机字符串
func RandString(l int) string {
strList := []byte(randChar)
result := []byte{}
i := 0
r := rand.New(rand.NewSource(time.Now().UnixNano()))
charLen := len(strList)
for i < l {
new := strList[r.Intn(charLen)]
result = append(result, new)
i = i + 1
}
return string(result)
}

View File

@@ -1,10 +1,12 @@
相关配置文件:
后端:
config.yml: 服务端口mysql等信息在此配置即可。
config.yml: 服务端口mysqlaeskey(16 24 32位)jwtkey等信息在此配置即可。
建议务必将aes.key(资源密码加密如机器、数据库、redis等密码)与jwt.key(jwt秘钥)两信息使用随机字符串替换。
前端:
static/config.js: 若前后端分开部署则将该文件中的api地址配成后端服务的真实地址即可否则无需修改。
服务启动:./startup.sh
服务启动&重启./startup.sh
服务关闭:./shutdown.sh
直接通过 host:ip即可访问项目

View File

@@ -2,6 +2,12 @@
execfile=./mayfly-go
pid=`ps ax | grep -i 'mayfly-go' | grep -v grep | awk '{print $1}'`
if [ ! -z "${pid}" ] ; then
echo "The mayfly-go already running, shutdown and restart..."
kill ${pid}
fi
if [ ! -x "${execfile}" ]; then
sudo chmod +x "${execfile}"
fi