mirror of
				https://gitee.com/dromara/mayfly-go
				synced 2025-11-04 08:20:25 +08:00 
			
		
		
		
	Compare commits
	
		
			8 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 
						 | 
					5271bd21e8 | ||
| 
						 | 
					db554ebdc9 | ||
| 
						 | 
					1c18a01bf6 | ||
| 
						 | 
					729a3d7028 | ||
| 
						 | 
					b88923a128 | ||
| 
						 | 
					fe8cd93c78 | ||
| 
						 | 
					64b49dae2e | ||
| 
						 | 
					edbbbca5f9 | 
@@ -1,7 +1,7 @@
 | 
				
			|||||||
# 🌈mayfly-go
 | 
					# 🌈mayfly-go
 | 
				
			||||||
 | 
					
 | 
				
			||||||
### 介绍
 | 
					### 介绍
 | 
				
			||||||
简单基于DDD(领域驱动设计)分层架构实现的web版 **linux、数据库(mysql)、redis、mongo统一管理操作平台**
 | 
					简单基于DDD(领域驱动设计)分层架构实现的web版 **linux、数据库(mysql postgres)、redis(单机 集群)、mongo统一管理操作平台**
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
### 开发语言与主要框架
 | 
					### 开发语言与主要框架
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										5116
									
								
								mayfly_go_web/package-lock.json
									
									
									
										generated
									
									
									
										Normal file
									
								
							
							
						
						
									
										5116
									
								
								mayfly_go_web/package-lock.json
									
									
									
										generated
									
									
									
										Normal file
									
								
							
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							@@ -7,25 +7,26 @@
 | 
				
			|||||||
    "lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/"
 | 
					    "lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/"
 | 
				
			||||||
  },
 | 
					  },
 | 
				
			||||||
  "dependencies": {
 | 
					  "dependencies": {
 | 
				
			||||||
    "@element-plus/icons-vue": "^2.0.4",
 | 
					    "@element-plus/icons-vue": "^2.0.6",
 | 
				
			||||||
    "axios": "^0.27.2",
 | 
					    "axios": "^0.27.2",
 | 
				
			||||||
    "codemirror": "^5.65.5",
 | 
					    "codemirror": "^5.65.5",
 | 
				
			||||||
    "countup.js": "^2.0.7",
 | 
					    "countup.js": "^2.0.7",
 | 
				
			||||||
    "cropperjs": "^1.5.11",
 | 
					    "cropperjs": "^1.5.11",
 | 
				
			||||||
    "echarts": "^5.3.2",
 | 
					    "echarts": "^5.3.3",
 | 
				
			||||||
    "element-plus": "^2.2.4",
 | 
					    "element-plus": "^2.2.9",
 | 
				
			||||||
    "jsoneditor": "^9.8.0",
 | 
					    "jsencrypt": "^3.2.1",
 | 
				
			||||||
 | 
					    "jsoneditor": "^9.9.0",
 | 
				
			||||||
    "lodash": "^4.17.21",
 | 
					    "lodash": "^4.17.21",
 | 
				
			||||||
    "mitt": "^3.0.0",
 | 
					    "mitt": "^3.0.0",
 | 
				
			||||||
    "nprogress": "^0.2.0",
 | 
					    "nprogress": "^0.2.0",
 | 
				
			||||||
    "screenfull": "^5.1.0",
 | 
					    "screenfull": "^5.1.0",
 | 
				
			||||||
    "sortablejs": "^1.13.0",
 | 
					    "sortablejs": "^1.13.0",
 | 
				
			||||||
    "sql-formatter": "^6.1.2",
 | 
					    "sql-formatter": "^7.0.3",
 | 
				
			||||||
    "vue": "^3.2.37",
 | 
					    "vue": "^3.2.37",
 | 
				
			||||||
    "vue-clipboard3": "^1.0.1",
 | 
					    "vue-clipboard3": "^1.0.1",
 | 
				
			||||||
    "vue-router": "^4.0.15",
 | 
					    "vue-router": "^4.1.2",
 | 
				
			||||||
    "vuex": "^4.0.2",
 | 
					    "vuex": "^4.0.2",
 | 
				
			||||||
    "xterm": "^4.18.0",
 | 
					    "xterm": "^4.19.0",
 | 
				
			||||||
    "xterm-addon-fit": "^0.5.0"
 | 
					    "xterm-addon-fit": "^0.5.0"
 | 
				
			||||||
  },
 | 
					  },
 | 
				
			||||||
  "devDependencies": {
 | 
					  "devDependencies": {
 | 
				
			||||||
@@ -43,8 +44,8 @@
 | 
				
			|||||||
    "prettier": "^2.3.0",
 | 
					    "prettier": "^2.3.0",
 | 
				
			||||||
    "sass": "^1.45.1",
 | 
					    "sass": "^1.45.1",
 | 
				
			||||||
    "sass-loader": "^12.4.0",
 | 
					    "sass-loader": "^12.4.0",
 | 
				
			||||||
    "typescript": "^4.2.4",
 | 
					    "typescript": "^4.7.4",
 | 
				
			||||||
    "vite": "^2.9.10",
 | 
					    "vite": "^2.9.13",
 | 
				
			||||||
    "vue-eslint-parser": "^8.0.1"
 | 
					    "vue-eslint-parser": "^8.0.1"
 | 
				
			||||||
  },
 | 
					  },
 | 
				
			||||||
  "browserslist": [
 | 
					  "browserslist": [
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,4 +1,5 @@
 | 
				
			|||||||
window.globalConfig = {
 | 
					window.globalConfig = {
 | 
				
			||||||
    "BaseApiUrl": "http://localhost:8888",
 | 
					    // 默认为空,以访问根目录为api请求地址。若前后端分离部署可单独配置该后端api请求地址
 | 
				
			||||||
    "BaseWsUrl": "ws://localhost:8888"
 | 
					    "BaseApiUrl": "",
 | 
				
			||||||
 | 
					    "BaseWsUrl": ""
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -1,6 +1,6 @@
 | 
				
			|||||||
const config = {
 | 
					const config = {
 | 
				
			||||||
    baseApiUrl: `${(window as any).globalConfig.BaseApiUrl}/api`,
 | 
					    baseApiUrl: `${(window as any).globalConfig.BaseApiUrl}/api`,
 | 
				
			||||||
    baseWsUrl: `${(window as any).globalConfig.BaseWsUrl}/api`
 | 
					    baseWsUrl: `${(window as any).globalConfig.BaseWsUrl || `${location.protocol == 'https:' ? 'wss:' : 'ws:'}//${location.host}`}/api`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default config
 | 
					export default config
 | 
				
			||||||
@@ -2,6 +2,8 @@ import request from './request'
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
export default {
 | 
					export default {
 | 
				
			||||||
    login: (param: any) => request.request('POST', '/sys/accounts/login', param, null),
 | 
					    login: (param: any) => request.request('POST', '/sys/accounts/login', param, null),
 | 
				
			||||||
 | 
					    changePwd: (param: any) => request.request('POST', '/sys/accounts/change-pwd', param, null),
 | 
				
			||||||
 | 
					    getPublicKey: () => request.request('GET', '/common/public-key', null, null),
 | 
				
			||||||
    captcha: () => request.request('GET', '/sys/captcha', null, null),
 | 
					    captcha: () => request.request('GET', '/sys/captcha', null, null),
 | 
				
			||||||
    logout: (param: any) => request.request('POST', '/sys/accounts/logout/{token}', param, null),
 | 
					    logout: (param: any) => request.request('POST', '/sys/accounts/logout/{token}', param, null),
 | 
				
			||||||
    getMenuRoute: (param: any) => request.request('Get', '/sys/resources/account', param, null)
 | 
					    getMenuRoute: (param: any) => request.request('Get', '/sys/resources/account', param, null)
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										37
									
								
								mayfly_go_web/src/common/rsa.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										37
									
								
								mayfly_go_web/src/common/rsa.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,37 @@
 | 
				
			|||||||
 | 
					import openApi from './openApi';
 | 
				
			||||||
 | 
					import JSEncrypt from 'jsencrypt'
 | 
				
			||||||
 | 
					import { notBlank } from './assert';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var encryptor: any = null
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					export async function getRsaPublicKey() {
 | 
				
			||||||
 | 
					    let publicKey = sessionStorage.getItem('RsaPublicKey')
 | 
				
			||||||
 | 
					    if (publicKey) {
 | 
				
			||||||
 | 
					        return publicKey
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					    publicKey = await openApi.getPublicKey() as string
 | 
				
			||||||
 | 
					    sessionStorage.setItem('RsaPublicKey', publicKey)
 | 
				
			||||||
 | 
					    return publicKey
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					/**
 | 
				
			||||||
 | 
					 * 公钥加密指定值
 | 
				
			||||||
 | 
					 * 
 | 
				
			||||||
 | 
					 * @param value value
 | 
				
			||||||
 | 
					 * @returns 加密后的值
 | 
				
			||||||
 | 
					 */
 | 
				
			||||||
 | 
					export async function RsaEncrypt(value: any) {
 | 
				
			||||||
 | 
					    // 不存在则返回空值
 | 
				
			||||||
 | 
					    if (!value) {
 | 
				
			||||||
 | 
					        return ""
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					    if (encryptor != null) {
 | 
				
			||||||
 | 
					        return encryptor.encrypt(value)
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					    console.log(value)
 | 
				
			||||||
 | 
					    encryptor = new JSEncrypt()
 | 
				
			||||||
 | 
					    const publicKey = await getRsaPublicKey() as string;
 | 
				
			||||||
 | 
					    notBlank(publicKey, "获取公钥失败")
 | 
				
			||||||
 | 
					    encryptor.setPublicKey(publicKey)//设置公钥
 | 
				
			||||||
 | 
					    return encryptor.encrypt(value)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -10,6 +10,7 @@ export const imports = {
 | 
				
			|||||||
    "ResourceList": () => import('@/views/system/resource'),
 | 
					    "ResourceList": () => import('@/views/system/resource'),
 | 
				
			||||||
    "RoleList": () => import('@/views/system/role'),
 | 
					    "RoleList": () => import('@/views/system/role'),
 | 
				
			||||||
    "AccountList": () => import('@/views/system/account'),
 | 
					    "AccountList": () => import('@/views/system/account'),
 | 
				
			||||||
 | 
					    "SyslogList": () => import('@/views/system/syslog/SyslogList.vue'),
 | 
				
			||||||
    // project
 | 
					    // project
 | 
				
			||||||
    "ProjectList": () => import('@/views/ops/project/ProjectList.vue'),
 | 
					    "ProjectList": () => import('@/views/ops/project/ProjectList.vue'),
 | 
				
			||||||
    // db
 | 
					    // db
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -239,16 +239,6 @@
 | 
				
			|||||||
	color: set-color(primary);
 | 
						color: set-color(primary);
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
/* Switch 开关
 | 
					 | 
				
			||||||
------------------------------- */
 | 
					 | 
				
			||||||
.el-switch.is-checked .el-switch__core {
 | 
					 | 
				
			||||||
	border-color: set-color(primary);
 | 
					 | 
				
			||||||
	background-color: set-color(primary);
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
.el-switch__label.is-active {
 | 
					 | 
				
			||||||
	color: set-color(primary);
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
/* Slider 滑块
 | 
					/* Slider 滑块
 | 
				
			||||||
------------------------------- */
 | 
					------------------------------- */
 | 
				
			||||||
.el-slider__bar {
 | 
					.el-slider__bar {
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -30,7 +30,7 @@ import { useStore } from '@/store/index.ts';
 | 
				
			|||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'layoutBreadcrumbSearch',
 | 
					    name: 'layoutBreadcrumbSearch',
 | 
				
			||||||
    setup() {
 | 
					    setup() {
 | 
				
			||||||
        const layoutMenuAutocompleteRef = ref();
 | 
					        const layoutMenuAutocompleteRef: any = ref(null);
 | 
				
			||||||
        const store = useStore();
 | 
					        const store = useStore();
 | 
				
			||||||
        const router = useRouter();
 | 
					        const router = useRouter();
 | 
				
			||||||
        const state: any = reactive({
 | 
					        const state: any = reactive({
 | 
				
			||||||
@@ -44,8 +44,10 @@ export default defineComponent({
 | 
				
			|||||||
            state.isShowSearch = true;
 | 
					            state.isShowSearch = true;
 | 
				
			||||||
            initTageView();
 | 
					            initTageView();
 | 
				
			||||||
            nextTick(() => {
 | 
					            nextTick(() => {
 | 
				
			||||||
 | 
					                setTimeout(() => {
 | 
				
			||||||
                    layoutMenuAutocompleteRef.value.focus();
 | 
					                    layoutMenuAutocompleteRef.value.focus();
 | 
				
			||||||
                });
 | 
					                });
 | 
				
			||||||
 | 
					            });
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
        // 搜索弹窗关闭
 | 
					        // 搜索弹窗关闭
 | 
				
			||||||
        const closeSearch = () => {
 | 
					        const closeSearch = () => {
 | 
				
			||||||
@@ -68,7 +70,6 @@ export default defineComponent({
 | 
				
			|||||||
        // 初始化菜单数据
 | 
					        // 初始化菜单数据
 | 
				
			||||||
        const initTageView = () => {
 | 
					        const initTageView = () => {
 | 
				
			||||||
            if (state.tagsViewList.length > 0) return false;
 | 
					            if (state.tagsViewList.length > 0) return false;
 | 
				
			||||||
            console.log(getRoutes(store.state.routesList.routesList));
 | 
					 | 
				
			||||||
            getRoutes(store.state.routesList.routesList).map((v: any) => {
 | 
					            getRoutes(store.state.routesList.routesList).map((v: any) => {
 | 
				
			||||||
                if (!v.meta.isHide) {
 | 
					                if (!v.meta.isHide) {
 | 
				
			||||||
                    state.tagsViewList.push({ ...v });
 | 
					                    state.tagsViewList.push({ ...v });
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,18 +1,12 @@
 | 
				
			|||||||
<template>
 | 
					<template>
 | 
				
			||||||
 | 
					    <div>
 | 
				
			||||||
        <el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="login-content-form" size="large">
 | 
					        <el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="login-content-form" size="large">
 | 
				
			||||||
            <el-form-item prop="username">
 | 
					            <el-form-item prop="username">
 | 
				
			||||||
                <el-input type="text" placeholder="请输入用户名" prefix-icon="user" v-model="loginForm.username" clearable autocomplete="off">
 | 
					                <el-input type="text" placeholder="请输入用户名" prefix-icon="user" v-model="loginForm.username" clearable autocomplete="off">
 | 
				
			||||||
                </el-input>
 | 
					                </el-input>
 | 
				
			||||||
            </el-form-item>
 | 
					            </el-form-item>
 | 
				
			||||||
            <el-form-item prop="password">
 | 
					            <el-form-item prop="password">
 | 
				
			||||||
            <el-input
 | 
					                <el-input type="password" placeholder="请输入密码" prefix-icon="lock" v-model="loginForm.password" autocomplete="off" show-password>
 | 
				
			||||||
                type="password"
 | 
					 | 
				
			||||||
                placeholder="请输入密码"
 | 
					 | 
				
			||||||
                prefix-icon="lock"
 | 
					 | 
				
			||||||
                v-model="loginForm.password"
 | 
					 | 
				
			||||||
                autocomplete="off"
 | 
					 | 
				
			||||||
                show-password
 | 
					 | 
				
			||||||
            >
 | 
					 | 
				
			||||||
                </el-input>
 | 
					                </el-input>
 | 
				
			||||||
            </el-form-item>
 | 
					            </el-form-item>
 | 
				
			||||||
            <el-form-item prop="captcha">
 | 
					            <el-form-item prop="captcha">
 | 
				
			||||||
@@ -49,6 +43,33 @@
 | 
				
			|||||||
                </el-button>
 | 
					                </el-button>
 | 
				
			||||||
            </el-form-item>
 | 
					            </el-form-item>
 | 
				
			||||||
        </el-form>
 | 
					        </el-form>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        <el-dialog title="修改密码" v-model="changePwdDialog.visible" :close-on-click-modal="false" width="450px" :destroy-on-close="true">
 | 
				
			||||||
 | 
					            <el-form :model="changePwdDialog.form" :rules="changePwdDialog.rules" ref="changePwdFormRef" label-width="65px">
 | 
				
			||||||
 | 
					                <el-form-item prop="username" label="用户名" required>
 | 
				
			||||||
 | 
					                    <el-input v-model.trim="changePwdDialog.form.username" disabled></el-input>
 | 
				
			||||||
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					                <el-form-item prop="oldPassword" label="旧密码" required>
 | 
				
			||||||
 | 
					                    <el-input v-model.trim="changePwdDialog.form.oldPassword" autocomplete="new-password" type="password"></el-input>
 | 
				
			||||||
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					                <el-form-item prop="newPassword" label="新密码" required>
 | 
				
			||||||
 | 
					                    <el-input
 | 
				
			||||||
 | 
					                        v-model.trim="changePwdDialog.form.newPassword"
 | 
				
			||||||
 | 
					                        placeholder="须为8位以上且包含字⺟⼤⼩写+数字+特殊符号"
 | 
				
			||||||
 | 
					                        type="password"
 | 
				
			||||||
 | 
					                        autocomplete="new-password"
 | 
				
			||||||
 | 
					                    ></el-input>
 | 
				
			||||||
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					            </el-form>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            <template #footer>
 | 
				
			||||||
 | 
					                <div class="dialog-footer">
 | 
				
			||||||
 | 
					                    <el-button @click="cancelChangePwd">取 消</el-button>
 | 
				
			||||||
 | 
					                    <el-button @click="changePwd" type="primary" :loading="loading.changePwd">确 定</el-button>
 | 
				
			||||||
 | 
					                </div>
 | 
				
			||||||
 | 
					            </template>
 | 
				
			||||||
 | 
					        </el-dialog>
 | 
				
			||||||
 | 
					    </div>
 | 
				
			||||||
</template>
 | 
					</template>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
<script lang="ts">
 | 
					<script lang="ts">
 | 
				
			||||||
@@ -60,7 +81,9 @@ import { useStore } from '@/store/index.ts';
 | 
				
			|||||||
import { setSession } from '@/common/utils/storage.ts';
 | 
					import { setSession } from '@/common/utils/storage.ts';
 | 
				
			||||||
import { formatAxis } from '@/common/utils/formatTime.ts';
 | 
					import { formatAxis } from '@/common/utils/formatTime.ts';
 | 
				
			||||||
import openApi from '@/common/openApi';
 | 
					import openApi from '@/common/openApi';
 | 
				
			||||||
 | 
					import { RsaEncrypt } from '@/common/rsa';
 | 
				
			||||||
import { letterAvatar } from '@/common/utils/string';
 | 
					import { letterAvatar } from '@/common/utils/string';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'AccountLogin',
 | 
					    name: 'AccountLogin',
 | 
				
			||||||
    setup() {
 | 
					    setup() {
 | 
				
			||||||
@@ -68,6 +91,8 @@ export default defineComponent({
 | 
				
			|||||||
        const route = useRoute();
 | 
					        const route = useRoute();
 | 
				
			||||||
        const router = useRouter();
 | 
					        const router = useRouter();
 | 
				
			||||||
        const loginFormRef: any = ref(null);
 | 
					        const loginFormRef: any = ref(null);
 | 
				
			||||||
 | 
					        const changePwdFormRef: any = ref(null);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const state = reactive({
 | 
					        const state = reactive({
 | 
				
			||||||
            captchaImage: '',
 | 
					            captchaImage: '',
 | 
				
			||||||
            loginForm: {
 | 
					            loginForm: {
 | 
				
			||||||
@@ -76,6 +101,24 @@ export default defineComponent({
 | 
				
			|||||||
                captcha: '',
 | 
					                captcha: '',
 | 
				
			||||||
                cid: '',
 | 
					                cid: '',
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
 | 
					            changePwdDialog: {
 | 
				
			||||||
 | 
					                visible: false,
 | 
				
			||||||
 | 
					                form: {
 | 
				
			||||||
 | 
					                    username: '',
 | 
				
			||||||
 | 
					                    oldPassword: '',
 | 
				
			||||||
 | 
					                    newPassword: '',
 | 
				
			||||||
 | 
					                },
 | 
				
			||||||
 | 
					                rules: {
 | 
				
			||||||
 | 
					                    newPassword: [
 | 
				
			||||||
 | 
					                        { required: true, message: '请输入新密码', trigger: 'blur' },
 | 
				
			||||||
 | 
					                        {
 | 
				
			||||||
 | 
					                            pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]])[A-Za-z\d`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]]{8,}$/,
 | 
				
			||||||
 | 
					                            message: '须为8位以上且包含字⺟⼤⼩写+数字+特殊符号',
 | 
				
			||||||
 | 
					                            trigger: 'blur',
 | 
				
			||||||
 | 
					                        },
 | 
				
			||||||
 | 
					                    ],
 | 
				
			||||||
 | 
					                },
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
            rules: {
 | 
					            rules: {
 | 
				
			||||||
                username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
 | 
					                username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
 | 
				
			||||||
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
 | 
					                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
 | 
				
			||||||
@@ -83,6 +126,7 @@ export default defineComponent({
 | 
				
			|||||||
            },
 | 
					            },
 | 
				
			||||||
            loading: {
 | 
					            loading: {
 | 
				
			||||||
                signIn: false,
 | 
					                signIn: false,
 | 
				
			||||||
 | 
					                changePwd: false,
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -116,15 +160,26 @@ export default defineComponent({
 | 
				
			|||||||
        const onSignIn = async () => {
 | 
					        const onSignIn = async () => {
 | 
				
			||||||
            state.loading.signIn = true;
 | 
					            state.loading.signIn = true;
 | 
				
			||||||
            let loginRes;
 | 
					            let loginRes;
 | 
				
			||||||
 | 
					            const originPwd = state.loginForm.password;
 | 
				
			||||||
            try {
 | 
					            try {
 | 
				
			||||||
                loginRes = await openApi.login(state.loginForm);
 | 
					                const loginReq = { ...state.loginForm };
 | 
				
			||||||
                // // 存储 token 到浏览器缓存
 | 
					                loginReq.password = await RsaEncrypt(originPwd);
 | 
				
			||||||
 | 
					                loginRes = await openApi.login(loginReq);
 | 
				
			||||||
 | 
					                // 存储 token 到浏览器缓存
 | 
				
			||||||
                setSession('token', loginRes.token);
 | 
					                setSession('token', loginRes.token);
 | 
				
			||||||
                setSession('menus', loginRes.menus);
 | 
					                setSession('menus', loginRes.menus);
 | 
				
			||||||
            } catch (e) {
 | 
					            } catch (e: any) {
 | 
				
			||||||
                state.loading.signIn = false;
 | 
					                state.loading.signIn = false;
 | 
				
			||||||
                state.loginForm.captcha = '';
 | 
					                state.loginForm.captcha = '';
 | 
				
			||||||
 | 
					                // 密码强度不足
 | 
				
			||||||
 | 
					                if (e.code && e.code == 401) {
 | 
				
			||||||
 | 
					                    state.changePwdDialog.form.username = state.loginForm.username;
 | 
				
			||||||
 | 
					                    state.changePwdDialog.form.oldPassword = originPwd;
 | 
				
			||||||
 | 
					                    state.changePwdDialog.form.newPassword = '';
 | 
				
			||||||
 | 
					                    state.changePwdDialog.visible = true;
 | 
				
			||||||
 | 
					                } else {
 | 
				
			||||||
                    getCaptcha();
 | 
					                    getCaptcha();
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
                return;
 | 
					                return;
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
            // 用户信息
 | 
					            // 用户信息
 | 
				
			||||||
@@ -174,11 +229,44 @@ export default defineComponent({
 | 
				
			|||||||
            }, 300);
 | 
					            }, 300);
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const changePwd = () => {
 | 
				
			||||||
 | 
					            changePwdFormRef.value.validate(async (valid: boolean) => {
 | 
				
			||||||
 | 
					                if (!valid) {
 | 
				
			||||||
 | 
					                    return false;
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					                try {
 | 
				
			||||||
 | 
					                    state.loading.changePwd = true;
 | 
				
			||||||
 | 
					                    const form = state.changePwdDialog.form;
 | 
				
			||||||
 | 
					                    const changePwdReq: any = { ...form };
 | 
				
			||||||
 | 
					                    changePwdReq.oldPassword = await RsaEncrypt(form.oldPassword);
 | 
				
			||||||
 | 
					                    changePwdReq.newPassword = await RsaEncrypt(form.newPassword);
 | 
				
			||||||
 | 
					                    await openApi.changePwd(changePwdReq);
 | 
				
			||||||
 | 
					                    ElMessage.success('密码修改成功, 新密码已填充至登录密码框');
 | 
				
			||||||
 | 
					                    state.loginForm.password = state.changePwdDialog.form.newPassword;
 | 
				
			||||||
 | 
					                    state.changePwdDialog.visible = false;
 | 
				
			||||||
 | 
					                    getCaptcha();
 | 
				
			||||||
 | 
					                } finally {
 | 
				
			||||||
 | 
					                    state.loading.changePwd = false;
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            });
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const cancelChangePwd = () => {
 | 
				
			||||||
 | 
					            state.changePwdDialog.visible = false;
 | 
				
			||||||
 | 
					            state.changePwdDialog.form.newPassword = '';
 | 
				
			||||||
 | 
					            state.changePwdDialog.form.oldPassword = '';
 | 
				
			||||||
 | 
					            state.changePwdDialog.form.username = '';
 | 
				
			||||||
 | 
					            getCaptcha();
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return {
 | 
					        return {
 | 
				
			||||||
            getCaptcha,
 | 
					            getCaptcha,
 | 
				
			||||||
            currentTime,
 | 
					            currentTime,
 | 
				
			||||||
            loginFormRef,
 | 
					            loginFormRef,
 | 
				
			||||||
 | 
					            changePwdFormRef,
 | 
				
			||||||
            login,
 | 
					            login,
 | 
				
			||||||
 | 
					            changePwd,
 | 
				
			||||||
 | 
					            cancelChangePwd,
 | 
				
			||||||
            ...toRefs(state),
 | 
					            ...toRefs(state),
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
    },
 | 
					    },
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,7 +1,7 @@
 | 
				
			|||||||
<template>
 | 
					<template>
 | 
				
			||||||
    <div>
 | 
					    <div>
 | 
				
			||||||
        <el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :close-on-click-modal="false" :destroy-on-close="true" width="35%">
 | 
					        <el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :close-on-click-modal="false" :destroy-on-close="true" width="38%">
 | 
				
			||||||
            <el-form :model="form" ref="dbForm" :rules="rules" label-width="85px">
 | 
					            <el-form :model="form" ref="dbForm" :rules="rules" label-width="95px">
 | 
				
			||||||
                <el-form-item prop="projectId" label="项目:" required>
 | 
					                <el-form-item prop="projectId" label="项目:" required>
 | 
				
			||||||
                    <el-select style="width: 100%" v-model="form.projectId" placeholder="请选择项目" @change="changeProject" filterable>
 | 
					                    <el-select style="width: 100%" v-model="form.projectId" placeholder="请选择项目" @change="changeProject" filterable>
 | 
				
			||||||
                        <el-option v-for="item in projects" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
 | 
					                        <el-option v-for="item in projects" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
 | 
				
			||||||
@@ -19,13 +19,14 @@
 | 
				
			|||||||
                <el-form-item prop="type" label="类型:" required>
 | 
					                <el-form-item prop="type" label="类型:" required>
 | 
				
			||||||
                    <el-select style="width: 100%" v-model="form.type" placeholder="请选择数据库类型">
 | 
					                    <el-select style="width: 100%" v-model="form.type" placeholder="请选择数据库类型">
 | 
				
			||||||
                        <el-option key="item.id" label="mysql" value="mysql"> </el-option>
 | 
					                        <el-option key="item.id" label="mysql" value="mysql"> </el-option>
 | 
				
			||||||
 | 
					                        <el-option key="item.id" label="postgres" value="postgres"> </el-option>
 | 
				
			||||||
                    </el-select>
 | 
					                    </el-select>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
                <el-form-item prop="host" label="host:" required>
 | 
					                <el-form-item prop="host" label="host:" required>
 | 
				
			||||||
                    <el-input v-model.trim="form.host" placeholder="请输入主机ip" auto-complete="off"></el-input>
 | 
					                    <el-input v-model.trim="form.host" placeholder="请输入主机ip" auto-complete="off"></el-input>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
                <el-form-item prop="port" label="port:" required>
 | 
					                <el-form-item prop="port" label="port:" required>
 | 
				
			||||||
                    <el-input type="number" v-model.trim="form.port" placeholder="请输入端口"></el-input>
 | 
					                    <el-input type="number" v-model.number="form.port" placeholder="请输入端口"></el-input>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
                <el-form-item prop="username" label="用户名:" required>
 | 
					                <el-form-item prop="username" label="用户名:" required>
 | 
				
			||||||
                    <el-input v-model.trim="form.username" placeholder="请输入用户名"></el-input>
 | 
					                    <el-input v-model.trim="form.username" placeholder="请输入用户名"></el-input>
 | 
				
			||||||
@@ -39,6 +40,9 @@
 | 
				
			|||||||
                        autocomplete="new-password"
 | 
					                        autocomplete="new-password"
 | 
				
			||||||
                    ></el-input>
 | 
					                    ></el-input>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					                <el-form-item prop="params" label="连接参数:">
 | 
				
			||||||
 | 
					                    <el-input v-model="form.params" placeholder="其他连接参数,形如: key1=value1&key2=value2"></el-input>
 | 
				
			||||||
 | 
					                </el-form-item>
 | 
				
			||||||
                <el-form-item prop="database" label="数据库名:" required>
 | 
					                <el-form-item prop="database" label="数据库名:" required>
 | 
				
			||||||
                    <el-tag
 | 
					                    <el-tag
 | 
				
			||||||
                        v-for="db in databaseList"
 | 
					                        v-for="db in databaseList"
 | 
				
			||||||
@@ -82,6 +86,7 @@ import { projectApi } from '../project/api.ts';
 | 
				
			|||||||
import { ElMessage } from 'element-plus';
 | 
					import { ElMessage } from 'element-plus';
 | 
				
			||||||
import type { ElInput } from 'element-plus';
 | 
					import type { ElInput } from 'element-plus';
 | 
				
			||||||
import { notBlank } from '@/common/assert';
 | 
					import { notBlank } from '@/common/assert';
 | 
				
			||||||
 | 
					import { RsaEncrypt } from '@/common/rsa';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'DbEdit',
 | 
					    name: 'DbEdit',
 | 
				
			||||||
@@ -116,6 +121,7 @@ export default defineComponent({
 | 
				
			|||||||
                port: 3306,
 | 
					                port: 3306,
 | 
				
			||||||
                username: null,
 | 
					                username: null,
 | 
				
			||||||
                password: null,
 | 
					                password: null,
 | 
				
			||||||
 | 
					                params: null,
 | 
				
			||||||
                database: '',
 | 
					                database: '',
 | 
				
			||||||
                project: null,
 | 
					                project: null,
 | 
				
			||||||
                projectId: null,
 | 
					                projectId: null,
 | 
				
			||||||
@@ -173,13 +179,6 @@ export default defineComponent({
 | 
				
			|||||||
                        trigger: ['change', 'blur'],
 | 
					                        trigger: ['change', 'blur'],
 | 
				
			||||||
                    },
 | 
					                    },
 | 
				
			||||||
                ],
 | 
					                ],
 | 
				
			||||||
                // password: [
 | 
					 | 
				
			||||||
                //     {
 | 
					 | 
				
			||||||
                //         required: true,
 | 
					 | 
				
			||||||
                //         message: '请输入密码',
 | 
					 | 
				
			||||||
                //         trigger: ['change', 'blur'],
 | 
					 | 
				
			||||||
                //     },
 | 
					 | 
				
			||||||
                // ],
 | 
					 | 
				
			||||||
                database: [
 | 
					                database: [
 | 
				
			||||||
                    {
 | 
					                    {
 | 
				
			||||||
                        required: true,
 | 
					                        required: true,
 | 
				
			||||||
@@ -261,10 +260,11 @@ export default defineComponent({
 | 
				
			|||||||
            if (!state.form.id) {
 | 
					            if (!state.form.id) {
 | 
				
			||||||
                notBlank(state.form.password, '新增操作,密码不可为空');
 | 
					                notBlank(state.form.password, '新增操作,密码不可为空');
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
            dbForm.value.validate((valid: boolean) => {
 | 
					            dbForm.value.validate(async (valid: boolean) => {
 | 
				
			||||||
                if (valid) {
 | 
					                if (valid) {
 | 
				
			||||||
                    state.form.port = Number.parseInt(state.form.port as any);
 | 
					                    const reqForm = { ...state.form };
 | 
				
			||||||
                    dbApi.saveDb.request(state.form).then(() => {
 | 
					                    reqForm.password = await RsaEncrypt(reqForm.password);
 | 
				
			||||||
 | 
					                    dbApi.saveDb.request(reqForm).then(() => {
 | 
				
			||||||
                        ElMessage.success('保存成功');
 | 
					                        ElMessage.success('保存成功');
 | 
				
			||||||
                        emit('val-change', state.form);
 | 
					                        emit('val-change', state.form);
 | 
				
			||||||
                        state.btnLoading = true;
 | 
					                        state.btnLoading = true;
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -20,15 +20,15 @@
 | 
				
			|||||||
                        </el-radio>
 | 
					                        </el-radio>
 | 
				
			||||||
                    </template>
 | 
					                    </template>
 | 
				
			||||||
                </el-table-column>
 | 
					                </el-table-column>
 | 
				
			||||||
                <el-table-column prop="project" label="项目" min-width="100"></el-table-column>
 | 
					                <el-table-column prop="project" label="项目" min-width="100" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
                <el-table-column prop="env" label="环境" min-width="100"></el-table-column>
 | 
					                <el-table-column prop="env" label="环境" min-width="100"></el-table-column>
 | 
				
			||||||
                <el-table-column prop="name" label="名称" min-width="200"></el-table-column>
 | 
					                <el-table-column prop="name" label="名称" min-width="160" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
                <el-table-column min-width="160" label="host:port">
 | 
					                <el-table-column min-width="170" label="host:port" show-overflow-tooltip>
 | 
				
			||||||
                    <template #default="scope">
 | 
					                    <template #default="scope">
 | 
				
			||||||
                        {{ `${scope.row.host}:${scope.row.port}` }}
 | 
					                        {{ `${scope.row.host}:${scope.row.port}` }}
 | 
				
			||||||
                    </template>
 | 
					                    </template>
 | 
				
			||||||
                </el-table-column>
 | 
					                </el-table-column>
 | 
				
			||||||
                <el-table-column prop="type" label="类型" min-width="80"></el-table-column>
 | 
					                <el-table-column prop="type" label="类型" min-width="90"></el-table-column>
 | 
				
			||||||
                <el-table-column prop="database" label="数据库" min-width="160">
 | 
					                <el-table-column prop="database" label="数据库" min-width="160">
 | 
				
			||||||
                    <template #default="scope">
 | 
					                    <template #default="scope">
 | 
				
			||||||
                        <el-tag
 | 
					                        <el-tag
 | 
				
			||||||
@@ -72,9 +72,35 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        <el-dialog width="75%" :title="`${db} 表信息`" :before-close="closeTableInfo" v-model="tableInfoDialog.visible">
 | 
					        <el-dialog width="75%" :title="`${db} 表信息`" :before-close="closeTableInfo" v-model="tableInfoDialog.visible">
 | 
				
			||||||
            <el-row class="mb10">
 | 
					            <el-row class="mb10">
 | 
				
			||||||
 | 
					                <el-popover v-model:visible="showDumpInfo" :width="470" placement="right">
 | 
				
			||||||
 | 
					                    <template #reference>
 | 
				
			||||||
 | 
					                        <el-button class="ml5" type="success" size="small" @click="showDumpInfo = !showDumpInfo">导出</el-button>
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                    <el-form-item label="导出内容: ">
 | 
				
			||||||
 | 
					                        <el-radio-group v-model="dumpInfo.type">
 | 
				
			||||||
 | 
					                            <el-radio :label="1" size="small">结构</el-radio>
 | 
				
			||||||
 | 
					                            <el-radio :label="2" size="small">数据</el-radio>
 | 
				
			||||||
 | 
					                            <el-radio :label="3" size="small">结构+数据</el-radio>
 | 
				
			||||||
 | 
					                        </el-radio-group>
 | 
				
			||||||
 | 
					                    </el-form-item>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                    <el-form-item label="导出表: ">
 | 
				
			||||||
 | 
					                        <el-table @selection-change="handleDumpTableSelectionChange" max-height="300" size="small" :data="tableInfoDialog.infos">
 | 
				
			||||||
 | 
					                            <el-table-column type="selection" width="45" />
 | 
				
			||||||
 | 
					                            <el-table-column property="tableName" label="表名" min-width="150" show-overflow-tooltip> </el-table-column>
 | 
				
			||||||
 | 
					                            <el-table-column property="tableComment" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
 | 
					                        </el-table>
 | 
				
			||||||
 | 
					                    </el-form-item>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                    <div style="text-align: right">
 | 
				
			||||||
 | 
					                        <el-button @click="showDumpInfo = false" size="small">取消</el-button>
 | 
				
			||||||
 | 
					                        <el-button @click="dump(db)" type="success" size="small">确定</el-button>
 | 
				
			||||||
 | 
					                    </div>
 | 
				
			||||||
 | 
					                </el-popover>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                <el-button type="primary" size="small" @click="tableCreateDialog.visible = true">创建表</el-button>
 | 
					                <el-button type="primary" size="small" @click="tableCreateDialog.visible = true">创建表</el-button>
 | 
				
			||||||
            </el-row>
 | 
					            </el-row>
 | 
				
			||||||
            <el-table border stripe :data="tableInfoDialog.infos" size="small">
 | 
					            <el-table v-loading="tableInfoDialog.loading" border stripe :data="tableInfoDialog.infos" size="small">
 | 
				
			||||||
                <el-table-column property="tableName" label="表名" min-width="150" show-overflow-tooltip></el-table-column>
 | 
					                <el-table-column property="tableName" label="表名" min-width="150" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
                <el-table-column property="tableComment" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
 | 
					                <el-table-column property="tableComment" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
                <el-table-column
 | 
					                <el-table-column
 | 
				
			||||||
@@ -198,6 +224,7 @@
 | 
				
			|||||||
                <el-table-column prop="columnName" label="列名" show-overflow-tooltip> </el-table-column>
 | 
					                <el-table-column prop="columnName" label="列名" show-overflow-tooltip> </el-table-column>
 | 
				
			||||||
                <el-table-column prop="seqInIndex" label="列序列号" show-overflow-tooltip> </el-table-column>
 | 
					                <el-table-column prop="seqInIndex" label="列序列号" show-overflow-tooltip> </el-table-column>
 | 
				
			||||||
                <el-table-column prop="indexType" label="类型"> </el-table-column>
 | 
					                <el-table-column prop="indexType" label="类型"> </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="indexComment" label="备注" min-width="230" show-overflow-tooltip> </el-table-column>
 | 
				
			||||||
            </el-table>
 | 
					            </el-table>
 | 
				
			||||||
        </el-dialog>
 | 
					        </el-dialog>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -226,6 +253,10 @@ import { dbApi } from './api';
 | 
				
			|||||||
import enums from './enums';
 | 
					import enums from './enums';
 | 
				
			||||||
import { projectApi } from '../project/api.ts';
 | 
					import { projectApi } from '../project/api.ts';
 | 
				
			||||||
import SqlExecBox from './component/SqlExecBox.ts';
 | 
					import SqlExecBox from './component/SqlExecBox.ts';
 | 
				
			||||||
 | 
					import config from '@/common/config';
 | 
				
			||||||
 | 
					import { getSession } from '@/common/utils/storage';
 | 
				
			||||||
 | 
					import { isTrue } from '@/common/assert';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'DbList',
 | 
					    name: 'DbList',
 | 
				
			||||||
    components: {
 | 
					    components: {
 | 
				
			||||||
@@ -255,6 +286,13 @@ export default defineComponent({
 | 
				
			|||||||
            },
 | 
					            },
 | 
				
			||||||
            datas: [],
 | 
					            datas: [],
 | 
				
			||||||
            total: 0,
 | 
					            total: 0,
 | 
				
			||||||
 | 
					            showDumpInfo: false,
 | 
				
			||||||
 | 
					            dumpInfo: {
 | 
				
			||||||
 | 
					                id: 0,
 | 
				
			||||||
 | 
					                db: '',
 | 
				
			||||||
 | 
					                type: 3,
 | 
				
			||||||
 | 
					                tables: [],
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
            // sql执行记录弹框
 | 
					            // sql执行记录弹框
 | 
				
			||||||
            sqlExecLogDialog: {
 | 
					            sqlExecLogDialog: {
 | 
				
			||||||
                title: '',
 | 
					                title: '',
 | 
				
			||||||
@@ -276,6 +314,7 @@ export default defineComponent({
 | 
				
			|||||||
            },
 | 
					            },
 | 
				
			||||||
            chooseTableName: '',
 | 
					            chooseTableName: '',
 | 
				
			||||||
            tableInfoDialog: {
 | 
					            tableInfoDialog: {
 | 
				
			||||||
 | 
					                loading: false,
 | 
				
			||||||
                visible: false,
 | 
					                visible: false,
 | 
				
			||||||
                infos: [],
 | 
					                infos: [],
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
@@ -303,7 +342,7 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        onMounted(async () => {
 | 
					        onMounted(async () => {
 | 
				
			||||||
            search();
 | 
					            search();
 | 
				
			||||||
            state.projects = (await projectApi.projects.request({ pageNum: 1, pageSize: 100 })).list;
 | 
					            state.projects = await projectApi.accountProjects.request(null);
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const choose = (item: any) => {
 | 
					        const choose = (item: any) => {
 | 
				
			||||||
@@ -391,6 +430,29 @@ export default defineComponent({
 | 
				
			|||||||
            searchSqlExecLog();
 | 
					            searchSqlExecLog();
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        /**
 | 
				
			||||||
 | 
					         * 选择导出数据库表
 | 
				
			||||||
 | 
					         */
 | 
				
			||||||
 | 
					        const handleDumpTableSelectionChange = (vals: any) => {
 | 
				
			||||||
 | 
					            state.dumpInfo.tables = vals.map((x: any) => x.tableName);
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        /**
 | 
				
			||||||
 | 
					         * 数据库信息导出
 | 
				
			||||||
 | 
					         */
 | 
				
			||||||
 | 
					        const dump = (db: string) => {
 | 
				
			||||||
 | 
					            isTrue(state.dumpInfo.tables.length > 0, '请选择要导出的表');
 | 
				
			||||||
 | 
					            const a = document.createElement('a');
 | 
				
			||||||
 | 
					            a.setAttribute(
 | 
				
			||||||
 | 
					                'href',
 | 
				
			||||||
 | 
					                `${config.baseApiUrl}/dbs/${state.dbId}/dump?db=${db}&type=${state.dumpInfo.type}&tables=${state.dumpInfo.tables.join(
 | 
				
			||||||
 | 
					                    ','
 | 
				
			||||||
 | 
					                )}&token=${getSession('token')}`
 | 
				
			||||||
 | 
					            );
 | 
				
			||||||
 | 
					            a.click();
 | 
				
			||||||
 | 
					            state.showDumpInfo = false;
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const onShowRollbackSql = async (sqlExecLog: any) => {
 | 
					        const onShowRollbackSql = async (sqlExecLog: any) => {
 | 
				
			||||||
            const columns = await dbApi.columnMetadata.request({ id: sqlExecLog.dbId, db: sqlExecLog.db, tableName: sqlExecLog.table });
 | 
					            const columns = await dbApi.columnMetadata.request({ id: sqlExecLog.dbId, db: sqlExecLog.db, tableName: sqlExecLog.table });
 | 
				
			||||||
            const primaryKey = columns[0].columnName;
 | 
					            const primaryKey = columns[0].columnName;
 | 
				
			||||||
@@ -434,13 +496,19 @@ export default defineComponent({
 | 
				
			|||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const showTableInfo = async (row: any, db: string) => {
 | 
					        const showTableInfo = async (row: any, db: string) => {
 | 
				
			||||||
 | 
					            state.tableInfoDialog.loading = true;
 | 
				
			||||||
 | 
					            state.tableInfoDialog.visible = true;
 | 
				
			||||||
 | 
					            try {
 | 
				
			||||||
                state.tableInfoDialog.infos = await dbApi.tableInfos.request({ id: row.id, db });
 | 
					                state.tableInfoDialog.infos = await dbApi.tableInfos.request({ id: row.id, db });
 | 
				
			||||||
                state.dbId = row.id;
 | 
					                state.dbId = row.id;
 | 
				
			||||||
                state.db = db;
 | 
					                state.db = db;
 | 
				
			||||||
            state.tableInfoDialog.visible = true;
 | 
					            } finally {
 | 
				
			||||||
 | 
					                state.tableInfoDialog.loading = false;
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const closeTableInfo = () => {
 | 
					        const closeTableInfo = () => {
 | 
				
			||||||
 | 
					            state.showDumpInfo = false;
 | 
				
			||||||
            state.tableInfoDialog.visible = false;
 | 
					            state.tableInfoDialog.visible = false;
 | 
				
			||||||
            state.tableInfoDialog.infos = [];
 | 
					            state.tableInfoDialog.infos = [];
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
@@ -510,6 +578,8 @@ export default defineComponent({
 | 
				
			|||||||
            valChange,
 | 
					            valChange,
 | 
				
			||||||
            deleteDb,
 | 
					            deleteDb,
 | 
				
			||||||
            onShowSqlExec,
 | 
					            onShowSqlExec,
 | 
				
			||||||
 | 
					            handleDumpTableSelectionChange,
 | 
				
			||||||
 | 
					            dump,
 | 
				
			||||||
            onBeforeCloseSqlExecDialog,
 | 
					            onBeforeCloseSqlExecDialog,
 | 
				
			||||||
            handleSqlExecPageChange,
 | 
					            handleSqlExecPageChange,
 | 
				
			||||||
            searchSqlExecLog,
 | 
					            searchSqlExecLog,
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -190,7 +190,7 @@
 | 
				
			|||||||
                        @cell-dblclick="cellClick"
 | 
					                        @cell-dblclick="cellClick"
 | 
				
			||||||
                        @sort-change="onTableSortChange"
 | 
					                        @sort-change="onTableSortChange"
 | 
				
			||||||
                        @selection-change="onDataSelectionChange"
 | 
					                        @selection-change="onDataSelectionChange"
 | 
				
			||||||
                        :data="dt.execRes.data"
 | 
					                        :data="dt.datas"
 | 
				
			||||||
                        size="small"
 | 
					                        size="small"
 | 
				
			||||||
                        :max-height="dataTabsTableHeight"
 | 
					                        :max-height="dataTabsTableHeight"
 | 
				
			||||||
                        v-loading="dt.loading"
 | 
					                        v-loading="dt.loading"
 | 
				
			||||||
@@ -200,12 +200,12 @@
 | 
				
			|||||||
                        border
 | 
					                        border
 | 
				
			||||||
                        class="mt5"
 | 
					                        class="mt5"
 | 
				
			||||||
                    >
 | 
					                    >
 | 
				
			||||||
                        <el-table-column v-if="dt.execRes.tableColumn.length > 0" type="selection" width="35" />
 | 
					                        <el-table-column v-if="dt.datas.length > 0" type="selection" width="35" />
 | 
				
			||||||
                        <el-table-column
 | 
					                        <el-table-column
 | 
				
			||||||
                            min-width="100"
 | 
					                            min-width="100"
 | 
				
			||||||
                            :width="flexColumnWidth(item, dt.execRes.data)"
 | 
					                            :width="flexColumnWidth(item, dt.datas)"
 | 
				
			||||||
                            align="center"
 | 
					                            align="center"
 | 
				
			||||||
                            v-for="item in dt.execRes.tableColumn"
 | 
					                            v-for="item in dt.columnNames"
 | 
				
			||||||
                            :key="item"
 | 
					                            :key="item"
 | 
				
			||||||
                            :prop="item"
 | 
					                            :prop="item"
 | 
				
			||||||
                            :label="item"
 | 
					                            :label="item"
 | 
				
			||||||
@@ -215,12 +215,21 @@
 | 
				
			|||||||
                            <template #header>
 | 
					                            <template #header>
 | 
				
			||||||
                                <el-tooltip raw-content placement="top" effect="customized">
 | 
					                                <el-tooltip raw-content placement="top" effect="customized">
 | 
				
			||||||
                                    <template #content> {{ getColumnTip(dt.name, item) }} </template>
 | 
					                                    <template #content> {{ getColumnTip(dt.name, item) }} </template>
 | 
				
			||||||
                                    <!-- <el-icon><question-filled /></el-icon> -->
 | 
					 | 
				
			||||||
                                    {{ item }}
 | 
					                                    {{ item }}
 | 
				
			||||||
                                </el-tooltip>
 | 
					                                </el-tooltip>
 | 
				
			||||||
                            </template>
 | 
					                            </template>
 | 
				
			||||||
                        </el-table-column>
 | 
					                        </el-table-column>
 | 
				
			||||||
                    </el-table>
 | 
					                    </el-table>
 | 
				
			||||||
 | 
					                    <el-row type="flex" class="mt5" justify="center">
 | 
				
			||||||
 | 
					                        <el-pagination
 | 
				
			||||||
 | 
					                            small
 | 
				
			||||||
 | 
					                            :total="dt.count"
 | 
				
			||||||
 | 
					                            @current-change="handlePageChange(dt)"
 | 
				
			||||||
 | 
					                            layout="prev, pager, next, total, jumper"
 | 
				
			||||||
 | 
					                            v-model:current-page="dt.pageNum"
 | 
				
			||||||
 | 
					                            :page-size="defalutLimit"
 | 
				
			||||||
 | 
					                        ></el-pagination>
 | 
				
			||||||
 | 
					                    </el-row>
 | 
				
			||||||
                </el-tab-pane>
 | 
					                </el-tab-pane>
 | 
				
			||||||
            </el-tabs>
 | 
					            </el-tabs>
 | 
				
			||||||
        </el-container>
 | 
					        </el-container>
 | 
				
			||||||
@@ -263,15 +272,15 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        const state = reactive({
 | 
					        const state = reactive({
 | 
				
			||||||
            token: token,
 | 
					            token: token,
 | 
				
			||||||
            defalutLimit: 25, // 默认查询数量
 | 
					            defalutLimit: 20, // 默认查询数量
 | 
				
			||||||
            dbs: [], // 数据库实例列表
 | 
					            dbs: [], // 数据库实例列表
 | 
				
			||||||
            databaseList: [], // 数据库实例拥有的数据库列表,1数据库实例  -> 多数据库
 | 
					            databaseList: [], // 数据库实例拥有的数据库列表,1数据库实例  -> 多数据库
 | 
				
			||||||
            db: '', // 当前操作的数据库
 | 
					            db: '', // 当前操作的数据库
 | 
				
			||||||
 | 
					            dbType: '',
 | 
				
			||||||
            tables: [],
 | 
					            tables: [],
 | 
				
			||||||
            dbId: null, // 当前选中操作的数据库实例
 | 
					            dbId: null, // 当前选中操作的数据库实例
 | 
				
			||||||
            tableName: '',
 | 
					            tableName: '',
 | 
				
			||||||
            tableMetadata: [],
 | 
					            tableMetadata: [],
 | 
				
			||||||
            columnMetadata: [],
 | 
					 | 
				
			||||||
            sqlName: '', // 当前sql模板名
 | 
					            sqlName: '', // 当前sql模板名
 | 
				
			||||||
            sqlNames: [], // 所有sql模板名
 | 
					            sqlNames: [], // 所有sql模板名
 | 
				
			||||||
            activeName: 'Query',
 | 
					            activeName: 'Query',
 | 
				
			||||||
@@ -356,7 +365,7 @@ export default defineComponent({
 | 
				
			|||||||
        const setHeight = () => {
 | 
					        const setHeight = () => {
 | 
				
			||||||
            // 默认300px
 | 
					            // 默认300px
 | 
				
			||||||
            codemirror.setSize('auto', `${window.innerHeight - 538}px`);
 | 
					            codemirror.setSize('auto', `${window.innerHeight - 538}px`);
 | 
				
			||||||
            state.dataTabsTableHeight = window.innerHeight - 258;
 | 
					            state.dataTabsTableHeight = window.innerHeight - 258 - 33;
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        /**
 | 
					        /**
 | 
				
			||||||
@@ -457,33 +466,6 @@ export default defineComponent({
 | 
				
			|||||||
                sql: sql.trim(),
 | 
					                sql: sql.trim(),
 | 
				
			||||||
                remark,
 | 
					                remark,
 | 
				
			||||||
            });
 | 
					            });
 | 
				
			||||||
            // const sqlTrim = sql.trim();
 | 
					 | 
				
			||||||
            // let remark = '';
 | 
					 | 
				
			||||||
            // let canRun = true;
 | 
					 | 
				
			||||||
            // const needRemark = ['update', 'UPDATE', 'delete', 'DELETE', 'INSERT', 'insert'].indexOf(sqlTrim.split(' ')[0]);
 | 
					 | 
				
			||||||
            // if (needRemark) {
 | 
					 | 
				
			||||||
            //     const res: any = await ElMessageBox.prompt('请输入备注', 'Tip', {
 | 
					 | 
				
			||||||
            //         confirmButtonText: '确定',
 | 
					 | 
				
			||||||
            //         cancelButtonText: '取消',
 | 
					 | 
				
			||||||
            //     });
 | 
					 | 
				
			||||||
            //     remark = res.value;
 | 
					 | 
				
			||||||
            //     if (!remark) {
 | 
					 | 
				
			||||||
            //         canRun = false;
 | 
					 | 
				
			||||||
            //     }
 | 
					 | 
				
			||||||
            // }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
            // if (!canRun) {
 | 
					 | 
				
			||||||
            //     return;
 | 
					 | 
				
			||||||
            // }
 | 
					 | 
				
			||||||
            // try {
 | 
					 | 
				
			||||||
            //     state.queryTab.loading = true;
 | 
					 | 
				
			||||||
            //     return await dbApi.sqlExec.request({
 | 
					 | 
				
			||||||
            //         id: state.dbId,
 | 
					 | 
				
			||||||
            //         db: state.db,
 | 
					 | 
				
			||||||
            //         sql: sqlTrim,
 | 
					 | 
				
			||||||
            //         remark,
 | 
					 | 
				
			||||||
            //     });
 | 
					 | 
				
			||||||
            // } catch (e: any) {}
 | 
					 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const removeDataTab = (targetName: string) => {
 | 
					        const removeDataTab = (targetName: string) => {
 | 
				
			||||||
@@ -533,7 +515,7 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        // 获取sql文件上传执行url
 | 
					        // 获取sql文件上传执行url
 | 
				
			||||||
        const getUploadSqlFileUrl = () => {
 | 
					        const getUploadSqlFileUrl = () => {
 | 
				
			||||||
            return `${config.baseApiUrl}/dbs/${state.dbId}/exec-sql-file`;
 | 
					            return `${config.baseApiUrl}/dbs/${state.dbId}/exec-sql-file?db=${state.db}`;
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const flexColumnWidth = (str: any, tableData: any, flag = 'equal') => {
 | 
					        const flexColumnWidth = (str: any, tableData: any, flag = 'equal') => {
 | 
				
			||||||
@@ -641,7 +623,9 @@ export default defineComponent({
 | 
				
			|||||||
         */
 | 
					         */
 | 
				
			||||||
        const changeDbInstance = (dbId: any) => {
 | 
					        const changeDbInstance = (dbId: any) => {
 | 
				
			||||||
            state.db = '';
 | 
					            state.db = '';
 | 
				
			||||||
            state.databaseList = (state.dbs.find((e: any) => e.id == dbId) as any).database.split(' ');
 | 
					            const dbInfo = state.dbs.find((e: any) => e.id == dbId) as any;
 | 
				
			||||||
 | 
					            state.dbType = dbInfo.type;
 | 
				
			||||||
 | 
					            state.databaseList = dbInfo.database.split(' ');
 | 
				
			||||||
            clearDb();
 | 
					            clearDb();
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -673,8 +657,6 @@ export default defineComponent({
 | 
				
			|||||||
            if (tableName == '') {
 | 
					            if (tableName == '') {
 | 
				
			||||||
                return;
 | 
					                return;
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
            state.columnMetadata = (await getColumns(tableName)) as any;
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
            if (!execSelectSql) {
 | 
					            if (!execSelectSql) {
 | 
				
			||||||
                return;
 | 
					                return;
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
@@ -691,40 +673,17 @@ export default defineComponent({
 | 
				
			|||||||
            tab = {
 | 
					            tab = {
 | 
				
			||||||
                label: tableName,
 | 
					                label: tableName,
 | 
				
			||||||
                name: tableName,
 | 
					                name: tableName,
 | 
				
			||||||
                execRes: {
 | 
					                datas: [],
 | 
				
			||||||
                    tableColumn: [],
 | 
					                columnNames: [],
 | 
				
			||||||
                    data: [],
 | 
					                pageNum: 1,
 | 
				
			||||||
                },
 | 
					                count: 0,
 | 
				
			||||||
                querySql: getDefaultSelectSql(tableName),
 | 
					 | 
				
			||||||
            };
 | 
					            };
 | 
				
			||||||
 | 
					            tab.columnNames = await getColumnNames(tableName);
 | 
				
			||||||
            state.dataTabs[tableName] = tab;
 | 
					            state.dataTabs[tableName] = tab;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            state.dataTabs[tableName].execRes.tableColumn = [];
 | 
					 | 
				
			||||||
            state.dataTabs[tableName].execRes.data = [];
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
            onRefresh(tableName);
 | 
					            onRefresh(tableName);
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        /**
 | 
					 | 
				
			||||||
         * 获取默认查询语句
 | 
					 | 
				
			||||||
         */
 | 
					 | 
				
			||||||
        const getDefaultSelectSql = (tableName: string, where: string = '', orderBy: string = '') => {
 | 
					 | 
				
			||||||
            return `SELECT * FROM \`${tableName}\` ${where ? 'WHERE ' + where : ''} ${orderBy ? orderBy : ''} LIMIT ${state.defalutLimit}`;
 | 
					 | 
				
			||||||
        };
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        const selectByCondition = async (tableName: string, condition: string) => {
 | 
					 | 
				
			||||||
            notEmpty(condition, '条件不能为空');
 | 
					 | 
				
			||||||
            state.dataTabs[tableName].loading = true;
 | 
					 | 
				
			||||||
            try {
 | 
					 | 
				
			||||||
                const colAndData: any = await runSql(getDefaultSelectSql(tableName, condition));
 | 
					 | 
				
			||||||
                state.dataTabs[tableName].execRes.tableColumn = colAndData.colNames;
 | 
					 | 
				
			||||||
                state.dataTabs[tableName].execRes.data = colAndData.res;
 | 
					 | 
				
			||||||
                state.dataTabs[tableName].loading = false;
 | 
					 | 
				
			||||||
            } catch (err) {
 | 
					 | 
				
			||||||
                state.dataTabs[tableName].loading = false;
 | 
					 | 
				
			||||||
            }
 | 
					 | 
				
			||||||
        };
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        /**
 | 
					        /**
 | 
				
			||||||
         * 获取表的所有列信息
 | 
					         * 获取表的所有列信息
 | 
				
			||||||
         */
 | 
					         */
 | 
				
			||||||
@@ -748,6 +707,11 @@ export default defineComponent({
 | 
				
			|||||||
            return tableMap.get(tableName);
 | 
					            return tableMap.get(tableName);
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const getColumnNames = async (tableName: string) => {
 | 
				
			||||||
 | 
					            const columns = await getColumns(tableName);
 | 
				
			||||||
 | 
					            return columns.map((t: any) => t.columnName);
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        /**
 | 
					        /**
 | 
				
			||||||
         * 条件查询,点击列信息后显示输入对应的值
 | 
					         * 条件查询,点击列信息后显示输入对应的值
 | 
				
			||||||
         */
 | 
					         */
 | 
				
			||||||
@@ -773,13 +737,75 @@ export default defineComponent({
 | 
				
			|||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const onRefresh = async (tableName: string) => {
 | 
					        const onRefresh = async (tableName: string) => {
 | 
				
			||||||
 | 
					            const dataTab = state.dataTabs[tableName];
 | 
				
			||||||
            // 查询条件置空
 | 
					            // 查询条件置空
 | 
				
			||||||
            state.dataTabs[tableName].condition = '';
 | 
					            dataTab.condition = '';
 | 
				
			||||||
            state.dataTabs[tableName].loading = true;
 | 
					            dataTab.pageNum = 1;
 | 
				
			||||||
            const colAndData: any = await runSql(state.dataTabs[tableName].querySql);
 | 
					            setDataTabDatas(dataTab);
 | 
				
			||||||
            state.dataTabs[tableName].execRes.tableColumn = colAndData.colNames;
 | 
					        };
 | 
				
			||||||
            state.dataTabs[tableName].execRes.data = colAndData.res;
 | 
					
 | 
				
			||||||
            state.dataTabs[tableName].loading = false;
 | 
					        /**
 | 
				
			||||||
 | 
					         * 数据tab修改页数
 | 
				
			||||||
 | 
					         */
 | 
				
			||||||
 | 
					        const handlePageChange = async (dataTab: any) => {
 | 
				
			||||||
 | 
					            setDataTabDatas(dataTab);
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        /**
 | 
				
			||||||
 | 
					         * 根据条件查询数据
 | 
				
			||||||
 | 
					         */
 | 
				
			||||||
 | 
					        const selectByCondition = async (tableName: string, condition: string) => {
 | 
				
			||||||
 | 
					            notEmpty(condition, '条件不能为空');
 | 
				
			||||||
 | 
					            const dataTab = state.dataTabs[tableName];
 | 
				
			||||||
 | 
					            dataTab.pageNum = 1;
 | 
				
			||||||
 | 
					            setDataTabDatas(dataTab);
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        /**
 | 
				
			||||||
 | 
					         * 设置data tab的表数据
 | 
				
			||||||
 | 
					         */
 | 
				
			||||||
 | 
					        const setDataTabDatas = async (dataTab: any) => {
 | 
				
			||||||
 | 
					            dataTab.loading = true;
 | 
				
			||||||
 | 
					            try {
 | 
				
			||||||
 | 
					                dataTab.count = await getTableCount(dataTab.name, dataTab.condition);
 | 
				
			||||||
 | 
					                if (dataTab.count > 0) {
 | 
				
			||||||
 | 
					                    const colAndData: any = await runSql(getDefaultSelectSql(dataTab.name, dataTab.condition, dataTab.orderBy, dataTab.pageNum));
 | 
				
			||||||
 | 
					                    dataTab.datas = colAndData.res;
 | 
				
			||||||
 | 
					                } else {
 | 
				
			||||||
 | 
					                    dataTab.datas = [];
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            } finally {
 | 
				
			||||||
 | 
					                dataTab.loading = false;
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        /**
 | 
				
			||||||
 | 
					         * 获取表的统计数量
 | 
				
			||||||
 | 
					         */
 | 
				
			||||||
 | 
					        const getTableCount = async (tableName: string, condition: string = '') => {
 | 
				
			||||||
 | 
					            const countRes = await runSql(getDefaultCountSql(tableName, condition));
 | 
				
			||||||
 | 
					            return countRes.res[0].count;
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        /**
 | 
				
			||||||
 | 
					         * 获取默认查询语句
 | 
				
			||||||
 | 
					         */
 | 
				
			||||||
 | 
					        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};`
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					            if (state.dbType == 'postgres') {
 | 
				
			||||||
 | 
					                return `${baseSql} OFFSET ${(pageNum - 1) * state.defalutLimit} LIMIT ${state.defalutLimit};`
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					            return baseSql;
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        /**
 | 
				
			||||||
 | 
					         * 获取默认查询统计语句
 | 
				
			||||||
 | 
					         */
 | 
				
			||||||
 | 
					        const getDefaultCountSql = (tableName: string, where: string = '') => {
 | 
				
			||||||
 | 
					            return `SELECT COUNT(*) count FROM ${tableName} ${where ? 'WHERE ' + where : ''}`;
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        /**
 | 
					        /**
 | 
				
			||||||
@@ -801,7 +827,8 @@ export default defineComponent({
 | 
				
			|||||||
            const tableName = state.activeName;
 | 
					            const tableName = state.activeName;
 | 
				
			||||||
            const sortType = sort.order == 'descending' ? 'DESC' : 'ASC';
 | 
					            const sortType = sort.order == 'descending' ? 'DESC' : 'ASC';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            state.dataTabs[state.activeName].querySql = getDefaultSelectSql(tableName, '', `ORDER BY \`${sort.prop}\` ${sortType}`);
 | 
					            const orderBy = `ORDER BY ${sort.prop} ${sortType}`;
 | 
				
			||||||
 | 
					            state.dataTabs[state.activeName].orderBy = orderBy;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            onRefresh(tableName);
 | 
					            onRefresh(tableName);
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
@@ -892,7 +919,6 @@ export default defineComponent({
 | 
				
			|||||||
            state.tableName = '';
 | 
					            state.tableName = '';
 | 
				
			||||||
            state.nowTableName = '';
 | 
					            state.nowTableName = '';
 | 
				
			||||||
            state.tableMetadata = [];
 | 
					            state.tableMetadata = [];
 | 
				
			||||||
            state.columnMetadata = [];
 | 
					 | 
				
			||||||
            state.dataTabs = {};
 | 
					            state.dataTabs = {};
 | 
				
			||||||
            setCodermirrorValue('');
 | 
					            setCodermirrorValue('');
 | 
				
			||||||
            state.sqlNames = [];
 | 
					            state.sqlNames = [];
 | 
				
			||||||
@@ -927,10 +953,7 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
            promptExeSql(sql, null, () => {
 | 
					            promptExeSql(sql, null, () => {
 | 
				
			||||||
                if (!queryTab) {
 | 
					                if (!queryTab) {
 | 
				
			||||||
                    state.dataTabs[state.activeName].execRes.data = state.dataTabs[state.activeName].execRes.data.filter(
 | 
					                    onRefresh(state.activeName);
 | 
				
			||||||
                        (d: any) => !(deleteDatas.findIndex((x: any) => x[primaryKeyColumnName] == d[primaryKeyColumnName]) != -1)
 | 
					 | 
				
			||||||
                    );
 | 
					 | 
				
			||||||
                    state.dataTabs[state.activeName].selectionDatas = [];
 | 
					 | 
				
			||||||
                } else {
 | 
					                } else {
 | 
				
			||||||
                    state.queryTab.execRes.data = state.queryTab.execRes.data.filter(
 | 
					                    state.queryTab.execRes.data = state.queryTab.execRes.data.filter(
 | 
				
			||||||
                        (d: any) => !(deleteDatas.findIndex((x: any) => x[primaryKeyColumnName] == d[primaryKeyColumnName]) != -1)
 | 
					                        (d: any) => !(deleteDatas.findIndex((x: any) => x[primaryKeyColumnName] == d[primaryKeyColumnName]) != -1)
 | 
				
			||||||
@@ -955,7 +978,7 @@ export default defineComponent({
 | 
				
			|||||||
                return;
 | 
					                return;
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
            // 转为字符串比较,可能存在数字等
 | 
					            // 转为字符串比较,可能存在数字等
 | 
				
			||||||
            let text = row[property] + '';
 | 
					            let text = (row[property] ? row[property] : '') + '';
 | 
				
			||||||
            let div = cell.children[0];
 | 
					            let div = cell.children[0];
 | 
				
			||||||
            if (div) {
 | 
					            if (div) {
 | 
				
			||||||
                let input = document.createElement('input');
 | 
					                let input = document.createElement('input');
 | 
				
			||||||
@@ -1107,6 +1130,7 @@ export default defineComponent({
 | 
				
			|||||||
            formatSql,
 | 
					            formatSql,
 | 
				
			||||||
            onBeforeChange,
 | 
					            onBeforeChange,
 | 
				
			||||||
            onRefresh,
 | 
					            onRefresh,
 | 
				
			||||||
 | 
					            handlePageChange,
 | 
				
			||||||
            selectByCondition,
 | 
					            selectByCondition,
 | 
				
			||||||
            onCommit,
 | 
					            onCommit,
 | 
				
			||||||
            addRow,
 | 
					            addRow,
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -5,6 +5,7 @@ export const dbApi = {
 | 
				
			|||||||
    dbs: Api.create("/dbs", 'get'),
 | 
					    dbs: Api.create("/dbs", 'get'),
 | 
				
			||||||
    saveDb: Api.create("/dbs", 'post'),
 | 
					    saveDb: Api.create("/dbs", 'post'),
 | 
				
			||||||
    deleteDb: Api.create("/dbs/{id}", 'delete'),
 | 
					    deleteDb: Api.create("/dbs/{id}", 'delete'),
 | 
				
			||||||
 | 
					    dumpDb: Api.create("/dbs/{id}/dump", 'post'),
 | 
				
			||||||
    tableInfos: Api.create("/dbs/{id}/t-infos", 'get'),
 | 
					    tableInfos: Api.create("/dbs/{id}/t-infos", 'get'),
 | 
				
			||||||
    tableIndex: Api.create("/dbs/{id}/t-index", 'get'),
 | 
					    tableIndex: Api.create("/dbs/{id}/t-index", 'get'),
 | 
				
			||||||
    tableDdl: Api.create("/dbs/{id}/t-create-ddl", 'get'),
 | 
					    tableDdl: Api.create("/dbs/{id}/t-create-ddl", 'get'),
 | 
				
			||||||
@@ -21,5 +22,5 @@ export const dbApi = {
 | 
				
			|||||||
    getSqlNames: Api.create("/dbs/{id}/sql-names", 'get'),
 | 
					    getSqlNames: Api.create("/dbs/{id}/sql-names", 'get'),
 | 
				
			||||||
    deleteDbSql: Api.create("/dbs/{id}/sql", 'delete'),
 | 
					    deleteDbSql: Api.create("/dbs/{id}/sql", 'delete'),
 | 
				
			||||||
    // 获取数据库sql执行记录
 | 
					    // 获取数据库sql执行记录
 | 
				
			||||||
    getSqlExecs: Api.create("/dbs/{id}/sql-execs", 'get'),
 | 
					    getSqlExecs: Api.create("/dbs/{dbId}/sql-execs", 'get'),
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -2,7 +2,7 @@
 | 
				
			|||||||
    <div>
 | 
					    <div>
 | 
				
			||||||
        <el-dialog title="待执行SQL" v-model="dialogVisible" :show-close="false" width="600px">
 | 
					        <el-dialog title="待执行SQL" v-model="dialogVisible" :show-close="false" width="600px">
 | 
				
			||||||
            <codemirror height="350px" class="codesql" ref="cmEditor" language="sql" v-model="sqlValue" :options="cmOptions" />
 | 
					            <codemirror height="350px" class="codesql" ref="cmEditor" language="sql" v-model="sqlValue" :options="cmOptions" />
 | 
				
			||||||
            <el-input v-model="remark" placeholder="请输入执行备注" class="mt5" />
 | 
					            <el-input ref="remarkInputRef" v-model="remark" placeholder="请输入执行备注" class="mt5" />
 | 
				
			||||||
            <template #footer>
 | 
					            <template #footer>
 | 
				
			||||||
                <span class="dialog-footer">
 | 
					                <span class="dialog-footer">
 | 
				
			||||||
                    <el-button @click="cancel">取 消</el-button>
 | 
					                    <el-button @click="cancel">取 消</el-button>
 | 
				
			||||||
@@ -14,9 +14,9 @@
 | 
				
			|||||||
</template>
 | 
					</template>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
<script lang="ts">
 | 
					<script lang="ts">
 | 
				
			||||||
import { toRefs, reactive, defineComponent } from 'vue';
 | 
					import { toRefs, ref, nextTick, reactive, defineComponent } from 'vue';
 | 
				
			||||||
import { dbApi } from '../api';
 | 
					import { dbApi } from '../api';
 | 
				
			||||||
import { ElDialog, ElButton, ElInput, ElMessage } from 'element-plus';
 | 
					import { ElDialog, ElButton, ElInput, ElMessage, InputInstance } from 'element-plus';
 | 
				
			||||||
// import base style
 | 
					// import base style
 | 
				
			||||||
import 'codemirror/lib/codemirror.css';
 | 
					import 'codemirror/lib/codemirror.css';
 | 
				
			||||||
// 引入主题后还需要在 options 中指定主题才会生效
 | 
					// 引入主题后还需要在 options 中指定主题才会生效
 | 
				
			||||||
@@ -50,6 +50,7 @@ export default defineComponent({
 | 
				
			|||||||
        },
 | 
					        },
 | 
				
			||||||
    },
 | 
					    },
 | 
				
			||||||
    setup(props: any) {
 | 
					    setup(props: any) {
 | 
				
			||||||
 | 
					        const remarkInputRef = ref<InputInstance>();
 | 
				
			||||||
        const state = reactive({
 | 
					        const state = reactive({
 | 
				
			||||||
            dialogVisible: false,
 | 
					            dialogVisible: false,
 | 
				
			||||||
            sqlValue: '',
 | 
					            sqlValue: '',
 | 
				
			||||||
@@ -87,13 +88,19 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
            try {
 | 
					            try {
 | 
				
			||||||
                state.btnLoading = true;
 | 
					                state.btnLoading = true;
 | 
				
			||||||
                await dbApi.sqlExec.request({
 | 
					                const res = await dbApi.sqlExec.request({
 | 
				
			||||||
                    id: state.dbId,
 | 
					                    id: state.dbId,
 | 
				
			||||||
                    db: state.db,
 | 
					                    db: state.db,
 | 
				
			||||||
                    remark: state.remark,
 | 
					                    remark: state.remark,
 | 
				
			||||||
                    sql: state.sqlValue.trim(),
 | 
					                    sql: state.sqlValue.trim(),
 | 
				
			||||||
                });
 | 
					                });
 | 
				
			||||||
 | 
					                if (parseInt(res.res[0].影响条数) >= 1) {
 | 
				
			||||||
 | 
					                    ElMessage.success('执行成功');
 | 
				
			||||||
                    runSuccess = true;
 | 
					                    runSuccess = true;
 | 
				
			||||||
 | 
					                } else {
 | 
				
			||||||
 | 
					                    ElMessage.error('执行失败');
 | 
				
			||||||
 | 
					                    runSuccess = false;
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
            } catch (e) {
 | 
					            } catch (e) {
 | 
				
			||||||
                runSuccess = false;
 | 
					                runSuccess = false;
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
@@ -127,10 +134,16 @@ export default defineComponent({
 | 
				
			|||||||
            state.dbId = props.dbId;
 | 
					            state.dbId = props.dbId;
 | 
				
			||||||
            state.db = props.db;
 | 
					            state.db = props.db;
 | 
				
			||||||
            state.dialogVisible = true;
 | 
					            state.dialogVisible = true;
 | 
				
			||||||
 | 
					            nextTick(() => {
 | 
				
			||||||
 | 
					                setTimeout(() => {
 | 
				
			||||||
 | 
					                    remarkInputRef.value?.focus();
 | 
				
			||||||
 | 
					                });
 | 
				
			||||||
 | 
					            });
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return {
 | 
					        return {
 | 
				
			||||||
            ...toRefs(state),
 | 
					            ...toRefs(state),
 | 
				
			||||||
 | 
					            remarkInputRef,
 | 
				
			||||||
            open,
 | 
					            open,
 | 
				
			||||||
            runSql,
 | 
					            runSql,
 | 
				
			||||||
            cancel,
 | 
					            cancel,
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -89,17 +89,19 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
                                <template #dropdown>
 | 
					                                <template #dropdown>
 | 
				
			||||||
                                    <el-dropdown-menu>
 | 
					                                    <el-dropdown-menu>
 | 
				
			||||||
                                        <el-dropdown-item v-if="data.type == '-' && data.size < 1 * 1024 * 1024">
 | 
					                                        <el-dropdown-item
 | 
				
			||||||
                                            <el-link
 | 
					                                            @click="getFileContent(tree.folder.id, data.path)"
 | 
				
			||||||
                                                @click.prevent="getFileContent(tree.folder.id, data.path)"
 | 
					                                            v-if="data.type == '-' && data.size < 1 * 1024 * 1024"
 | 
				
			||||||
                                                type="info"
 | 
					 | 
				
			||||||
                                                icon="view"
 | 
					 | 
				
			||||||
                                                :underline="false"
 | 
					 | 
				
			||||||
                                        >
 | 
					                                        >
 | 
				
			||||||
                                                查看
 | 
					                                            <el-link type="info" icon="view" :underline="false">查看</el-link>
 | 
				
			||||||
                                            </el-link>
 | 
					 | 
				
			||||||
                                        </el-dropdown-item>
 | 
					                                        </el-dropdown-item>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                                        <span v-auth="'machine:file:write'">
 | 
				
			||||||
 | 
					                                            <el-dropdown-item @click="showCreateFileDialog(node, data)" v-if="data.type == 'd'">
 | 
				
			||||||
 | 
					                                                <el-link type="primary" icon="document" :underline="false" style="margin-left: 2px">新建</el-link>
 | 
				
			||||||
 | 
					                                            </el-dropdown-item>
 | 
				
			||||||
 | 
					                                        </span>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                                        <span v-auth="'machine:file:upload'">
 | 
					                                        <span v-auth="'machine:file:upload'">
 | 
				
			||||||
                                            <el-dropdown-item v-if="data.type == 'd'">
 | 
					                                            <el-dropdown-item v-if="data.type == 'd'">
 | 
				
			||||||
                                                <el-upload
 | 
					                                                <el-upload
 | 
				
			||||||
@@ -118,28 +120,14 @@
 | 
				
			|||||||
                                        </span>
 | 
					                                        </span>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                                        <span v-auth="'machine:file:write'">
 | 
					                                        <span v-auth="'machine:file:write'">
 | 
				
			||||||
                                            <el-dropdown-item v-if="data.type == '-'">
 | 
					                                            <el-dropdown-item @click="downloadFile(node, data)" v-if="data.type == '-'">
 | 
				
			||||||
                                                <el-link
 | 
					                                                <el-link type="primary" icon="download" :underline="false" style="margin-left: 2px">下载</el-link>
 | 
				
			||||||
                                                    @click.prevent="downloadFile(node, data)"
 | 
					 | 
				
			||||||
                                                    type="primary"
 | 
					 | 
				
			||||||
                                                    icon="download"
 | 
					 | 
				
			||||||
                                                    :underline="false"
 | 
					 | 
				
			||||||
                                                    style="margin-left: 2px"
 | 
					 | 
				
			||||||
                                                    >下载</el-link
 | 
					 | 
				
			||||||
                                                >
 | 
					 | 
				
			||||||
                                            </el-dropdown-item>
 | 
					                                            </el-dropdown-item>
 | 
				
			||||||
                                        </span>
 | 
					                                        </span>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                                        <span v-auth="'machine:file:rm'">
 | 
					                                        <span v-auth="'machine:file:rm'">
 | 
				
			||||||
                                            <el-dropdown-item v-if="!dontOperate(data)">
 | 
					                                            <el-dropdown-item @click="deleteFile(node, data)" v-if="!dontOperate(data)">
 | 
				
			||||||
                                                <el-link
 | 
					                                                <el-link type="danger" icon="delete" :underline="false" style="margin-left: 2px">删除</el-link>
 | 
				
			||||||
                                                    @click.prevent="deleteFile(node, data)"
 | 
					 | 
				
			||||||
                                                    type="danger"
 | 
					 | 
				
			||||||
                                                    icon="delete"
 | 
					 | 
				
			||||||
                                                    :underline="false"
 | 
					 | 
				
			||||||
                                                    style="margin-left: 2px"
 | 
					 | 
				
			||||||
                                                    >删除
 | 
					 | 
				
			||||||
                                                </el-link>
 | 
					 | 
				
			||||||
                                            </el-dropdown-item>
 | 
					                                            </el-dropdown-item>
 | 
				
			||||||
                                        </span>
 | 
					                                        </span>
 | 
				
			||||||
                                    </el-dropdown-menu>
 | 
					                                    </el-dropdown-menu>
 | 
				
			||||||
@@ -151,6 +139,35 @@
 | 
				
			|||||||
            </div>
 | 
					            </div>
 | 
				
			||||||
        </el-dialog>
 | 
					        </el-dialog>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        <el-dialog
 | 
				
			||||||
 | 
					            :destroy-on-close="true"
 | 
				
			||||||
 | 
					            title="新建文件"
 | 
				
			||||||
 | 
					            v-model="createFileDialog.visible"
 | 
				
			||||||
 | 
					            :before-close="closeCreateFileDialog"
 | 
				
			||||||
 | 
					            :close-on-click-modal="false"
 | 
				
			||||||
 | 
					            top="5vh"
 | 
				
			||||||
 | 
					            width="400px"
 | 
				
			||||||
 | 
					        >
 | 
				
			||||||
 | 
					            <div>
 | 
				
			||||||
 | 
					                <el-form-item prop="name" label="名称:">
 | 
				
			||||||
 | 
					                    <el-input v-model.trim="createFileDialog.name" placeholder="请输入名称" auto-complete="off"></el-input>
 | 
				
			||||||
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					                <el-form-item prop="type" label="类型:">
 | 
				
			||||||
 | 
					                    <el-radio-group v-model="createFileDialog.type">
 | 
				
			||||||
 | 
					                        <el-radio label="d" size="small">文件夹</el-radio>
 | 
				
			||||||
 | 
					                        <el-radio label="-" size="small">文件</el-radio>
 | 
				
			||||||
 | 
					                    </el-radio-group>
 | 
				
			||||||
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					            </div>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            <template #footer>
 | 
				
			||||||
 | 
					                <div class="dialog-footer">
 | 
				
			||||||
 | 
					                    <el-button @click="closeCreateFileDialog">关闭</el-button>
 | 
				
			||||||
 | 
					                    <el-button v-auth="'machine:file:write'" type="primary" @click="createFile">确定</el-button>
 | 
				
			||||||
 | 
					                </div>
 | 
				
			||||||
 | 
					            </template>
 | 
				
			||||||
 | 
					        </el-dialog>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        <el-dialog
 | 
					        <el-dialog
 | 
				
			||||||
            :destroy-on-close="true"
 | 
					            :destroy-on-close="true"
 | 
				
			||||||
            :title="fileContent.dialogTitle"
 | 
					            :title="fileContent.dialogTitle"
 | 
				
			||||||
@@ -182,6 +199,7 @@ import { codemirror } from '@/components/codemirror';
 | 
				
			|||||||
import { getSession } from '@/common/utils/storage';
 | 
					import { getSession } from '@/common/utils/storage';
 | 
				
			||||||
import enums from './enums';
 | 
					import enums from './enums';
 | 
				
			||||||
import config from '@/common/config';
 | 
					import config from '@/common/config';
 | 
				
			||||||
 | 
					import { isTrue } from '@/common/assert';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'FileManage',
 | 
					    name: 'FileManage',
 | 
				
			||||||
@@ -202,26 +220,8 @@ export default defineComponent({
 | 
				
			|||||||
        const fileTree: any = ref(null);
 | 
					        const fileTree: any = ref(null);
 | 
				
			||||||
        const token = getSession('token');
 | 
					        const token = getSession('token');
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const cmOptions = {
 | 
					        const folderType = 'd';
 | 
				
			||||||
            tabSize: 2,
 | 
					        const fileType = '-';
 | 
				
			||||||
            mode: 'text/x-sh',
 | 
					 | 
				
			||||||
            theme: 'panda-syntax',
 | 
					 | 
				
			||||||
            line: true,
 | 
					 | 
				
			||||||
            // 开启校验
 | 
					 | 
				
			||||||
            lint: true,
 | 
					 | 
				
			||||||
            gutters: ['CodeMirror-lint-markers'],
 | 
					 | 
				
			||||||
            indentWithTabs: true,
 | 
					 | 
				
			||||||
            smartIndent: true,
 | 
					 | 
				
			||||||
            matchBrackets: true,
 | 
					 | 
				
			||||||
            autofocus: true,
 | 
					 | 
				
			||||||
            styleSelectedText: true,
 | 
					 | 
				
			||||||
            styleActiveLine: true, // 高亮选中行
 | 
					 | 
				
			||||||
            foldGutter: true, // 块槽
 | 
					 | 
				
			||||||
            hintOptions: {
 | 
					 | 
				
			||||||
                // 当匹配只有一项的时候是否自动补全
 | 
					 | 
				
			||||||
                completeSingle: true,
 | 
					 | 
				
			||||||
            },
 | 
					 | 
				
			||||||
        };
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const state = reactive({
 | 
					        const state = reactive({
 | 
				
			||||||
            dialogVisible: false,
 | 
					            dialogVisible: false,
 | 
				
			||||||
@@ -268,6 +268,12 @@ export default defineComponent({
 | 
				
			|||||||
                path: '',
 | 
					                path: '',
 | 
				
			||||||
                type: '',
 | 
					                type: '',
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
 | 
					            createFileDialog: {
 | 
				
			||||||
 | 
					                visible: false,
 | 
				
			||||||
 | 
					                name: '',
 | 
				
			||||||
 | 
					                type: folderType,
 | 
				
			||||||
 | 
					                node: null as any,
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
            file: null as any,
 | 
					            file: null as any,
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -290,18 +296,6 @@ export default defineComponent({
 | 
				
			|||||||
            getFiles();
 | 
					            getFiles();
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        /**
 | 
					 | 
				
			||||||
         * tab切换触发事件
 | 
					 | 
				
			||||||
         * @param {Object} tab
 | 
					 | 
				
			||||||
         * @param {Object} event
 | 
					 | 
				
			||||||
         */
 | 
					 | 
				
			||||||
        // handleClick(tab, event) {
 | 
					 | 
				
			||||||
        //   // if (tab.name == 'file-manage') {
 | 
					 | 
				
			||||||
        //   //   this.fileManage.node.childNodes = [];
 | 
					 | 
				
			||||||
        //   //   this.loadNode(this.fileManage.node, this.fileManage.resolve);
 | 
					 | 
				
			||||||
        //   // }
 | 
					 | 
				
			||||||
        // }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        const add = () => {
 | 
					        const add = () => {
 | 
				
			||||||
            // 往数组头部添加元素
 | 
					            // 往数组头部添加元素
 | 
				
			||||||
            state.fileTable = [{}].concat(state.fileTable);
 | 
					            state.fileTable = [{}].concat(state.fileTable);
 | 
				
			||||||
@@ -329,7 +323,6 @@ export default defineComponent({
 | 
				
			|||||||
                        })
 | 
					                        })
 | 
				
			||||||
                        .then(() => {
 | 
					                        .then(() => {
 | 
				
			||||||
                            getFiles();
 | 
					                            getFiles();
 | 
				
			||||||
                            // state.fileTable.splice(idx, 1);
 | 
					 | 
				
			||||||
                        });
 | 
					                        });
 | 
				
			||||||
                });
 | 
					                });
 | 
				
			||||||
            } else {
 | 
					            } else {
 | 
				
			||||||
@@ -406,7 +399,6 @@ export default defineComponent({
 | 
				
			|||||||
            emit('update:visible', false);
 | 
					            emit('update:visible', false);
 | 
				
			||||||
            emit('update:machineId', null);
 | 
					            emit('update:machineId', null);
 | 
				
			||||||
            emit('cancel');
 | 
					            emit('cancel');
 | 
				
			||||||
            // state.activeName = 'conf-file'
 | 
					 | 
				
			||||||
            state.fileTable = [];
 | 
					            state.fileTable = [];
 | 
				
			||||||
            state.tree.folder = { id: 0 };
 | 
					            state.tree.folder = { id: 0 };
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
@@ -431,7 +423,7 @@ export default defineComponent({
 | 
				
			|||||||
                return resolve([
 | 
					                return resolve([
 | 
				
			||||||
                    {
 | 
					                    {
 | 
				
			||||||
                        name: path,
 | 
					                        name: path,
 | 
				
			||||||
                        type: 'd',
 | 
					                        type: folderType,
 | 
				
			||||||
                        path: path,
 | 
					                        path: path,
 | 
				
			||||||
                    },
 | 
					                    },
 | 
				
			||||||
                ]);
 | 
					                ]);
 | 
				
			||||||
@@ -453,13 +445,42 @@ export default defineComponent({
 | 
				
			|||||||
            });
 | 
					            });
 | 
				
			||||||
            for (const file of res) {
 | 
					            for (const file of res) {
 | 
				
			||||||
                const type = file.type;
 | 
					                const type = file.type;
 | 
				
			||||||
                if (type != 'd') {
 | 
					                if (type == fileType) {
 | 
				
			||||||
                    file.leaf = true;
 | 
					                    file.leaf = true;
 | 
				
			||||||
                }
 | 
					                }
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
            return resolve(res);
 | 
					            return resolve(res);
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const showCreateFileDialog = (node: any) => {
 | 
				
			||||||
 | 
					            isTrue(node.expanded, '请先点击展开该节点后再创建');
 | 
				
			||||||
 | 
					            state.createFileDialog.node = node;
 | 
				
			||||||
 | 
					            state.createFileDialog.visible = true;
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const createFile = async () => {
 | 
				
			||||||
 | 
					            const node = state.createFileDialog.node;
 | 
				
			||||||
 | 
					            console.log(node.data);
 | 
				
			||||||
 | 
					            const name = state.createFileDialog.name;
 | 
				
			||||||
 | 
					            const type = state.createFileDialog.type;
 | 
				
			||||||
 | 
					            const path = node.data.path + '/' + name;
 | 
				
			||||||
 | 
					            await machineApi.createFile.request({
 | 
				
			||||||
 | 
					                machineId: props.machineId,
 | 
				
			||||||
 | 
					                id: state.tree.folder.id,
 | 
				
			||||||
 | 
					                path,
 | 
				
			||||||
 | 
					                type,
 | 
				
			||||||
 | 
					            });
 | 
				
			||||||
 | 
					            fileTree.value.append({ name: name, path: path, type: type, leaf: type === fileType, size: 0 }, node);
 | 
				
			||||||
 | 
					            closeCreateFileDialog();
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const closeCreateFileDialog = () => {
 | 
				
			||||||
 | 
					            state.createFileDialog.visible = false;
 | 
				
			||||||
 | 
					            state.createFileDialog.node = null;
 | 
				
			||||||
 | 
					            state.createFileDialog.name = '';
 | 
				
			||||||
 | 
					            state.createFileDialog.type = folderType;
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const deleteFile = (node: any, data: any) => {
 | 
					        const deleteFile = (node: any, data: any) => {
 | 
				
			||||||
            const file = data.path;
 | 
					            const file = data.path;
 | 
				
			||||||
            ElMessageBox.confirm(`此操作将删除 [${file}], 是否继续?`, '提示', {
 | 
					            ElMessageBox.confirm(`此操作将删除 [${file}], 是否继续?`, '提示', {
 | 
				
			||||||
@@ -486,7 +507,6 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        const downloadFile = (node: any, data: any) => {
 | 
					        const downloadFile = (node: any, data: any) => {
 | 
				
			||||||
            const a = document.createElement('a');
 | 
					            const a = document.createElement('a');
 | 
				
			||||||
            // a.setAttribute('target', '_blank')
 | 
					 | 
				
			||||||
            a.setAttribute(
 | 
					            a.setAttribute(
 | 
				
			||||||
                'href',
 | 
					                'href',
 | 
				
			||||||
                `${config.baseApiUrl}/machines/${props.machineId}/files/${state.tree.folder.id}/read?type=1&path=${data.path}&token=${token}`
 | 
					                `${config.baseApiUrl}/machines/${props.machineId}/files/${state.tree.folder.id}/read?type=1&path=${data.path}&token=${token}`
 | 
				
			||||||
@@ -534,7 +554,6 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        const beforeUpload = (file: File) => {
 | 
					        const beforeUpload = (file: File) => {
 | 
				
			||||||
            state.file = file;
 | 
					            state.file = file;
 | 
				
			||||||
            // ElMessage.success(`'${file.name}' 上传中,请关注结果通知`);
 | 
					 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
        const getFilePath = (data: object, visible: boolean) => {
 | 
					        const getFilePath = (data: object, visible: boolean) => {
 | 
				
			||||||
            if (visible) {
 | 
					            if (visible) {
 | 
				
			||||||
@@ -590,7 +609,6 @@ export default defineComponent({
 | 
				
			|||||||
            fileTree,
 | 
					            fileTree,
 | 
				
			||||||
            enums,
 | 
					            enums,
 | 
				
			||||||
            token,
 | 
					            token,
 | 
				
			||||||
            cmOptions,
 | 
					 | 
				
			||||||
            add,
 | 
					            add,
 | 
				
			||||||
            getFiles,
 | 
					            getFiles,
 | 
				
			||||||
            handlePageChange,
 | 
					            handlePageChange,
 | 
				
			||||||
@@ -601,6 +619,9 @@ export default defineComponent({
 | 
				
			|||||||
            updateContent,
 | 
					            updateContent,
 | 
				
			||||||
            handleClose,
 | 
					            handleClose,
 | 
				
			||||||
            loadNode,
 | 
					            loadNode,
 | 
				
			||||||
 | 
					            showCreateFileDialog,
 | 
				
			||||||
 | 
					            closeCreateFileDialog,
 | 
				
			||||||
 | 
					            createFile,
 | 
				
			||||||
            deleteFile,
 | 
					            deleteFile,
 | 
				
			||||||
            downloadFile,
 | 
					            downloadFile,
 | 
				
			||||||
            getUploadFile,
 | 
					            getUploadFile,
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -48,6 +48,7 @@ import { toRefs, reactive, watch, defineComponent, ref } from 'vue';
 | 
				
			|||||||
import { machineApi } from './api';
 | 
					import { machineApi } from './api';
 | 
				
			||||||
import { ElMessage } from 'element-plus';
 | 
					import { ElMessage } from 'element-plus';
 | 
				
			||||||
import { notBlank } from '@/common/assert';
 | 
					import { notBlank } from '@/common/assert';
 | 
				
			||||||
 | 
					import { RsaEncrypt } from '@/common/rsa';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'MachineEdit',
 | 
					    name: 'MachineEdit',
 | 
				
			||||||
@@ -76,8 +77,8 @@ export default defineComponent({
 | 
				
			|||||||
                projectName: null,
 | 
					                projectName: null,
 | 
				
			||||||
                name: null,
 | 
					                name: null,
 | 
				
			||||||
                port: 22,
 | 
					                port: 22,
 | 
				
			||||||
                username: null,
 | 
					                username: "",
 | 
				
			||||||
                password: null,
 | 
					                password: "",
 | 
				
			||||||
                remark: '',
 | 
					                remark: '',
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
            btnLoading: false,
 | 
					            btnLoading: false,
 | 
				
			||||||
@@ -149,9 +150,11 @@ export default defineComponent({
 | 
				
			|||||||
            if (!state.form.id) {
 | 
					            if (!state.form.id) {
 | 
				
			||||||
                notBlank(state.form.password, '新增操作,密码不可为空');
 | 
					                notBlank(state.form.password, '新增操作,密码不可为空');
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
            machineForm.value.validate((valid: boolean) => {
 | 
					            machineForm.value.validate(async (valid: boolean) => {
 | 
				
			||||||
                if (valid) {
 | 
					                if (valid) {
 | 
				
			||||||
                    machineApi.saveMachine.request(state.form).then(() => {
 | 
					                    const reqForm = { ...state.form };
 | 
				
			||||||
 | 
					                    reqForm.password = await RsaEncrypt(state.form.password);
 | 
				
			||||||
 | 
					                    machineApi.saveMachine.request(reqForm).then(() => {
 | 
				
			||||||
                        ElMessage.success('保存成功');
 | 
					                        ElMessage.success('保存成功');
 | 
				
			||||||
                        emit('val-change', state.form);
 | 
					                        emit('val-change', state.form);
 | 
				
			||||||
                        state.btnLoading = true;
 | 
					                        state.btnLoading = true;
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -57,11 +57,10 @@
 | 
				
			|||||||
                            v-model="scope.row.status"
 | 
					                            v-model="scope.row.status"
 | 
				
			||||||
                            :active-value="1"
 | 
					                            :active-value="1"
 | 
				
			||||||
                            :inactive-value="-1"
 | 
					                            :inactive-value="-1"
 | 
				
			||||||
                            active-color="#13ce66"
 | 
					 | 
				
			||||||
                            inactive-color="#ff4949"
 | 
					 | 
				
			||||||
                            inline-prompt
 | 
					                            inline-prompt
 | 
				
			||||||
                            active-text="启用"
 | 
					                            active-text="启用"
 | 
				
			||||||
                            inactive-text="停用"
 | 
					                            inactive-text="停用"
 | 
				
			||||||
 | 
					                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
 | 
				
			||||||
                            @change="changeStatus(scope.row)"
 | 
					                            @change="changeStatus(scope.row)"
 | 
				
			||||||
                        ></el-switch>
 | 
					                        ></el-switch>
 | 
				
			||||||
                    </template>
 | 
					                    </template>
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -25,7 +25,7 @@
 | 
				
			|||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                <el-form-item prop="params" label="参数">
 | 
					                <el-form-item prop="params" label="参数">
 | 
				
			||||||
                    <el-input v-model.trim="form.params" placeholder="参数数组json,若无可不填"></el-input>
 | 
					                    <el-input v-model="form.params" placeholder="参数数组json,若无可不填"></el-input>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                <el-form-item prop="script" label="内容" id="content">
 | 
					                <el-form-item prop="script" label="内容" id="content">
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -25,6 +25,7 @@ export const machineApi = {
 | 
				
			|||||||
    rmFile: Api.create("/machines/{machineId}/files/{fileId}/remove", 'delete'),
 | 
					    rmFile: Api.create("/machines/{machineId}/files/{fileId}/remove", 'delete'),
 | 
				
			||||||
    uploadFile: Api.create("/machines/{machineId}/files/{fileId}/upload?token={token}", 'post'),
 | 
					    uploadFile: Api.create("/machines/{machineId}/files/{fileId}/upload?token={token}", 'post'),
 | 
				
			||||||
    fileContent: Api.create("/machines/{machineId}/files/{fileId}/read", 'get'),
 | 
					    fileContent: Api.create("/machines/{machineId}/files/{fileId}/read", 'get'),
 | 
				
			||||||
 | 
					    createFile: Api.create("/machines/{machineId}/files/{id}/create-file", 'post'),
 | 
				
			||||||
    // 修改文件内容
 | 
					    // 修改文件内容
 | 
				
			||||||
    updateFileContent: Api.create("/machines/{machineId}/files/{id}/write", 'post'),
 | 
					    updateFileContent: Api.create("/machines/{machineId}/files/{id}/write", 'post'),
 | 
				
			||||||
    // 添加文件or目录
 | 
					    // 添加文件or目录
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -15,7 +15,7 @@
 | 
				
			|||||||
                            </el-form-item>
 | 
					                            </el-form-item>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                            <el-form-item label="库" label-width="20px">
 | 
					                            <el-form-item label="库" label-width="20px">
 | 
				
			||||||
                                <el-select v-model="database" placeholder="请选择库" @change="changeDatabase">
 | 
					                                <el-select v-model="database" placeholder="请选择库" @change="changeDatabase" filterable>
 | 
				
			||||||
                                    <el-option v-for="item in databases" :key="item.Name" :label="item.Name" :value="item.Name">
 | 
					                                    <el-option v-for="item in databases" :key="item.Name" :label="item.Name" :value="item.Name">
 | 
				
			||||||
                                        <span style="float: left">{{ item.Name }}</span>
 | 
					                                        <span style="float: left">{{ item.Name }}</span>
 | 
				
			||||||
                                        <span style="float: right; color: #8492a6; margin-left: 4px; font-size: 13px">{{
 | 
					                                        <span style="float: right; color: #8492a6; margin-left: 4px; font-size: 13px">{{
 | 
				
			||||||
@@ -26,12 +26,8 @@
 | 
				
			|||||||
                            </el-form-item>
 | 
					                            </el-form-item>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                            <el-form-item label="集合" label-width="40px">
 | 
					                            <el-form-item label="集合" label-width="40px">
 | 
				
			||||||
                                <el-select v-model="collection" placeholder="请选择集合" @change="changeCollection">
 | 
					                                <el-select v-model="collection" placeholder="请选择集合" @change="changeCollection" filterable>
 | 
				
			||||||
                                    <el-option v-for="item in collections" :key="item" :label="item" :value="item">
 | 
					                                    <el-option v-for="item in collections" :key="item" :label="item" :value="item">
 | 
				
			||||||
                                        <!-- <span style="float: left">{{ item.uri }}</span>
 | 
					 | 
				
			||||||
                                            <span style="float: right; color: #8492a6; margin-left: 6px; font-size: 13px">{{
 | 
					 | 
				
			||||||
                                                ` [${item.name}]`
 | 
					 | 
				
			||||||
                                            }}</span> -->
 | 
					 | 
				
			||||||
                                    </el-option>
 | 
					                                    </el-option>
 | 
				
			||||||
                                </el-select>
 | 
					                                </el-select>
 | 
				
			||||||
                            </el-form-item>
 | 
					                            </el-form-item>
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -42,6 +42,7 @@ import { toRefs, reactive, watch, defineComponent, ref } from 'vue';
 | 
				
			|||||||
import { mongoApi } from './api';
 | 
					import { mongoApi } from './api';
 | 
				
			||||||
import { projectApi } from '../project/api.ts';
 | 
					import { projectApi } from '../project/api.ts';
 | 
				
			||||||
import { ElMessage } from 'element-plus';
 | 
					import { ElMessage } from 'element-plus';
 | 
				
			||||||
 | 
					import { RsaEncrypt } from '@/common/rsa';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'MongoEdit',
 | 
					    name: 'MongoEdit',
 | 
				
			||||||
@@ -144,9 +145,11 @@ export default defineComponent({
 | 
				
			|||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const btnOk = async () => {
 | 
					        const btnOk = async () => {
 | 
				
			||||||
            mongoForm.value.validate((valid: boolean) => {
 | 
					            mongoForm.value.validate(async (valid: boolean) => {
 | 
				
			||||||
                if (valid) {
 | 
					                if (valid) {
 | 
				
			||||||
                    mongoApi.saveMongo.request(state.form).then(() => {
 | 
					                    const reqForm = { ...state.form };
 | 
				
			||||||
 | 
					                    reqForm.uri = await RsaEncrypt(reqForm.uri);
 | 
				
			||||||
 | 
					                    mongoApi.saveMongo.request(reqForm).then(() => {
 | 
				
			||||||
                        ElMessage.success('保存成功');
 | 
					                        ElMessage.success('保存成功');
 | 
				
			||||||
                        emit('val-change', state.form);
 | 
					                        emit('val-change', state.form);
 | 
				
			||||||
                        state.btnLoading = true;
 | 
					                        state.btnLoading = true;
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -250,7 +250,7 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        onMounted(async () => {
 | 
					        onMounted(async () => {
 | 
				
			||||||
            search();
 | 
					            search();
 | 
				
			||||||
            state.projects = (await projectApi.projects.request({ pageNum: 1, pageSize: 100 })).list;
 | 
					            state.projects = await projectApi.accountProjects.request(null);
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const handlePageChange = (curPage: number) => {
 | 
					        const handlePageChange = (curPage: number) => {
 | 
				
			||||||
@@ -266,12 +266,6 @@ export default defineComponent({
 | 
				
			|||||||
            state.currentData = item;
 | 
					            state.currentData = item;
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // connect() {
 | 
					 | 
				
			||||||
        //   Req.post('/open/redis/connect', this.form, res => {
 | 
					 | 
				
			||||||
        //     this.redisInfo = res
 | 
					 | 
				
			||||||
        //   })
 | 
					 | 
				
			||||||
        // }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        const showDatabases = async (id: number) => {
 | 
					        const showDatabases = async (id: number) => {
 | 
				
			||||||
            state.databaseDialog.data = (await mongoApi.databases.request({ id })).Databases;
 | 
					            state.databaseDialog.data = (await mongoApi.databases.request({ id })).Databases;
 | 
				
			||||||
            state.databaseDialog.title = `数据库列表`;
 | 
					            state.databaseDialog.title = `数据库列表`;
 | 
				
			||||||
@@ -371,14 +365,6 @@ export default defineComponent({
 | 
				
			|||||||
            } catch (err) {}
 | 
					            } catch (err) {}
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // const info = (redis: any) => {
 | 
					 | 
				
			||||||
        //     redisApi.redisInfo.request({ id: redis.id }).then((res: any) => {
 | 
					 | 
				
			||||||
        //         state.infoDialog.info = res;
 | 
					 | 
				
			||||||
        //         state.infoDialog.title = `'${redis.host}' info`;
 | 
					 | 
				
			||||||
        //         state.infoDialog.visible = true;
 | 
					 | 
				
			||||||
        //     });
 | 
					 | 
				
			||||||
        // };
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        const search = async () => {
 | 
					        const search = async () => {
 | 
				
			||||||
            const res = await mongoApi.mongoList.request(state.query);
 | 
					            const res = await mongoApi.mongoList.request(state.query);
 | 
				
			||||||
            state.list = res.list;
 | 
					            state.list = res.list;
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -31,7 +31,7 @@
 | 
				
			|||||||
                                ></el-input>
 | 
					                                ></el-input>
 | 
				
			||||||
                            </el-form-item>
 | 
					                            </el-form-item>
 | 
				
			||||||
                            <el-form-item label="count" label-width="60px">
 | 
					                            <el-form-item label="count" label-width="60px">
 | 
				
			||||||
                                <el-input placeholder="count" style="width: 62px" v-model="scanParam.count"></el-input>
 | 
					                                <el-input placeholder="count" style="width: 62px" v-model.number="scanParam.count"></el-input>
 | 
				
			||||||
                            </el-form-item>
 | 
					                            </el-form-item>
 | 
				
			||||||
                            <el-form-item>
 | 
					                            <el-form-item>
 | 
				
			||||||
                                <el-button @click="searchKey()" type="success" icon="search" plain></el-button>
 | 
					                                <el-button @click="searchKey()" type="success" icon="search" plain></el-button>
 | 
				
			||||||
@@ -92,7 +92,7 @@ import { toRefs, reactive, defineComponent } from 'vue';
 | 
				
			|||||||
import { ElMessage, ElMessageBox } from 'element-plus';
 | 
					import { ElMessage, ElMessageBox } from 'element-plus';
 | 
				
			||||||
import ProjectEnvSelect from '../component/ProjectEnvSelect.vue';
 | 
					import ProjectEnvSelect from '../component/ProjectEnvSelect.vue';
 | 
				
			||||||
import DataEdit from './DataEdit.vue';
 | 
					import DataEdit from './DataEdit.vue';
 | 
				
			||||||
import { isTrue, notNull } from '@/common/assert';
 | 
					import { isTrue, notBlank, notNull } from '@/common/assert';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'DataOperation',
 | 
					    name: 'DataOperation',
 | 
				
			||||||
@@ -103,18 +103,15 @@ export default defineComponent({
 | 
				
			|||||||
    setup() {
 | 
					    setup() {
 | 
				
			||||||
        const state = reactive({
 | 
					        const state = reactive({
 | 
				
			||||||
            loading: false,
 | 
					            loading: false,
 | 
				
			||||||
            cluster: 0,
 | 
					 | 
				
			||||||
            redisList: [],
 | 
					            redisList: [],
 | 
				
			||||||
            query: {
 | 
					            query: {
 | 
				
			||||||
                envId: 0,
 | 
					                envId: 0,
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
            scanParam: {
 | 
					            scanParam: {
 | 
				
			||||||
                id: null,
 | 
					                id: null,
 | 
				
			||||||
                cluster: 0,
 | 
					 | 
				
			||||||
                match: null,
 | 
					                match: null,
 | 
				
			||||||
                count: 10,
 | 
					                count: 10,
 | 
				
			||||||
                cursor: 0,
 | 
					                cursor: {},
 | 
				
			||||||
                prevCursor: null,
 | 
					 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
            valueDialog: {
 | 
					            valueDialog: {
 | 
				
			||||||
                visible: false,
 | 
					                visible: false,
 | 
				
			||||||
@@ -151,31 +148,33 @@ export default defineComponent({
 | 
				
			|||||||
            }
 | 
					            }
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const changeRedis = () => {
 | 
					        const changeRedis = (id: number) => {
 | 
				
			||||||
            resetScanParam();
 | 
					            resetScanParam(id);
 | 
				
			||||||
            state.keys = [];
 | 
					            state.keys = [];
 | 
				
			||||||
            state.dbsize = 0;
 | 
					            state.dbsize = 0;
 | 
				
			||||||
            searchKey();
 | 
					            searchKey();
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const scan = () => {
 | 
					        const scan = async () => {
 | 
				
			||||||
            isTrue(state.scanParam.id != null, '请先选择redis');
 | 
					            isTrue(state.scanParam.id != null, '请先选择redis');
 | 
				
			||||||
 | 
					            notBlank(state.scanParam.count, 'count不能为空');
 | 
				
			||||||
            isTrue(state.scanParam.count < 20001, 'count不能超过20000');
 | 
					            isTrue(state.scanParam.count < 20001, 'count不能超过20000');
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            state.loading = true;
 | 
					            state.loading = true;
 | 
				
			||||||
            state.scanParam.cluster = state.cluster == 0 ? 0 : 1;
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
            redisApi.scan.request(state.scanParam).then((res) => {
 | 
					            try {
 | 
				
			||||||
 | 
					                const res = await redisApi.scan.request(state.scanParam);
 | 
				
			||||||
                state.keys = res.keys;
 | 
					                state.keys = res.keys;
 | 
				
			||||||
                state.dbsize = res.dbSize;
 | 
					                state.dbsize = res.dbSize;
 | 
				
			||||||
                state.scanParam.cursor = res.cursor;
 | 
					                state.scanParam.cursor = res.cursor;
 | 
				
			||||||
 | 
					            } finally {
 | 
				
			||||||
                state.loading = false;
 | 
					                state.loading = false;
 | 
				
			||||||
            });
 | 
					            }
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const searchKey = () => {
 | 
					        const searchKey = async () => {
 | 
				
			||||||
            state.scanParam.cursor = 0;
 | 
					            state.scanParam.cursor = {};
 | 
				
			||||||
            scan();
 | 
					            await scan();
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const clearRedis = () => {
 | 
					        const clearRedis = () => {
 | 
				
			||||||
@@ -193,10 +192,17 @@ export default defineComponent({
 | 
				
			|||||||
            }
 | 
					            }
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const resetScanParam = () => {
 | 
					        const resetScanParam = (id: number = 0) => {
 | 
				
			||||||
            state.scanParam.match = null;
 | 
					 | 
				
			||||||
            state.scanParam.cursor = 0;
 | 
					 | 
				
			||||||
            state.scanParam.count = 10;
 | 
					            state.scanParam.count = 10;
 | 
				
			||||||
 | 
					            if (id != 0) {
 | 
				
			||||||
 | 
					                const redis: any = state.redisList.find((x: any) => x.id == id);
 | 
				
			||||||
 | 
					                // 集群模式count设小点,因为后端会从所有master节点scan一遍然后合并结果
 | 
				
			||||||
 | 
					                if (redis && redis.mode == 'cluster') {
 | 
				
			||||||
 | 
					                    state.scanParam.count = 5;
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					            state.scanParam.match = null;
 | 
				
			||||||
 | 
					            state.scanParam.cursor = {};
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const getValue = async (row: any) => {
 | 
					        const getValue = async (row: any) => {
 | 
				
			||||||
@@ -204,11 +210,9 @@ export default defineComponent({
 | 
				
			|||||||
            const key = row.key;
 | 
					            const key = row.key;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            let res: any;
 | 
					            let res: any;
 | 
				
			||||||
            const id = state.cluster == 0 ? state.scanParam.id : state.cluster;
 | 
					 | 
				
			||||||
            const reqParam = {
 | 
					            const reqParam = {
 | 
				
			||||||
                cluster: state.cluster,
 | 
					 | 
				
			||||||
                key: row.key,
 | 
					                key: row.key,
 | 
				
			||||||
                id,
 | 
					                id: state.scanParam.id,
 | 
				
			||||||
            };
 | 
					            };
 | 
				
			||||||
            switch (type) {
 | 
					            switch (type) {
 | 
				
			||||||
                case 'string':
 | 
					                case 'string':
 | 
				
			||||||
@@ -260,29 +264,27 @@ export default defineComponent({
 | 
				
			|||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const del = (key: string) => {
 | 
					        const del = (key: string) => {
 | 
				
			||||||
            ElMessageBox.confirm(`此操作将删除对应的key , 是否继续?`, '提示', {
 | 
					            ElMessageBox.confirm(`确定删除[ ${key} ] 该key?`, '提示', {
 | 
				
			||||||
                confirmButtonText: '确定',
 | 
					                confirmButtonText: '确定',
 | 
				
			||||||
                cancelButtonText: '取消',
 | 
					                cancelButtonText: '取消',
 | 
				
			||||||
                type: 'warning',
 | 
					                type: 'warning',
 | 
				
			||||||
            })
 | 
					            })
 | 
				
			||||||
                .then(() => {
 | 
					                .then(() => {
 | 
				
			||||||
                    let id = state.cluster == 0 ? state.scanParam.id : state.cluster;
 | 
					 | 
				
			||||||
                    redisApi.delKey
 | 
					                    redisApi.delKey
 | 
				
			||||||
                        .request({
 | 
					                        .request({
 | 
				
			||||||
                            cluster: state.cluster,
 | 
					 | 
				
			||||||
                            key,
 | 
					                            key,
 | 
				
			||||||
                            id,
 | 
					                            id: state.scanParam.id,
 | 
				
			||||||
                        })
 | 
					                        })
 | 
				
			||||||
                        .then(() => {
 | 
					                        .then(() => {
 | 
				
			||||||
                            ElMessage.success('删除成功!');
 | 
					                            ElMessage.success('删除成功!');
 | 
				
			||||||
                            scan();
 | 
					                            searchKey();
 | 
				
			||||||
                        });
 | 
					                        });
 | 
				
			||||||
                })
 | 
					                })
 | 
				
			||||||
                .catch(() => {});
 | 
					                .catch(() => {});
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const ttlConveter = (ttl: any) => {
 | 
					        const ttlConveter = (ttl: any) => {
 | 
				
			||||||
            if (ttl == -1) {
 | 
					            if (ttl == -1 || ttl == 0) {
 | 
				
			||||||
                return '永久';
 | 
					                return '永久';
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
            if (!ttl) {
 | 
					            if (!ttl) {
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -13,21 +13,35 @@
 | 
				
			|||||||
                        <el-option v-for="item in envs" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
 | 
					                        <el-option v-for="item in envs" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
 | 
				
			||||||
                    </el-select>
 | 
					                    </el-select>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					                <el-form-item prop="mode" label="mode:" required>
 | 
				
			||||||
 | 
					                    <el-select style="width: 100%" v-model="form.mode" placeholder="请选择模式">
 | 
				
			||||||
 | 
					                        <el-option label="standalone" value="standalone"> </el-option>
 | 
				
			||||||
 | 
					                        <el-option label="cluster" value="cluster"> </el-option>
 | 
				
			||||||
 | 
					                    </el-select>
 | 
				
			||||||
 | 
					                </el-form-item>
 | 
				
			||||||
                <el-form-item prop="host" label="host:" required>
 | 
					                <el-form-item prop="host" label="host:" required>
 | 
				
			||||||
                    <el-input v-model.trim="form.host" placeholder="请输入host:port" auto-complete="off"></el-input>
 | 
					                    <el-input
 | 
				
			||||||
 | 
					                        v-model.trim="form.host"
 | 
				
			||||||
 | 
					                        placeholder="请输入host:port,集群模式用','分割"
 | 
				
			||||||
 | 
					                        auto-complete="off"
 | 
				
			||||||
 | 
					                        type="textarea"
 | 
				
			||||||
 | 
					                    ></el-input>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
                <el-form-item prop="password" label="密码:">
 | 
					                <el-form-item prop="password" label="密码:">
 | 
				
			||||||
                    <el-input
 | 
					                    <el-input
 | 
				
			||||||
                        type="password"
 | 
					                        type="password"
 | 
				
			||||||
                        show-password
 | 
					                        show-password
 | 
				
			||||||
                        v-model.trim="form.password"
 | 
					                        v-model.trim="form.password"
 | 
				
			||||||
                        placeholder="请输入密码"
 | 
					                        placeholder="请输入密码, 修改操作可不填"
 | 
				
			||||||
                        autocomplete="new-password"
 | 
					                        autocomplete="new-password"
 | 
				
			||||||
                    ></el-input>
 | 
					                    ></el-input>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
                <el-form-item prop="db" label="库号:" required>
 | 
					                <el-form-item prop="db" label="库号:" required>
 | 
				
			||||||
                    <el-input v-model.number="form.db" placeholder="请输入库号"></el-input>
 | 
					                    <el-input v-model.number="form.db" placeholder="请输入库号"></el-input>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
 | 
					                <el-form-item prop="remark" label="备注:">
 | 
				
			||||||
 | 
					                    <el-input v-model.trim="form.remark" auto-complete="off" type="textarea"></el-input>
 | 
				
			||||||
 | 
					                </el-form-item>
 | 
				
			||||||
            </el-form>
 | 
					            </el-form>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
            <template #footer>
 | 
					            <template #footer>
 | 
				
			||||||
@@ -45,6 +59,7 @@ import { toRefs, reactive, watch, defineComponent, ref } from 'vue';
 | 
				
			|||||||
import { redisApi } from './api';
 | 
					import { redisApi } from './api';
 | 
				
			||||||
import { projectApi } from '../project/api.ts';
 | 
					import { projectApi } from '../project/api.ts';
 | 
				
			||||||
import { ElMessage } from 'element-plus';
 | 
					import { ElMessage } from 'element-plus';
 | 
				
			||||||
 | 
					import { RsaEncrypt } from '@/common/rsa';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export default defineComponent({
 | 
					export default defineComponent({
 | 
				
			||||||
    name: 'RedisEdit',
 | 
					    name: 'RedisEdit',
 | 
				
			||||||
@@ -71,12 +86,14 @@ export default defineComponent({
 | 
				
			|||||||
            form: {
 | 
					            form: {
 | 
				
			||||||
                id: null,
 | 
					                id: null,
 | 
				
			||||||
                name: null,
 | 
					                name: null,
 | 
				
			||||||
 | 
					                mode: 'standalone',
 | 
				
			||||||
                host: null,
 | 
					                host: null,
 | 
				
			||||||
                password: null,
 | 
					                password: null,
 | 
				
			||||||
                project: null,
 | 
					                project: null,
 | 
				
			||||||
                projectId: null,
 | 
					                projectId: null,
 | 
				
			||||||
                envId: null,
 | 
					                envId: null,
 | 
				
			||||||
                env: null,
 | 
					                env: null,
 | 
				
			||||||
 | 
					                remark: '',
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
            btnLoading: false,
 | 
					            btnLoading: false,
 | 
				
			||||||
            rules: {
 | 
					            rules: {
 | 
				
			||||||
@@ -108,6 +125,13 @@ export default defineComponent({
 | 
				
			|||||||
                        trigger: ['change', 'blur'],
 | 
					                        trigger: ['change', 'blur'],
 | 
				
			||||||
                    },
 | 
					                    },
 | 
				
			||||||
                ],
 | 
					                ],
 | 
				
			||||||
 | 
					                mode: [
 | 
				
			||||||
 | 
					                    {
 | 
				
			||||||
 | 
					                        required: true,
 | 
				
			||||||
 | 
					                        message: '请输入模式',
 | 
				
			||||||
 | 
					                        trigger: ['change', 'blur'],
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                ],
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -148,9 +172,11 @@ export default defineComponent({
 | 
				
			|||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const btnOk = async () => {
 | 
					        const btnOk = async () => {
 | 
				
			||||||
            redisForm.value.validate((valid: boolean) => {
 | 
					            redisForm.value.validate(async (valid: boolean) => {
 | 
				
			||||||
                if (valid) {
 | 
					                if (valid) {
 | 
				
			||||||
                    redisApi.saveRedis.request(state.form).then(() => {
 | 
					                    const reqForm = { ...state.form };
 | 
				
			||||||
 | 
					                    reqForm.password = await RsaEncrypt(reqForm.password);
 | 
				
			||||||
 | 
					                    redisApi.saveRedis.request(reqForm).then(() => {
 | 
				
			||||||
                        ElMessage.success('保存成功');
 | 
					                        ElMessage.success('保存成功');
 | 
				
			||||||
                        emit('val-change', state.form);
 | 
					                        emit('val-change', state.form);
 | 
				
			||||||
                        state.btnLoading = true;
 | 
					                        state.btnLoading = true;
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -5,16 +5,12 @@
 | 
				
			|||||||
            <el-button type="primary" icon="edit" :disabled="currentId == null" @click="editRedis(false)" plain>编辑</el-button>
 | 
					            <el-button type="primary" icon="edit" :disabled="currentId == null" @click="editRedis(false)" plain>编辑</el-button>
 | 
				
			||||||
            <el-button type="danger" icon="delete" :disabled="currentId == null" @click="deleteRedis" plain>删除</el-button>
 | 
					            <el-button type="danger" icon="delete" :disabled="currentId == null" @click="deleteRedis" plain>删除</el-button>
 | 
				
			||||||
            <div style="float: right">
 | 
					            <div style="float: right">
 | 
				
			||||||
                <!-- <el-input placeholder="host"  style="width: 140px" v-model="query.host" @clear="search" plain clearable></el-input>
 | 
					 | 
				
			||||||
                <el-select v-model="params.clusterId"  clearable placeholder="集群选择">
 | 
					 | 
				
			||||||
                    <el-option v-for="item in clusters" :key="item.id" :value="item.id" :label="item.name"></el-option>
 | 
					 | 
				
			||||||
                </el-select> -->
 | 
					 | 
				
			||||||
                <el-select v-model="query.projectId" placeholder="请选择项目" filterable clearable>
 | 
					                <el-select v-model="query.projectId" placeholder="请选择项目" filterable clearable>
 | 
				
			||||||
                    <el-option v-for="item in projects" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
 | 
					                    <el-option v-for="item in projects" :key="item.id" :label="`${item.name} [${item.remark}]`" :value="item.id"> </el-option>
 | 
				
			||||||
                </el-select>
 | 
					                </el-select>
 | 
				
			||||||
                <el-button class="ml5" @click="search" type="success" icon="search"></el-button>
 | 
					                <el-button class="ml5" @click="search" type="success" icon="search"></el-button>
 | 
				
			||||||
            </div>
 | 
					            </div>
 | 
				
			||||||
            <el-table :data="redisTable" style="width: 100%" @current-change="choose" stripe>
 | 
					            <el-table :data="redisTable" @current-change="choose" stripe>
 | 
				
			||||||
                <el-table-column label="选择" width="60px">
 | 
					                <el-table-column label="选择" width="60px">
 | 
				
			||||||
                    <template #default="scope">
 | 
					                    <template #default="scope">
 | 
				
			||||||
                        <el-radio v-model="currentId" :label="scope.row.id">
 | 
					                        <el-radio v-model="currentId" :label="scope.row.id">
 | 
				
			||||||
@@ -22,19 +18,23 @@
 | 
				
			|||||||
                        </el-radio>
 | 
					                        </el-radio>
 | 
				
			||||||
                    </template>
 | 
					                    </template>
 | 
				
			||||||
                </el-table-column>
 | 
					                </el-table-column>
 | 
				
			||||||
                <el-table-column prop="project" label="项目" width></el-table-column>
 | 
					                <el-table-column prop="project" label="项目" min-width="100"></el-table-column>
 | 
				
			||||||
                <el-table-column prop="env" label="环境" width></el-table-column>
 | 
					                <el-table-column prop="env" label="环境" min-width="100"></el-table-column>
 | 
				
			||||||
                <el-table-column prop="host" label="host:port" width></el-table-column>
 | 
					                <el-table-column prop="host" label="host:port" min-width="150" show-overflow-tooltip> </el-table-column>
 | 
				
			||||||
                <el-table-column prop="createTime" label="创建时间">
 | 
					                <el-table-column prop="mode" label="mode" min-width="100"></el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="createTime" label="创建时间" min-width="160">
 | 
				
			||||||
                    <template #default="scope">
 | 
					                    <template #default="scope">
 | 
				
			||||||
                        {{ $filters.dateFormat(scope.row.createTime) }}
 | 
					                        {{ $filters.dateFormat(scope.row.createTime) }}
 | 
				
			||||||
                    </template>
 | 
					                    </template>
 | 
				
			||||||
                </el-table-column>
 | 
					                </el-table-column>
 | 
				
			||||||
                <el-table-column prop="creator" label="创建人"></el-table-column>
 | 
					                <el-table-column prop="creator" label="创建人" min-width="100"></el-table-column>
 | 
				
			||||||
                <el-table-column label="操作" width>
 | 
					                <el-table-column label="更多" min-width="130" fixed="right">
 | 
				
			||||||
                    <template #default="scope">
 | 
					                    <template #default="scope">
 | 
				
			||||||
                        <el-button type="primary" @click="info(scope.row)" icon="tickets" plain size="small">info</el-button>
 | 
					                        <el-link v-if="scope.row.mode == 'standalone'" type="primary" @click="info(scope.row)" :underline="false">单机信息</el-link>
 | 
				
			||||||
                        <!-- <el-button type="success" @click="manage(scope.row)" :ref="scope.row"  plain>数据管理</el-button> -->
 | 
					                        <el-link @click="onShowClusterInfo(scope.row)" v-if="scope.row.mode == 'cluster'" type="success" :underline="false"
 | 
				
			||||||
 | 
					                            >集群信息</el-link
 | 
				
			||||||
 | 
					                        >
 | 
				
			||||||
                    </template>
 | 
					                    </template>
 | 
				
			||||||
                </el-table-column>
 | 
					                </el-table-column>
 | 
				
			||||||
            </el-table>
 | 
					            </el-table>
 | 
				
			||||||
@@ -52,6 +52,84 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        <info v-model:visible="infoDialog.visible" :title="infoDialog.title" :info="infoDialog.info"></info>
 | 
					        <info v-model:visible="infoDialog.visible" :title="infoDialog.title" :info="infoDialog.info"></info>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        <el-dialog width="1000px" title="集群信息" v-model="clusterInfoDialog.visible">
 | 
				
			||||||
 | 
					            <el-input type="textarea" :autosize="{ minRows: 12, maxRows: 12 }" v-model="clusterInfoDialog.info"> </el-input>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            <el-divider content-position="left">节点信息</el-divider>
 | 
				
			||||||
 | 
					            <el-table :data="clusterInfoDialog.nodes" stripe size="small" border>
 | 
				
			||||||
 | 
					                <el-table-column prop="nodeId" label="nodeId" min-width="300">
 | 
				
			||||||
 | 
					                    <template #header>
 | 
				
			||||||
 | 
					                        nodeId
 | 
				
			||||||
 | 
					                        <el-tooltip class="box-item" effect="dark" content="节点id" placement="top">
 | 
				
			||||||
 | 
					                            <el-icon><question-filled /></el-icon>
 | 
				
			||||||
 | 
					                        </el-tooltip>
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="ip" label="ip" min-width="180">
 | 
				
			||||||
 | 
					                    <template #header>
 | 
				
			||||||
 | 
					                        ip
 | 
				
			||||||
 | 
					                        <el-tooltip
 | 
				
			||||||
 | 
					                            class="box-item"
 | 
				
			||||||
 | 
					                            effect="dark"
 | 
				
			||||||
 | 
					                            content="ip:port1@port2:port1指redis服务器与客户端通信的端口,port2则是集群内部节点间通信的端口"
 | 
				
			||||||
 | 
					                            placement="top"
 | 
				
			||||||
 | 
					                        >
 | 
				
			||||||
 | 
					                            <el-icon><question-filled /></el-icon>
 | 
				
			||||||
 | 
					                        </el-tooltip>
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                    <template #default="scope">
 | 
				
			||||||
 | 
					                        <el-tag
 | 
				
			||||||
 | 
					                            @click="info({ id: clusterInfoDialog.redisId, ip: scope.row.ip })"
 | 
				
			||||||
 | 
					                            effect="plain"
 | 
				
			||||||
 | 
					                            type="success"
 | 
				
			||||||
 | 
					                            size="small"
 | 
				
			||||||
 | 
					                            style="cursor: pointer"
 | 
				
			||||||
 | 
					                            >{{ scope.row.ip }}</el-tag
 | 
				
			||||||
 | 
					                        >
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="flags" label="flags" min-width="110"></el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="masterSlaveRelation" label="masterSlaveRelation" min-width="300">
 | 
				
			||||||
 | 
					                    <template #header>
 | 
				
			||||||
 | 
					                        masterSlaveRelation
 | 
				
			||||||
 | 
					                        <el-tooltip
 | 
				
			||||||
 | 
					                            class="box-item"
 | 
				
			||||||
 | 
					                            effect="dark"
 | 
				
			||||||
 | 
					                            content="如果节点是slave,并且已知master节点,则为master节点ID;否则为符号'-'"
 | 
				
			||||||
 | 
					                            placement="top"
 | 
				
			||||||
 | 
					                        >
 | 
				
			||||||
 | 
					                            <el-icon><question-filled /></el-icon>
 | 
				
			||||||
 | 
					                        </el-tooltip>
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="pingSent" label="pingSent" min-width="130" show-overflow-tooltip>
 | 
				
			||||||
 | 
					                    <template #default="scope">
 | 
				
			||||||
 | 
					                        {{ scope.row.pingSent == 0 ? 0 : new Date(parseInt(scope.row.pingSent)).toLocaleString() }}
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="pongRecv" label="pongRecv" min-width="130" show-overflow-tooltip>
 | 
				
			||||||
 | 
					                    <template #default="scope">
 | 
				
			||||||
 | 
					                        {{ scope.row.pongRecv == 0 ? 0 : new Date(parseInt(scope.row.pongRecv)).toLocaleString() }}
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="configEpoch" label="configEpoch" min-width="130">
 | 
				
			||||||
 | 
					                    <template #header>
 | 
				
			||||||
 | 
					                        configEpoch
 | 
				
			||||||
 | 
					                        <el-tooltip
 | 
				
			||||||
 | 
					                            class="box-item"
 | 
				
			||||||
 | 
					                            effect="dark"
 | 
				
			||||||
 | 
					                            content="节点的epoch值(如果该节点是从节点,则为其主节点的epoch值)。每当节点发生失败切换时,都会创建一个新的,独特的,递增的epoch。"
 | 
				
			||||||
 | 
					                            placement="top"
 | 
				
			||||||
 | 
					                        >
 | 
				
			||||||
 | 
					                            <el-icon><question-filled /></el-icon>
 | 
				
			||||||
 | 
					                        </el-tooltip>
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="linkState" label="linkState" min-width="100"></el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="slot" label="slot" min-width="100"></el-table-column>
 | 
				
			||||||
 | 
					            </el-table>
 | 
				
			||||||
 | 
					        </el-dialog>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        <redis-edit
 | 
					        <redis-edit
 | 
				
			||||||
            @val-change="valChange"
 | 
					            @val-change="valChange"
 | 
				
			||||||
            :projects="projects"
 | 
					            :projects="projects"
 | 
				
			||||||
@@ -92,6 +170,12 @@ export default defineComponent({
 | 
				
			|||||||
            redisInfo: {
 | 
					            redisInfo: {
 | 
				
			||||||
                url: '',
 | 
					                url: '',
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
 | 
					            clusterInfoDialog: {
 | 
				
			||||||
 | 
					                visible: false,
 | 
				
			||||||
 | 
					                redisId: 0,
 | 
				
			||||||
 | 
					                info: '',
 | 
				
			||||||
 | 
					                nodes: [],
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
            clusters: [
 | 
					            clusters: [
 | 
				
			||||||
                {
 | 
					                {
 | 
				
			||||||
                    id: 0,
 | 
					                    id: 0,
 | 
				
			||||||
@@ -118,7 +202,7 @@ export default defineComponent({
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
        onMounted(async () => {
 | 
					        onMounted(async () => {
 | 
				
			||||||
            search();
 | 
					            search();
 | 
				
			||||||
            state.projects = (await projectApi.projects.request({ pageNum: 1, pageSize: 100 })).list;
 | 
					            state.projects = await projectApi.accountProjects.request(null);
 | 
				
			||||||
        });
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const handlePageChange = (curPage: number) => {
 | 
					        const handlePageChange = (curPage: number) => {
 | 
				
			||||||
@@ -134,12 +218,6 @@ export default defineComponent({
 | 
				
			|||||||
            state.currentData = item;
 | 
					            state.currentData = item;
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // connect() {
 | 
					 | 
				
			||||||
        //   Req.post('/open/redis/connect', this.form, res => {
 | 
					 | 
				
			||||||
        //     this.redisInfo = res
 | 
					 | 
				
			||||||
        //   })
 | 
					 | 
				
			||||||
        // }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        const deleteRedis = async () => {
 | 
					        const deleteRedis = async () => {
 | 
				
			||||||
            try {
 | 
					            try {
 | 
				
			||||||
                await ElMessageBox.confirm(`确定删除该redis?`, '提示', {
 | 
					                await ElMessageBox.confirm(`确定删除该redis?`, '提示', {
 | 
				
			||||||
@@ -155,12 +233,23 @@ export default defineComponent({
 | 
				
			|||||||
            } catch (err) {}
 | 
					            } catch (err) {}
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const info = (redis: any) => {
 | 
					        const info = async (redis: any) => {
 | 
				
			||||||
            redisApi.redisInfo.request({ id: redis.id }).then((res: any) => {
 | 
					            var host = redis.host;
 | 
				
			||||||
 | 
					            if (redis.ip) {
 | 
				
			||||||
 | 
					                host = redis.ip.split('@')[0];
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					            const res = await redisApi.redisInfo.request({ id: redis.id, host });
 | 
				
			||||||
            state.infoDialog.info = res;
 | 
					            state.infoDialog.info = res;
 | 
				
			||||||
                state.infoDialog.title = `'${redis.host}' info`;
 | 
					            state.infoDialog.title = `'${host}' info`;
 | 
				
			||||||
            state.infoDialog.visible = true;
 | 
					            state.infoDialog.visible = true;
 | 
				
			||||||
            });
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const onShowClusterInfo = async (redis: any) => {
 | 
				
			||||||
 | 
					            const ci = await redisApi.clusterInfo.request({ id: redis.id });
 | 
				
			||||||
 | 
					            state.clusterInfoDialog.info = ci.clusterInfo;
 | 
				
			||||||
 | 
					            state.clusterInfoDialog.nodes = ci.clusterNodes;
 | 
				
			||||||
 | 
					            state.clusterInfoDialog.redisId = redis.id;
 | 
				
			||||||
 | 
					            state.clusterInfoDialog.visible = true;
 | 
				
			||||||
        };
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        const search = async () => {
 | 
					        const search = async () => {
 | 
				
			||||||
@@ -192,6 +281,7 @@ export default defineComponent({
 | 
				
			|||||||
            handlePageChange,
 | 
					            handlePageChange,
 | 
				
			||||||
            choose,
 | 
					            choose,
 | 
				
			||||||
            info,
 | 
					            info,
 | 
				
			||||||
 | 
					            onShowClusterInfo,
 | 
				
			||||||
            deleteRedis,
 | 
					            deleteRedis,
 | 
				
			||||||
            editRedis,
 | 
					            editRedis,
 | 
				
			||||||
            valChange,
 | 
					            valChange,
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -3,10 +3,11 @@ import Api from '@/common/Api';
 | 
				
			|||||||
export const redisApi = {
 | 
					export const redisApi = {
 | 
				
			||||||
    redisList : Api.create("/redis", 'get'),
 | 
					    redisList : Api.create("/redis", 'get'),
 | 
				
			||||||
    redisInfo: Api.create("/redis/{id}/info", 'get'),
 | 
					    redisInfo: Api.create("/redis/{id}/info", 'get'),
 | 
				
			||||||
 | 
					    clusterInfo: Api.create("/redis/{id}/cluster-info", 'get'),
 | 
				
			||||||
    saveRedis: Api.create("/redis", 'post'),
 | 
					    saveRedis: Api.create("/redis", 'post'),
 | 
				
			||||||
    delRedis: Api.create("/redis/{id}", 'delete'),
 | 
					    delRedis: Api.create("/redis/{id}", 'delete'),
 | 
				
			||||||
    // 获取权限列表
 | 
					    // 获取权限列表
 | 
				
			||||||
    scan: Api.create("/redis/{id}/scan/{cursor}/{count}", 'get'),
 | 
					    scan: Api.create("/redis/{id}/scan", 'post'),
 | 
				
			||||||
    getStringValue: Api.create("/redis/{id}/string-value", 'get'),
 | 
					    getStringValue: Api.create("/redis/{id}/string-value", 'get'),
 | 
				
			||||||
    saveStringValue: Api.create("/redis/{id}/string-value", 'post'),
 | 
					    saveStringValue: Api.create("/redis/{id}/string-value", 'post'),
 | 
				
			||||||
    getHashValue: Api.create("/redis/{id}/hash-value", 'get'),
 | 
					    getHashValue: Api.create("/redis/{id}/hash-value", 'get'),
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -3,7 +3,7 @@
 | 
				
			|||||||
        <el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :show-close="false" width="35%" :destroy-on-close="true">
 | 
					        <el-dialog :title="title" v-model="dialogVisible" :before-close="cancel" :show-close="false" width="35%" :destroy-on-close="true">
 | 
				
			||||||
            <el-form :model="form" ref="accountForm" :rules="rules" label-width="85px">
 | 
					            <el-form :model="form" ref="accountForm" :rules="rules" label-width="85px">
 | 
				
			||||||
                <el-form-item prop="username" label="用户名:" required>
 | 
					                <el-form-item prop="username" label="用户名:" required>
 | 
				
			||||||
                    <el-input :disabled="edit" v-model.trim="form.username" placeholder="请输入账号用户名" auto-complete="off"></el-input>
 | 
					                    <el-input :disabled="edit" v-model.trim="form.username" placeholder="请输入账号用户名,密码默认与账号名一致" auto-complete="off"></el-input>
 | 
				
			||||||
                </el-form-item>
 | 
					                </el-form-item>
 | 
				
			||||||
                <!-- <el-form-item prop="password" label="密码:" required>
 | 
					                <!-- <el-form-item prop="password" label="密码:" required>
 | 
				
			||||||
                    <el-input type="password" v-model.trim="form.password" placeholder="请输入密码" autocomplete="new-password"></el-input>
 | 
					                    <el-input type="password" v-model.trim="form.password" placeholder="请输入密码" autocomplete="new-password"></el-input>
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -2,7 +2,7 @@
 | 
				
			|||||||
    <div class="role-list">
 | 
					    <div class="role-list">
 | 
				
			||||||
        <el-card>
 | 
					        <el-card>
 | 
				
			||||||
            <el-button v-auth="'account:add'" type="primary" icon="plus" @click="editAccount(true)">添加</el-button>
 | 
					            <el-button v-auth="'account:add'" type="primary" icon="plus" @click="editAccount(true)">添加</el-button>
 | 
				
			||||||
            <el-button v-auth="'account:update'" :disabled="chooseId == null" @click="editAccount(false)" type="primary" icon="edit">编辑</el-button>
 | 
					            <!-- <el-button v-auth="'account:update'" :disabled="chooseId == null" @click="editAccount(false)" type="primary" icon="edit">编辑</el-button> -->
 | 
				
			||||||
            <el-button v-auth="'account:saveRoles'" :disabled="chooseId == null" @click="roleEdit()" type="success" icon="setting"
 | 
					            <el-button v-auth="'account:saveRoles'" :disabled="chooseId == null" @click="roleEdit()" type="success" icon="setting"
 | 
				
			||||||
                >角色分配</el-button
 | 
					                >角色分配</el-button
 | 
				
			||||||
            >
 | 
					            >
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -33,5 +33,5 @@ export const accountApi = {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
export const logApi = {
 | 
					export const logApi = {
 | 
				
			||||||
    list: Api.create("/sys/logs", "get")
 | 
					    list: Api.create("/syslogs", "get")
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -10,15 +10,14 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
            <div style="float: right">
 | 
					            <div style="float: right">
 | 
				
			||||||
                <el-input
 | 
					                <el-input
 | 
				
			||||||
                    placeholder="请输入角色名称!"
 | 
					                    placeholder="请输入角色名称"
 | 
				
			||||||
                    class="mr2"
 | 
					                    class="mr2"
 | 
				
			||||||
                    size="small"
 | 
					                    style="width: 200px"
 | 
				
			||||||
                    style="width: 300px"
 | 
					 | 
				
			||||||
                    v-model="query.name"
 | 
					                    v-model="query.name"
 | 
				
			||||||
                    @clear="search"
 | 
					                    @clear="search"
 | 
				
			||||||
                    clearable
 | 
					                    clearable
 | 
				
			||||||
                ></el-input>
 | 
					                ></el-input>
 | 
				
			||||||
                <el-button @click="search" type="success" icon="search" size="small"></el-button>
 | 
					                <el-button @click="search" type="success" icon="search"></el-button>
 | 
				
			||||||
            </div>
 | 
					            </div>
 | 
				
			||||||
            <el-table :data="roles" @current-change="choose" ref="table" style="width: 100%">
 | 
					            <el-table :data="roles" @current-change="choose" ref="table" style="width: 100%">
 | 
				
			||||||
                <el-table-column label="选择" width="50px">
 | 
					                <el-table-column label="选择" width="50px">
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										103
									
								
								mayfly_go_web/src/views/system/syslog/SyslogList.vue
									
									
									
									
									
										Executable file
									
								
							
							
						
						
									
										103
									
								
								mayfly_go_web/src/views/system/syslog/SyslogList.vue
									
									
									
									
									
										Executable file
									
								
							@@ -0,0 +1,103 @@
 | 
				
			|||||||
 | 
					<template>
 | 
				
			||||||
 | 
					    <div class="role-list">
 | 
				
			||||||
 | 
					        <el-card>
 | 
				
			||||||
 | 
					            <div style="float: right">
 | 
				
			||||||
 | 
					                <el-select
 | 
				
			||||||
 | 
					                    remote
 | 
				
			||||||
 | 
					                    :remote-method="getAccount"
 | 
				
			||||||
 | 
					                    v-model="query.creatorId"
 | 
				
			||||||
 | 
					                    filterable
 | 
				
			||||||
 | 
					                    placeholder="请输入并选择账号"
 | 
				
			||||||
 | 
					                    clearable
 | 
				
			||||||
 | 
					                    class="mr5"
 | 
				
			||||||
 | 
					                >
 | 
				
			||||||
 | 
					                    <el-option v-for="item in accounts" :key="item.id" :label="item.username" :value="item.id"> </el-option>
 | 
				
			||||||
 | 
					                </el-select>
 | 
				
			||||||
 | 
					                <el-select v-model="query.type" filterable placeholder="请选择操作结果" clearable class="mr5">
 | 
				
			||||||
 | 
					                    <el-option label="成功" :value="1"> </el-option>
 | 
				
			||||||
 | 
					                    <el-option label="失败" :value="2"> </el-option>
 | 
				
			||||||
 | 
					                </el-select>
 | 
				
			||||||
 | 
					                <el-button @click="search" type="success" icon="search"></el-button>
 | 
				
			||||||
 | 
					            </div>
 | 
				
			||||||
 | 
					            <el-table :data="logs" style="width: 100%">
 | 
				
			||||||
 | 
					                <el-table-column prop="creator" label="操作人" min-width="100" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="createTime" label="操作时间" min-width="160">
 | 
				
			||||||
 | 
					                    <template #default="scope">
 | 
				
			||||||
 | 
					                        {{ $filters.dateFormat(scope.row.createTime) }}
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="type" label="结果" min-width="65">
 | 
				
			||||||
 | 
					                    <template #default="scope">
 | 
				
			||||||
 | 
					                        <el-tag v-if="scope.row.type == 1" type="success" size="small">成功</el-tag>
 | 
				
			||||||
 | 
					                        <el-tag v-if="scope.row.type == 2" type="danger" size="small">失败</el-tag>
 | 
				
			||||||
 | 
					                    </template>
 | 
				
			||||||
 | 
					                </el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="description" label="描述" min-width="160" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                <el-table-column prop="reqParam" label="请求信息" min-width="300" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
 | 
					                <el-table-column prop="resp" label="响应信息" min-width="200" show-overflow-tooltip></el-table-column>
 | 
				
			||||||
 | 
					            </el-table>
 | 
				
			||||||
 | 
					            <el-row style="margin-top: 20px" type="flex" justify="end">
 | 
				
			||||||
 | 
					                <el-pagination
 | 
				
			||||||
 | 
					                    style="text-align: right"
 | 
				
			||||||
 | 
					                    @current-change="handlePageChange"
 | 
				
			||||||
 | 
					                    :total="total"
 | 
				
			||||||
 | 
					                    layout="prev, pager, next, total, jumper"
 | 
				
			||||||
 | 
					                    v-model:current-page="query.pageNum"
 | 
				
			||||||
 | 
					                    :page-size="query.pageSize"
 | 
				
			||||||
 | 
					                ></el-pagination>
 | 
				
			||||||
 | 
					            </el-row>
 | 
				
			||||||
 | 
					        </el-card>
 | 
				
			||||||
 | 
					    </div>
 | 
				
			||||||
 | 
					</template>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					<script lang="ts">
 | 
				
			||||||
 | 
					import { toRefs, reactive, onMounted, defineComponent } from 'vue';
 | 
				
			||||||
 | 
					import { logApi, accountApi } from '../api';
 | 
				
			||||||
 | 
					export default defineComponent({
 | 
				
			||||||
 | 
					    name: 'SyslogList',
 | 
				
			||||||
 | 
					    components: {},
 | 
				
			||||||
 | 
					    setup() {
 | 
				
			||||||
 | 
					        const state = reactive({
 | 
				
			||||||
 | 
					            query: {
 | 
				
			||||||
 | 
					                pageNum: 1,
 | 
				
			||||||
 | 
					                pageSize: 10,
 | 
				
			||||||
 | 
					                name: null,
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
 | 
					            total: 0,
 | 
				
			||||||
 | 
					            logs: [],
 | 
				
			||||||
 | 
					            accounts: [],
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        onMounted(() => {
 | 
				
			||||||
 | 
					            search();
 | 
				
			||||||
 | 
					        });
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const search = async () => {
 | 
				
			||||||
 | 
					            let res = await logApi.list.request(state.query);
 | 
				
			||||||
 | 
					            state.logs = res.list;
 | 
				
			||||||
 | 
					            state.total = res.total;
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const handlePageChange = (curPage: number) => {
 | 
				
			||||||
 | 
					            state.query.pageNum = curPage;
 | 
				
			||||||
 | 
					            search();
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        const getAccount = (username: any) => {
 | 
				
			||||||
 | 
					            accountApi.list.request({ username }).then((res) => {
 | 
				
			||||||
 | 
					                state.accounts = res.list;
 | 
				
			||||||
 | 
					            });
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return {
 | 
				
			||||||
 | 
					            ...toRefs(state),
 | 
				
			||||||
 | 
					            search,
 | 
				
			||||||
 | 
					            handlePageChange,
 | 
				
			||||||
 | 
					            getAccount,
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					    },
 | 
				
			||||||
 | 
					});
 | 
				
			||||||
 | 
					</script>
 | 
				
			||||||
 | 
					<style lang="scss">
 | 
				
			||||||
 | 
					</style>
 | 
				
			||||||
@@ -30,7 +30,6 @@ const viteConfig: UserConfig = {
 | 
				
			|||||||
				target: 'http://localhost:8888',
 | 
									target: 'http://localhost:8888',
 | 
				
			||||||
				ws: true,
 | 
									ws: true,
 | 
				
			||||||
				changeOrigin: true,
 | 
									changeOrigin: true,
 | 
				
			||||||
				rewrite: (path) => path.replace(/^\/api/, '/'),
 | 
					 | 
				
			||||||
			},
 | 
								},
 | 
				
			||||||
		},
 | 
							},
 | 
				
			||||||
	},
 | 
						},
 | 
				
			||||||
 
 | 
				
			|||||||
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							@@ -1,6 +1,6 @@
 | 
				
			|||||||
app:
 | 
					app:
 | 
				
			||||||
  name: mayfly-go
 | 
					  name: mayfly-go
 | 
				
			||||||
  version: 1.0.0
 | 
					  version: 1.2.0
 | 
				
			||||||
  
 | 
					  
 | 
				
			||||||
server:
 | 
					server:
 | 
				
			||||||
  # debug release test
 | 
					  # debug release test
 | 
				
			||||||
@@ -29,10 +29,6 @@ jwt:
 | 
				
			|||||||
  # 过期时间单位分钟
 | 
					  # 过期时间单位分钟
 | 
				
			||||||
  expire-time: 1440
 | 
					  expire-time: 1440
 | 
				
			||||||
 | 
					
 | 
				
			||||||
redis:
 | 
					 | 
				
			||||||
  host: 127.0.0.1
 | 
					 | 
				
			||||||
  port: 6379
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
mysql:
 | 
					mysql:
 | 
				
			||||||
  host: localhost:3306
 | 
					  host: localhost:3306
 | 
				
			||||||
  username: root
 | 
					  username: root
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,19 +1,20 @@
 | 
				
			|||||||
module mayfly-go
 | 
					module mayfly-go
 | 
				
			||||||
 | 
					
 | 
				
			||||||
go 1.17
 | 
					go 1.18
 | 
				
			||||||
 | 
					
 | 
				
			||||||
require (
 | 
					require (
 | 
				
			||||||
	github.com/dgrijalva/jwt-go v3.2.0+incompatible // jwt
 | 
						github.com/dgrijalva/jwt-go v3.2.0+incompatible // jwt
 | 
				
			||||||
	github.com/gin-gonic/gin v1.7.7
 | 
						github.com/gin-gonic/gin v1.8.1
 | 
				
			||||||
	github.com/go-redis/redis v6.15.9+incompatible
 | 
						github.com/go-redis/redis/v8 v8.11.5
 | 
				
			||||||
	github.com/gorilla/websocket v1.5.0
 | 
						github.com/gorilla/websocket v1.5.0
 | 
				
			||||||
 | 
						github.com/lib/pq v1.10.6
 | 
				
			||||||
	github.com/mojocn/base64Captcha v1.3.5 // 验证码
 | 
						github.com/mojocn/base64Captcha v1.3.5 // 验证码
 | 
				
			||||||
	github.com/pkg/sftp v1.13.4
 | 
						github.com/pkg/sftp v1.13.5
 | 
				
			||||||
	github.com/robfig/cron/v3 v3.0.1 // 定时任务
 | 
						github.com/robfig/cron/v3 v3.0.1 // 定时任务
 | 
				
			||||||
	github.com/sirupsen/logrus v1.8.1
 | 
						github.com/sirupsen/logrus v1.8.1
 | 
				
			||||||
	github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2
 | 
						github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2
 | 
				
			||||||
	go.mongodb.org/mongo-driver v1.9.1 // mongo
 | 
						go.mongodb.org/mongo-driver v1.9.1 // mongo
 | 
				
			||||||
	golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // ssh
 | 
						golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // ssh
 | 
				
			||||||
	gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
 | 
						gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
 | 
				
			||||||
	// gorm
 | 
						// gorm
 | 
				
			||||||
	gorm.io/driver/mysql v1.3.4
 | 
						gorm.io/driver/mysql v1.3.4
 | 
				
			||||||
@@ -21,14 +22,16 @@ require (
 | 
				
			|||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
require (
 | 
					require (
 | 
				
			||||||
 | 
						github.com/cespare/xxhash/v2 v2.1.2 // indirect
 | 
				
			||||||
 | 
						github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
 | 
				
			||||||
	github.com/gin-contrib/sse v0.1.0 // indirect
 | 
						github.com/gin-contrib/sse v0.1.0 // indirect
 | 
				
			||||||
	github.com/go-playground/locales v0.14.0 // indirect
 | 
						github.com/go-playground/locales v0.14.0 // indirect
 | 
				
			||||||
	github.com/go-playground/universal-translator v0.18.0 // indirect
 | 
						github.com/go-playground/universal-translator v0.18.0 // indirect
 | 
				
			||||||
	github.com/go-playground/validator/v10 v10.10.1 // indirect
 | 
						github.com/go-playground/validator/v10 v10.10.1 // indirect
 | 
				
			||||||
	github.com/go-sql-driver/mysql v1.6.0 // indirect
 | 
						github.com/go-sql-driver/mysql v1.6.0 // indirect
 | 
				
			||||||
	github.com/go-stack/stack v1.8.0 // indirect
 | 
						github.com/go-stack/stack v1.8.0 // indirect
 | 
				
			||||||
 | 
						github.com/goccy/go-json v0.9.7 // indirect
 | 
				
			||||||
	github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
 | 
						github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
 | 
				
			||||||
	github.com/golang/protobuf v1.5.2 // indirect
 | 
					 | 
				
			||||||
	github.com/golang/snappy v0.0.1 // indirect
 | 
						github.com/golang/snappy v0.0.1 // indirect
 | 
				
			||||||
	github.com/jinzhu/inflection v1.0.0 // indirect
 | 
						github.com/jinzhu/inflection v1.0.0 // indirect
 | 
				
			||||||
	github.com/jinzhu/now v1.1.4 // indirect
 | 
						github.com/jinzhu/now v1.1.4 // indirect
 | 
				
			||||||
@@ -39,8 +42,7 @@ require (
 | 
				
			|||||||
	github.com/mattn/go-isatty v0.0.14 // indirect
 | 
						github.com/mattn/go-isatty v0.0.14 // indirect
 | 
				
			||||||
	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
 | 
						github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
 | 
				
			||||||
	github.com/modern-go/reflect2 v1.0.2 // indirect
 | 
						github.com/modern-go/reflect2 v1.0.2 // indirect
 | 
				
			||||||
	github.com/onsi/ginkgo v1.16.5 // indirect
 | 
						github.com/pelletier/go-toml/v2 v2.0.1 // indirect
 | 
				
			||||||
	github.com/onsi/gomega v1.18.1 // indirect
 | 
					 | 
				
			||||||
	github.com/pkg/errors v0.9.1 // indirect
 | 
						github.com/pkg/errors v0.9.1 // indirect
 | 
				
			||||||
	github.com/ugorji/go/codec v1.2.7 // indirect
 | 
						github.com/ugorji/go/codec v1.2.7 // indirect
 | 
				
			||||||
	github.com/xdg-go/pbkdf2 v1.0.0 // indirect
 | 
						github.com/xdg-go/pbkdf2 v1.0.0 // indirect
 | 
				
			||||||
@@ -48,9 +50,11 @@ require (
 | 
				
			|||||||
	github.com/xdg-go/stringprep v1.0.2 // indirect
 | 
						github.com/xdg-go/stringprep v1.0.2 // indirect
 | 
				
			||||||
	github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
 | 
						github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
 | 
				
			||||||
	golang.org/x/image v0.0.0-20220302094943-723b81ca9867 // indirect
 | 
						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/sync v0.0.0-20201020160332-67f06af15bc9 // indirect
 | 
				
			||||||
	golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 // indirect
 | 
						golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 // indirect
 | 
				
			||||||
	golang.org/x/text v0.3.7 // indirect
 | 
						golang.org/x/text v0.3.7 // indirect
 | 
				
			||||||
	google.golang.org/protobuf v1.27.1 // indirect
 | 
						golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
 | 
				
			||||||
 | 
						google.golang.org/protobuf v1.28.0 // indirect
 | 
				
			||||||
	gopkg.in/yaml.v2 v2.4.0 // indirect
 | 
						gopkg.in/yaml.v2 v2.4.0 // indirect
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -2,7 +2,7 @@ package initialize
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	common_index_router "mayfly-go/internal/common/router"
 | 
						common_router "mayfly-go/internal/common/router"
 | 
				
			||||||
	devops_router "mayfly-go/internal/devops/router"
 | 
						devops_router "mayfly-go/internal/devops/router"
 | 
				
			||||||
	sys_router "mayfly-go/internal/sys/router"
 | 
						sys_router "mayfly-go/internal/sys/router"
 | 
				
			||||||
	"mayfly-go/pkg/config"
 | 
						"mayfly-go/pkg/config"
 | 
				
			||||||
@@ -46,13 +46,15 @@ func InitRouter() *gin.Engine {
 | 
				
			|||||||
	// 设置路由组
 | 
						// 设置路由组
 | 
				
			||||||
	api := router.Group("/api")
 | 
						api := router.Group("/api")
 | 
				
			||||||
	{
 | 
						{
 | 
				
			||||||
		common_index_router.InitIndexRouter(api)
 | 
							common_router.InitIndexRouter(api)
 | 
				
			||||||
 | 
							common_router.InitCommonRouter(api)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		sys_router.InitCaptchaRouter(api)
 | 
							sys_router.InitCaptchaRouter(api)
 | 
				
			||||||
		sys_router.InitAccountRouter(api) // 注册account路由
 | 
							sys_router.InitAccountRouter(api) // 注册account路由
 | 
				
			||||||
		sys_router.InitResourceRouter(api)
 | 
							sys_router.InitResourceRouter(api)
 | 
				
			||||||
		sys_router.InitRoleRouter(api)
 | 
							sys_router.InitRoleRouter(api)
 | 
				
			||||||
		sys_router.InitSystemRouter(api)
 | 
							sys_router.InitSystemRouter(api)
 | 
				
			||||||
 | 
							sys_router.InitSyslogRouter(api)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		devops_router.InitProjectRouter(api)
 | 
							devops_router.InitProjectRouter(api)
 | 
				
			||||||
		devops_router.InitDbRouter(api)
 | 
							devops_router.InitDbRouter(api)
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										10
									
								
								server/initialize/savelog.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								server/initialize/savelog.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,10 @@
 | 
				
			|||||||
 | 
					package initialize
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						sys_application "mayfly-go/internal/sys/application"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/ctx"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func InitSaveLogFunc() ctx.SaveLogFunc {
 | 
				
			||||||
 | 
						return sys_application.SyslogApp.SaveFromReq
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										16
									
								
								server/internal/common/api/common.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								server/internal/common/api/common.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,16 @@
 | 
				
			|||||||
 | 
					package api
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"mayfly-go/pkg/biz"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/ctx"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/utils"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type Common struct {
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (i *Common) RasPublicKey(rc *ctx.ReqCtx) {
 | 
				
			||||||
 | 
						publicKeyStr, err := utils.GetRsaPublicKey()
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "rsa生成公私钥失败")
 | 
				
			||||||
 | 
						rc.ResData = publicKeyStr
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										21
									
								
								server/internal/common/router/common.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								server/internal/common/router/common.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,21 @@
 | 
				
			|||||||
 | 
					package router
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"mayfly-go/internal/common/api"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/ctx"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/gin-gonic/gin"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func InitCommonRouter(router *gin.RouterGroup) {
 | 
				
			||||||
 | 
						common := router.Group("common")
 | 
				
			||||||
 | 
						c := &api.Common{}
 | 
				
			||||||
 | 
						{
 | 
				
			||||||
 | 
							// 获取公钥
 | 
				
			||||||
 | 
							common.GET("public-key", func(g *gin.Context) {
 | 
				
			||||||
 | 
								ctx.NewReqCtxWithGin(g).
 | 
				
			||||||
 | 
									WithNeedToken(false).
 | 
				
			||||||
 | 
									Handle(c.RasPublicKey)
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -2,7 +2,7 @@ package api
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"io/ioutil"
 | 
						"io"
 | 
				
			||||||
	"mayfly-go/internal/devops/api/form"
 | 
						"mayfly-go/internal/devops/api/form"
 | 
				
			||||||
	"mayfly-go/internal/devops/api/vo"
 | 
						"mayfly-go/internal/devops/api/vo"
 | 
				
			||||||
	"mayfly-go/internal/devops/application"
 | 
						"mayfly-go/internal/devops/application"
 | 
				
			||||||
@@ -16,8 +16,10 @@ import (
 | 
				
			|||||||
	"mayfly-go/pkg/ws"
 | 
						"mayfly-go/pkg/ws"
 | 
				
			||||||
	"strconv"
 | 
						"strconv"
 | 
				
			||||||
	"strings"
 | 
						"strings"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/gin-gonic/gin"
 | 
						"github.com/gin-gonic/gin"
 | 
				
			||||||
 | 
						"github.com/xwb1989/sqlparser"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Db struct {
 | 
					type Db struct {
 | 
				
			||||||
@@ -27,6 +29,8 @@ type Db struct {
 | 
				
			|||||||
	ProjectApp   application.Project
 | 
						ProjectApp   application.Project
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const DEFAULT_COLUMN_SIZE = 500
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// @router /api/dbs [get]
 | 
					// @router /api/dbs [get]
 | 
				
			||||||
func (d *Db) Dbs(rc *ctx.ReqCtx) {
 | 
					func (d *Db) Dbs(rc *ctx.ReqCtx) {
 | 
				
			||||||
	g := rc.GinCtx
 | 
						g := rc.GinCtx
 | 
				
			||||||
@@ -41,10 +45,18 @@ func (d *Db) Save(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	form := &form.DbForm{}
 | 
						form := &form.DbForm{}
 | 
				
			||||||
	ginx.BindJsonAndValid(rc.GinCtx, form)
 | 
						ginx.BindJsonAndValid(rc.GinCtx, form)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	rc.ReqParam = form
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	db := new(entity.Db)
 | 
						db := new(entity.Db)
 | 
				
			||||||
	utils.Copy(db, form)
 | 
						utils.Copy(db, form)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 密码解密,并使用解密后的赋值
 | 
				
			||||||
 | 
						originPwd, err := utils.DefaultRsaDecrypt(form.Password, true)
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
 | 
				
			||||||
 | 
						db.Password = originPwd
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 密码脱敏记录日志
 | 
				
			||||||
 | 
						form.Password = "****"
 | 
				
			||||||
 | 
						rc.ReqParam = form
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	db.SetBaseInfo(rc.LoginAccount)
 | 
						db.SetBaseInfo(rc.LoginAccount)
 | 
				
			||||||
	d.DbApp.Save(db)
 | 
						d.DbApp.Save(db)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -91,7 +103,7 @@ func (d *Db) ExecSql(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	rc.ReqParam = fmt.Sprintf("db: %d:%s | sql: %s", id, db, sql)
 | 
						rc.ReqParam = fmt.Sprintf("db: %d:%s | sql: %s", id, db, sql)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	biz.NotEmpty(sql, "sql不能为空")
 | 
						biz.NotEmpty(sql, "sql不能为空")
 | 
				
			||||||
	if strings.HasPrefix(sql, "SELECT") || strings.HasPrefix(sql, "select") || strings.HasPrefix(sql, "show") {
 | 
						if strings.HasPrefix(sql, "SELECT") || strings.HasPrefix(sql, "select") || strings.HasPrefix(sql, "show") || strings.HasPrefix(sql, "explain") {
 | 
				
			||||||
		colNames, res, err := dbInstance.SelectData(sql)
 | 
							colNames, res, err := dbInstance.SelectData(sql)
 | 
				
			||||||
		biz.ErrIsNilAppendErr(err, "查询失败: %s")
 | 
							biz.ErrIsNilAppendErr(err, "查询失败: %s")
 | 
				
			||||||
		colAndRes := make(map[string]interface{})
 | 
							colAndRes := make(map[string]interface{})
 | 
				
			||||||
@@ -128,14 +140,12 @@ func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	fileheader, err := g.FormFile("file")
 | 
						fileheader, err := g.FormFile("file")
 | 
				
			||||||
	biz.ErrIsNilAppendErr(err, "读取sql文件失败: %s")
 | 
						biz.ErrIsNilAppendErr(err, "读取sql文件失败: %s")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// 读取sql文件并根据;切割sql语句
 | 
					 | 
				
			||||||
	file, _ := fileheader.Open()
 | 
						file, _ := fileheader.Open()
 | 
				
			||||||
	filename := fileheader.Filename
 | 
						filename := fileheader.Filename
 | 
				
			||||||
	bytes, _ := ioutil.ReadAll(file)
 | 
					 | 
				
			||||||
	sqlContent := string(bytes)
 | 
					 | 
				
			||||||
	sqls := strings.Split(sqlContent, ";")
 | 
					 | 
				
			||||||
	dbId, db := GetIdAndDb(g)
 | 
						dbId, db := GetIdAndDb(g)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						rc.ReqParam = fmt.Sprintf("dbId: %d, db: %s, filename: %s", dbId, db, filename)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	go func() {
 | 
						go func() {
 | 
				
			||||||
		db := d.DbApp.GetDbInstance(dbId, db)
 | 
							db := d.DbApp.GetDbInstance(dbId, db)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -153,12 +163,14 @@ func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
		biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, db.ProjectId), "%s")
 | 
							biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, db.ProjectId), "%s")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		for _, sql := range sqls {
 | 
							tokens := sqlparser.NewTokenizer(file)
 | 
				
			||||||
			sql = strings.Trim(sql, " ")
 | 
							for {
 | 
				
			||||||
			if sql == "" || sql == "\n" {
 | 
								stmt, err := sqlparser.ParseNext(tokens)
 | 
				
			||||||
				continue
 | 
								if err == io.EOF {
 | 
				
			||||||
 | 
									break
 | 
				
			||||||
			}
 | 
								}
 | 
				
			||||||
			_, err := db.Exec(sql)
 | 
								sql := sqlparser.String(stmt)
 | 
				
			||||||
 | 
								_, err = db.Exec(sql)
 | 
				
			||||||
			if err != nil {
 | 
								if err != nil {
 | 
				
			||||||
				d.MsgApp.CreateAndSend(rc.LoginAccount, ws.ErrMsg("sql脚本执行失败", fmt.Sprintf("[%s]%s执行失败: [%s]", filename, dbInfo, err.Error())))
 | 
									d.MsgApp.CreateAndSend(rc.LoginAccount, ws.ErrMsg("sql脚本执行失败", fmt.Sprintf("[%s]%s执行失败: [%s]", filename, dbInfo, err.Error())))
 | 
				
			||||||
				return
 | 
									return
 | 
				
			||||||
@@ -168,6 +180,97 @@ func (d *Db) ExecSqlFile(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	}()
 | 
						}()
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 数据库dump
 | 
				
			||||||
 | 
					func (d *Db) DumpSql(rc *ctx.ReqCtx) {
 | 
				
			||||||
 | 
						g := rc.GinCtx
 | 
				
			||||||
 | 
						dbId, db := GetIdAndDb(g)
 | 
				
			||||||
 | 
						dumpType := g.Query("type")
 | 
				
			||||||
 | 
						tablesStr := g.Query("tables")
 | 
				
			||||||
 | 
						biz.NotEmpty(tablesStr, "请选择要导出的表")
 | 
				
			||||||
 | 
						tables := strings.Split(tablesStr, ",")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 是否需要导出表结构
 | 
				
			||||||
 | 
						needStruct := dumpType == "1" || dumpType == "3"
 | 
				
			||||||
 | 
						// 是否需要导出数据
 | 
				
			||||||
 | 
						needData := dumpType == "2" || dumpType == "3"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						dbInstance := d.DbApp.GetDbInstance(dbId, db)
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(d.ProjectApp.CanAccess(rc.LoginAccount.Id, dbInstance.ProjectId), "%s")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						now := time.Now()
 | 
				
			||||||
 | 
						filename := fmt.Sprintf("%s.%s.sql", db, now.Format("200601021504"))
 | 
				
			||||||
 | 
						g.Header("Content-Type", "application/octet-stream")
 | 
				
			||||||
 | 
						g.Header("Content-Disposition", "attachment; filename="+filename)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						writer := g.Writer
 | 
				
			||||||
 | 
						writer.WriteString("-- ----------------------------")
 | 
				
			||||||
 | 
						writer.WriteString("\n-- 导出平台: mayfly-go")
 | 
				
			||||||
 | 
						writer.WriteString(fmt.Sprintf("\n-- 导出时间: %s ", now.Format("2006-01-02 15:04:05")))
 | 
				
			||||||
 | 
						writer.WriteString(fmt.Sprintf("\n-- 导出数据库: %s ", db))
 | 
				
			||||||
 | 
						writer.WriteString("\n-- ----------------------------\n")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for _, table := range tables {
 | 
				
			||||||
 | 
							if needStruct {
 | 
				
			||||||
 | 
								writer.WriteString(fmt.Sprintf("\n-- ----------------------------\n-- 表结构: %s \n-- ----------------------------\n", table))
 | 
				
			||||||
 | 
								writer.WriteString(fmt.Sprintf("DROP TABLE IF EXISTS `%s`;\n", table))
 | 
				
			||||||
 | 
								writer.WriteString(dbInstance.GetCreateTableDdl(table)[0]["Create Table"].(string) + ";\n")
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							if !needData {
 | 
				
			||||||
 | 
								continue
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							writer.WriteString(fmt.Sprintf("\n-- ----------------------------\n-- 表记录: %s \n-- ----------------------------\n", table))
 | 
				
			||||||
 | 
							writer.WriteString("BEGIN;\n")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							countSql := fmt.Sprintf("SELECT COUNT(*) count FROM %s", table)
 | 
				
			||||||
 | 
							_, countRes, _ := dbInstance.SelectData(countSql)
 | 
				
			||||||
 | 
							// 查询出所有列信息总数,手动分页获取所有数据
 | 
				
			||||||
 | 
							maCount := int(countRes[0]["count"].(int64))
 | 
				
			||||||
 | 
							// 计算需要查询的页数
 | 
				
			||||||
 | 
							pageNum := maCount / DEFAULT_COLUMN_SIZE
 | 
				
			||||||
 | 
							if maCount%DEFAULT_COLUMN_SIZE > 0 {
 | 
				
			||||||
 | 
								pageNum++
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							var sqlTmp string
 | 
				
			||||||
 | 
							switch dbInstance.Type {
 | 
				
			||||||
 | 
							case "mysql":
 | 
				
			||||||
 | 
								sqlTmp = "SELECT * FROM %s LIMIT %d, %d"
 | 
				
			||||||
 | 
							case "postgres":
 | 
				
			||||||
 | 
								sqlTmp = "SELECT * FROM %s OFFSET %d LIMIT %d"
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							for index := 0; index < pageNum; index++ {
 | 
				
			||||||
 | 
								sql := fmt.Sprintf(sqlTmp, table, index*DEFAULT_COLUMN_SIZE, DEFAULT_COLUMN_SIZE)
 | 
				
			||||||
 | 
								columns, result, _ := dbInstance.SelectData(sql)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								insertSql := "INSERT INTO `%s` VALUES (%s);\n"
 | 
				
			||||||
 | 
								for _, res := range result {
 | 
				
			||||||
 | 
									var values []string
 | 
				
			||||||
 | 
									for _, column := range columns {
 | 
				
			||||||
 | 
										value := res[column]
 | 
				
			||||||
 | 
										if value == nil {
 | 
				
			||||||
 | 
											values = append(values, "NULL")
 | 
				
			||||||
 | 
											continue
 | 
				
			||||||
 | 
										}
 | 
				
			||||||
 | 
										strValue, ok := value.(string)
 | 
				
			||||||
 | 
										if ok {
 | 
				
			||||||
 | 
											values = append(values, fmt.Sprintf("%#v", strValue))
 | 
				
			||||||
 | 
										} else {
 | 
				
			||||||
 | 
											values = append(values, utils.ToString(value))
 | 
				
			||||||
 | 
										}
 | 
				
			||||||
 | 
									}
 | 
				
			||||||
 | 
									writer.WriteString(fmt.Sprintf(insertSql, table, strings.Join(values, ", ")))
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							writer.WriteString("COMMIT;\n")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						rc.NoRes = true
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						rc.ReqParam = fmt.Sprintf("dbId: %d, db: %s, tables: %s, dumpType: %s", dbId, db, tablesStr, dumpType)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// @router /api/db/:dbId/t-metadata [get]
 | 
					// @router /api/db/:dbId/t-metadata [get]
 | 
				
			||||||
func (d *Db) TableMA(rc *ctx.ReqCtx) {
 | 
					func (d *Db) TableMA(rc *ctx.ReqCtx) {
 | 
				
			||||||
	dbi := d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx))
 | 
						dbi := d.DbApp.GetDbInstance(GetIdAndDb(rc.GinCtx))
 | 
				
			||||||
@@ -217,7 +320,7 @@ func (d *Db) HintTables(rc *ctx.ReqCtx) {
 | 
				
			|||||||
		columnName := fmt.Sprintf("%s  [%s]", v["columnName"], v["columnType"])
 | 
							columnName := fmt.Sprintf("%s  [%s]", v["columnName"], v["columnType"])
 | 
				
			||||||
		comment := v["columnComment"]
 | 
							comment := v["columnComment"]
 | 
				
			||||||
		// 如果字段备注不为空,则加上备注信息
 | 
							// 如果字段备注不为空,则加上备注信息
 | 
				
			||||||
		if comment != "" {
 | 
							if comment != nil && comment != "" {
 | 
				
			||||||
			columnName = fmt.Sprintf("%s[%s]", columnName, comment)
 | 
								columnName = fmt.Sprintf("%s[%s]", columnName, comment)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -8,6 +8,7 @@ type DbForm struct {
 | 
				
			|||||||
	Port      int    `binding:"required" json:"port"`
 | 
						Port      int    `binding:"required" json:"port"`
 | 
				
			||||||
	Username  string `binding:"required" json:"username"`
 | 
						Username  string `binding:"required" json:"username"`
 | 
				
			||||||
	Password  string `json:"password"`
 | 
						Password  string `json:"password"`
 | 
				
			||||||
 | 
						Params    string `json:"params"`
 | 
				
			||||||
	Database  string `binding:"required" json:"database"`
 | 
						Database  string `binding:"required" json:"database"`
 | 
				
			||||||
	ProjectId uint64 `binding:"required" json:"projectId"`
 | 
						ProjectId uint64 `binding:"required" json:"projectId"`
 | 
				
			||||||
	Project   string `json:"project"`
 | 
						Project   string `json:"project"`
 | 
				
			||||||
@@ -15,6 +16,13 @@ type DbForm struct {
 | 
				
			|||||||
	EnvId     uint64 `binding:"required" json:"envId"`
 | 
						EnvId     uint64 `binding:"required" json:"envId"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type DbSqlSaveForm struct {
 | 
				
			||||||
 | 
						Name string
 | 
				
			||||||
 | 
						Sql  string `binding:"required"`
 | 
				
			||||||
 | 
						Type int    `binding:"required"`
 | 
				
			||||||
 | 
						Db   string `binding:"required"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 数据库SQL执行表单
 | 
					// 数据库SQL执行表单
 | 
				
			||||||
type DbSqlExecForm struct {
 | 
					type DbSqlExecForm struct {
 | 
				
			||||||
	Db     string `binding:"required" json:"db"`  //数据库名
 | 
						Db     string `binding:"required" json:"db"`  //数据库名
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -38,11 +38,9 @@ type MachineScriptForm struct {
 | 
				
			|||||||
	Script      string `binding:"required"`
 | 
						Script      string `binding:"required"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type DbSqlSaveForm struct {
 | 
					type MachineCreateFileForm struct {
 | 
				
			||||||
	Name string
 | 
						Path string `binding:"required"`
 | 
				
			||||||
	Sql  string `binding:"required"`
 | 
						Type string `binding:"required"`
 | 
				
			||||||
	Type int    `binding:"required"`
 | 
					 | 
				
			||||||
	Db   string `binding:"required"`
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type MachineFileUpdateForm struct {
 | 
					type MachineFileUpdateForm struct {
 | 
				
			||||||
@@ -4,11 +4,13 @@ type Redis struct {
 | 
				
			|||||||
	Id        uint64
 | 
						Id        uint64
 | 
				
			||||||
	Host      string `binding:"required" json:"host"`
 | 
						Host      string `binding:"required" json:"host"`
 | 
				
			||||||
	Password  string `json:"password"`
 | 
						Password  string `json:"password"`
 | 
				
			||||||
 | 
						Mode      string `json:"mode"`
 | 
				
			||||||
	Db        int    `json:"db"`
 | 
						Db        int    `json:"db"`
 | 
				
			||||||
	ProjectId uint64 `binding:"required" json:"projectId"`
 | 
						ProjectId uint64 `binding:"required" json:"projectId"`
 | 
				
			||||||
	Project   string `json:"project"`
 | 
						Project   string `json:"project"`
 | 
				
			||||||
	Env       string `json:"env"`
 | 
						Env       string `json:"env"`
 | 
				
			||||||
	EnvId     uint64 `binding:"required" json:"envId"`
 | 
						EnvId     uint64 `binding:"required" json:"envId"`
 | 
				
			||||||
 | 
						Remark    string `json:"remark"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type KeyInfo struct {
 | 
					type KeyInfo struct {
 | 
				
			||||||
@@ -30,3 +32,9 @@ type SetValue struct {
 | 
				
			|||||||
	KeyInfo
 | 
						KeyInfo
 | 
				
			||||||
	Value []interface{} `binding:"required" json:"value"`
 | 
						Value []interface{} `binding:"required" json:"value"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type RedisScanForm struct {
 | 
				
			||||||
 | 
						Cursor map[string]uint64 `json:"cursor"`
 | 
				
			||||||
 | 
						Match  string            `json:"match"`
 | 
				
			||||||
 | 
						Count  int64             `json:"count"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -57,6 +57,15 @@ func (m *Machine) SaveMachine(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	entity := new(entity.Machine)
 | 
						entity := new(entity.Machine)
 | 
				
			||||||
	utils.Copy(entity, machineForm)
 | 
						utils.Copy(entity, machineForm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 密码解密,并使用解密后的赋值
 | 
				
			||||||
 | 
						originPwd, err := utils.DefaultRsaDecrypt(machineForm.Password, true)
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
 | 
				
			||||||
 | 
						entity.Password = originPwd
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 密码脱敏记录日志
 | 
				
			||||||
 | 
						machineForm.Password = "****"
 | 
				
			||||||
 | 
						rc.ReqParam = machineForm
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	entity.SetBaseInfo(rc.LoginAccount)
 | 
						entity.SetBaseInfo(rc.LoginAccount)
 | 
				
			||||||
	m.MachineApp.Save(entity)
 | 
						m.MachineApp.Save(entity)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -60,6 +60,22 @@ func (m *MachineFile) DeleteFile(rc *ctx.ReqCtx) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
/***      sftp相关操作      */
 | 
					/***      sftp相关操作      */
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (m *MachineFile) CreateFile(rc *ctx.ReqCtx) {
 | 
				
			||||||
 | 
						g := rc.GinCtx
 | 
				
			||||||
 | 
						fid := GetMachineFileId(g)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						form := new(form.MachineCreateFileForm)
 | 
				
			||||||
 | 
						ginx.BindJsonAndValid(g, form)
 | 
				
			||||||
 | 
						path := form.Path
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if form.Type == dir {
 | 
				
			||||||
 | 
							m.MachineFileApp.MkDir(fid, form.Path)
 | 
				
			||||||
 | 
						} else {
 | 
				
			||||||
 | 
							m.MachineFileApp.CreateFile(fid, form.Path)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						rc.ReqParam = fmt.Sprintf("path: %s, type: %s", path, form.Type)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (m *MachineFile) ReadFileContent(rc *ctx.ReqCtx) {
 | 
					func (m *MachineFile) ReadFileContent(rc *ctx.ReqCtx) {
 | 
				
			||||||
	g := rc.GinCtx
 | 
						g := rc.GinCtx
 | 
				
			||||||
	fid := GetMachineFileId(g)
 | 
						fid := GetMachineFileId(g)
 | 
				
			||||||
@@ -104,6 +120,7 @@ func (m *MachineFile) GetDirEntry(rc *ctx.ReqCtx) {
 | 
				
			|||||||
			Size: fi.Size(),
 | 
								Size: fi.Size(),
 | 
				
			||||||
			Path: readPath + fi.Name(),
 | 
								Path: readPath + fi.Name(),
 | 
				
			||||||
			Type: getFileType(fi.Mode()),
 | 
								Type: getFileType(fi.Mode()),
 | 
				
			||||||
 | 
								Mode: fi.Mode().String(),
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	rc.ResData = fisVO
 | 
						rc.ResData = fisVO
 | 
				
			||||||
@@ -155,7 +172,6 @@ func (m *MachineFile) UploadFile(rc *ctx.ReqCtx) {
 | 
				
			|||||||
func (m *MachineFile) RemoveFile(rc *ctx.ReqCtx) {
 | 
					func (m *MachineFile) RemoveFile(rc *ctx.ReqCtx) {
 | 
				
			||||||
	g := rc.GinCtx
 | 
						g := rc.GinCtx
 | 
				
			||||||
	fid := GetMachineFileId(g)
 | 
						fid := GetMachineFileId(g)
 | 
				
			||||||
	// mid := GetMachineId(g)
 | 
					 | 
				
			||||||
	path := g.Query("path")
 | 
						path := g.Query("path")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	m.MachineFileApp.RemoveFile(fid, path)
 | 
						m.MachineFileApp.RemoveFile(fid, path)
 | 
				
			||||||
@@ -167,8 +183,11 @@ func getFileType(fm fs.FileMode) string {
 | 
				
			|||||||
	if fm.IsDir() {
 | 
						if fm.IsDir() {
 | 
				
			||||||
		return dir
 | 
							return dir
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
						if fm.IsRegular() {
 | 
				
			||||||
		return file
 | 
							return file
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
						return dir
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func GetMachineFileId(g *gin.Context) uint64 {
 | 
					func GetMachineFileId(g *gin.Context) uint64 {
 | 
				
			||||||
	fileId, _ := strconv.Atoi(g.Param("fileId"))
 | 
						fileId, _ := strconv.Atoi(g.Param("fileId"))
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -38,6 +38,11 @@ func (m *Mongo) Save(rc *ctx.ReqCtx) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
	mongo := new(entity.Mongo)
 | 
						mongo := new(entity.Mongo)
 | 
				
			||||||
	utils.Copy(mongo, form)
 | 
						utils.Copy(mongo, form)
 | 
				
			||||||
 | 
						// 解密uri,并使用解密后的赋值
 | 
				
			||||||
 | 
						originUri, err := utils.DefaultRsaDecrypt(form.Uri, true)
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "解密uri错误: %s")
 | 
				
			||||||
 | 
						mongo.Uri = originUri
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	mongo.SetBaseInfo(rc.LoginAccount)
 | 
						mongo.SetBaseInfo(rc.LoginAccount)
 | 
				
			||||||
	m.MongoApp.Save(mongo)
 | 
						m.MongoApp.Save(mongo)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -43,7 +43,8 @@ func (p *Project) GetProjects(rc *ctx.ReqCtx) {
 | 
				
			|||||||
func (p *Project) SaveProject(rc *ctx.ReqCtx) {
 | 
					func (p *Project) SaveProject(rc *ctx.ReqCtx) {
 | 
				
			||||||
	project := &entity.Project{}
 | 
						project := &entity.Project{}
 | 
				
			||||||
	ginx.BindJsonAndValid(rc.GinCtx, project)
 | 
						ginx.BindJsonAndValid(rc.GinCtx, project)
 | 
				
			||||||
	rc.ReqParam = project
 | 
					
 | 
				
			||||||
 | 
						rc.ReqParam = fmt.Sprintf("projectId: %d, projectName: %s, remark: %s", project.Id, project.Name, project.Remark)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	project.SetBaseInfo(rc.LoginAccount)
 | 
						project.SetBaseInfo(rc.LoginAccount)
 | 
				
			||||||
	p.ProjectApp.SaveProject(project)
 | 
						p.ProjectApp.SaveProject(project)
 | 
				
			||||||
@@ -81,7 +82,8 @@ func (p *Project) GetProjectMembers(rc *ctx.ReqCtx) {
 | 
				
			|||||||
func (p *Project) SaveProjectMember(rc *ctx.ReqCtx) {
 | 
					func (p *Project) SaveProjectMember(rc *ctx.ReqCtx) {
 | 
				
			||||||
	projectMem := &entity.ProjectMember{}
 | 
						projectMem := &entity.ProjectMember{}
 | 
				
			||||||
	ginx.BindJsonAndValid(rc.GinCtx, projectMem)
 | 
						ginx.BindJsonAndValid(rc.GinCtx, projectMem)
 | 
				
			||||||
	rc.ReqParam = projectMem
 | 
					
 | 
				
			||||||
 | 
						rc.ReqParam = fmt.Sprintf("projectId: %d, username: %s", projectMem.ProjectId, projectMem.Username)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// 校验账号,并赋值username
 | 
						// 校验账号,并赋值username
 | 
				
			||||||
	account := &sys_entity.Account{}
 | 
						account := &sys_entity.Account{}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,6 +1,7 @@
 | 
				
			|||||||
package api
 | 
					package api
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
	"mayfly-go/internal/devops/api/form"
 | 
						"mayfly-go/internal/devops/api/form"
 | 
				
			||||||
	"mayfly-go/internal/devops/api/vo"
 | 
						"mayfly-go/internal/devops/api/vo"
 | 
				
			||||||
	"mayfly-go/internal/devops/application"
 | 
						"mayfly-go/internal/devops/application"
 | 
				
			||||||
@@ -11,7 +12,10 @@ import (
 | 
				
			|||||||
	"mayfly-go/pkg/utils"
 | 
						"mayfly-go/pkg/utils"
 | 
				
			||||||
	"strconv"
 | 
						"strconv"
 | 
				
			||||||
	"strings"
 | 
						"strings"
 | 
				
			||||||
 | 
						"sync"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/go-redis/redis/v8"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Redis struct {
 | 
					type Redis struct {
 | 
				
			||||||
@@ -32,10 +36,18 @@ func (r *Redis) Save(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	form := &form.Redis{}
 | 
						form := &form.Redis{}
 | 
				
			||||||
	ginx.BindJsonAndValid(rc.GinCtx, form)
 | 
						ginx.BindJsonAndValid(rc.GinCtx, form)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	rc.ReqParam = form
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	redis := new(entity.Redis)
 | 
						redis := new(entity.Redis)
 | 
				
			||||||
	utils.Copy(redis, form)
 | 
						utils.Copy(redis, form)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 密码解密,并使用解密后的赋值
 | 
				
			||||||
 | 
						originPwd, err := utils.DefaultRsaDecrypt(redis.Password, true)
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "解密密码错误: %s")
 | 
				
			||||||
 | 
						redis.Password = originPwd
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 密码脱敏记录日志
 | 
				
			||||||
 | 
						form.Password = "****"
 | 
				
			||||||
 | 
						rc.ReqParam = form
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	redis.SetBaseInfo(rc.LoginAccount)
 | 
						redis.SetBaseInfo(rc.LoginAccount)
 | 
				
			||||||
	r.RedisApp.Save(redis)
 | 
						r.RedisApp.Save(redis)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -45,7 +57,40 @@ func (r *Redis) DeleteRedis(rc *ctx.ReqCtx) {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (r *Redis) RedisInfo(rc *ctx.ReqCtx) {
 | 
					func (r *Redis) RedisInfo(rc *ctx.ReqCtx) {
 | 
				
			||||||
	res, _ := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(rc.GinCtx, "id"))).Cli.Info().Result()
 | 
						ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(rc.GinCtx, "id")))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var res string
 | 
				
			||||||
 | 
						var err error
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						ctx := context.Background()
 | 
				
			||||||
 | 
						if ri.Mode == "" || ri.Mode == entity.RedisModeStandalone {
 | 
				
			||||||
 | 
							res, err = ri.Cli.Info(ctx).Result()
 | 
				
			||||||
 | 
						} else if ri.Mode == entity.RedisModeCluster {
 | 
				
			||||||
 | 
							host := rc.GinCtx.Query("host")
 | 
				
			||||||
 | 
							biz.NotEmpty(host, "集群模式host信息不能为空")
 | 
				
			||||||
 | 
							clusterClient := ri.ClusterCli
 | 
				
			||||||
 | 
							var redisClient *redis.Client
 | 
				
			||||||
 | 
							// 遍历集群的master节点找到该redis client
 | 
				
			||||||
 | 
							clusterClient.ForEachMaster(ctx, func(ctx context.Context, client *redis.Client) error {
 | 
				
			||||||
 | 
								if host == client.Options().Addr {
 | 
				
			||||||
 | 
									redisClient = client
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
								return nil
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
							if redisClient == nil {
 | 
				
			||||||
 | 
								// 遍历集群的slave节点找到该redis client
 | 
				
			||||||
 | 
								clusterClient.ForEachSlave(ctx, func(ctx context.Context, client *redis.Client) error {
 | 
				
			||||||
 | 
									if host == client.Options().Addr {
 | 
				
			||||||
 | 
										redisClient = client
 | 
				
			||||||
 | 
									}
 | 
				
			||||||
 | 
									return nil
 | 
				
			||||||
 | 
								})
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							biz.NotNil(redisClient, "该实例不在该集群中")
 | 
				
			||||||
 | 
							res, err = redisClient.Info(ctx).Result()
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "获取redis info失败: %s")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	datas := strings.Split(res, "\r\n")
 | 
						datas := strings.Split(res, "\r\n")
 | 
				
			||||||
	i := 0
 | 
						i := 0
 | 
				
			||||||
@@ -81,22 +126,74 @@ func (r *Redis) RedisInfo(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	rc.ResData = parseMap
 | 
						rc.ResData = parseMap
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (r *Redis) ClusterInfo(rc *ctx.ReqCtx) {
 | 
				
			||||||
 | 
						g := rc.GinCtx
 | 
				
			||||||
 | 
						ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
				
			||||||
 | 
						biz.IsEquals(ri.Mode, entity.RedisModeCluster, "非集群模式")
 | 
				
			||||||
 | 
						info, _ := ri.ClusterCli.ClusterInfo(context.Background()).Result()
 | 
				
			||||||
 | 
						nodesStr, _ := ri.ClusterCli.ClusterNodes(context.Background()).Result()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						nodesRes := make([]map[string]string, 0)
 | 
				
			||||||
 | 
						nodes := strings.Split(nodesStr, "\n")
 | 
				
			||||||
 | 
						for _, node := range nodes {
 | 
				
			||||||
 | 
							if node == "" {
 | 
				
			||||||
 | 
								continue
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							nodeInfos := strings.Split(node, " ")
 | 
				
			||||||
 | 
							node := make(map[string]string)
 | 
				
			||||||
 | 
							node["nodeId"] = nodeInfos[0]
 | 
				
			||||||
 | 
							// ip:port1@port2:port1指redis服务器与客户端通信的端口,port2则是集群内部节点间通信的端口
 | 
				
			||||||
 | 
							node["ip"] = nodeInfos[1]
 | 
				
			||||||
 | 
							node["flags"] = nodeInfos[2]
 | 
				
			||||||
 | 
							// 如果节点是slave,并且已知master节点,则为master节点ID;否则为符号"-"
 | 
				
			||||||
 | 
							node["masterSlaveRelation"] = nodeInfos[3]
 | 
				
			||||||
 | 
							// 最近一次发送ping的时间,这个时间是一个unix毫秒时间戳,0代表没有发送过
 | 
				
			||||||
 | 
							node["pingSent"] = nodeInfos[4]
 | 
				
			||||||
 | 
							// 最近一次收到pong的时间,使用unix时间戳表示
 | 
				
			||||||
 | 
							node["pongRecv"] = nodeInfos[5]
 | 
				
			||||||
 | 
							// 节点的epoch值(如果该节点是从节点,则为其主节点的epoch值)。每当节点发生失败切换时,都会创建一个新的,独特的,递增的epoch。
 | 
				
			||||||
 | 
							// 如果多个节点竞争同一个哈希槽时,epoch值更高的节点会抢夺到
 | 
				
			||||||
 | 
							node["configEpoch"] = nodeInfos[6]
 | 
				
			||||||
 | 
							// node-to-node集群总线使用的链接的状态,我们使用这个链接与集群中其他节点进行通信.值可以是 connected 和 disconnected
 | 
				
			||||||
 | 
							node["linkState"] = nodeInfos[7]
 | 
				
			||||||
 | 
							// slave节点没有插槽信息
 | 
				
			||||||
 | 
							if len(nodeInfos) > 8 {
 | 
				
			||||||
 | 
								// slot:master节点第9位为哈希槽值或者一个哈希槽范围,代表当前节点可以提供服务的所有哈希槽值。如果只是一个值,那就是只有一个槽会被使用。
 | 
				
			||||||
 | 
								// 如果是一个范围,这个值表示为起始槽-结束槽,节点将处理包括起始槽和结束槽在内的所有哈希槽。
 | 
				
			||||||
 | 
								node["slot"] = nodeInfos[8]
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							nodesRes = append(nodesRes, node)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						rc.ResData = map[string]interface{}{
 | 
				
			||||||
 | 
							"clusterInfo":  info,
 | 
				
			||||||
 | 
							"clusterNodes": nodesRes,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// scan获取redis的key列表信息
 | 
					// scan获取redis的key列表信息
 | 
				
			||||||
func (r *Redis) Scan(rc *ctx.ReqCtx) {
 | 
					func (r *Redis) Scan(rc *ctx.ReqCtx) {
 | 
				
			||||||
	g := rc.GinCtx
 | 
						g := rc.GinCtx
 | 
				
			||||||
 | 
					 | 
				
			||||||
	ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
						ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
				
			||||||
	biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
						biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	keys, cursor := ri.Scan(uint64(ginx.PathParamInt(g, "cursor")), g.Query("match"), int64(ginx.PathParamInt(g, "count")))
 | 
						form := &form.RedisScanForm{}
 | 
				
			||||||
 | 
						ginx.BindJsonAndValid(rc.GinCtx, form)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						cmd := ri.GetCmdable()
 | 
				
			||||||
 | 
						ctx := context.Background()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						kis := make([]*vo.KeyInfo, 0)
 | 
				
			||||||
 | 
						var cursorRes map[string]uint64 = make(map[string]uint64)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if ri.Mode == "" || ri.Mode == entity.RedisModeStandalone {
 | 
				
			||||||
 | 
							redisAddr := ri.Cli.Options().Addr
 | 
				
			||||||
 | 
							keys, cursor := ri.Scan(form.Cursor[redisAddr], form.Match, form.Count)
 | 
				
			||||||
 | 
							cursorRes[redisAddr] = cursor
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		var keyInfoSplit []string
 | 
							var keyInfoSplit []string
 | 
				
			||||||
		if len(keys) > 0 {
 | 
							if len(keys) > 0 {
 | 
				
			||||||
		keyInfoLua := `
 | 
								keyInfosLua := `local result = {}
 | 
				
			||||||
			local result = {}
 | 
												-- KEYS[1]为第1个参数,lua数组下标从1开始
 | 
				
			||||||
			-- KEYS[1]为第1个参数,lua数组下标从1开始
 | 
					 | 
				
			||||||
			local ttl = redis.call('ttl', KEYS[1]);
 | 
					 | 
				
			||||||
			local keyType = redis.call('type', KEYS[1]);
 | 
					 | 
				
			||||||
							for i = 1, #KEYS do
 | 
												for i = 1, #KEYS do
 | 
				
			||||||
								local ttl = redis.call('ttl', KEYS[i]);
 | 
													local ttl = redis.call('ttl', KEYS[i]);
 | 
				
			||||||
								local keyType = redis.call('type', KEYS[i]);
 | 
													local keyType = redis.call('type', KEYS[i]);
 | 
				
			||||||
@@ -104,20 +201,50 @@ func (r *Redis) Scan(rc *ctx.ReqCtx) {
 | 
				
			|||||||
							end;
 | 
												end;
 | 
				
			||||||
							return table.concat(result, ".");`
 | 
												return table.concat(result, ".");`
 | 
				
			||||||
			// 通过lua获取 ttl,type.ttl2,type2格式,以便下面切割获取ttl和type。避免多次调用ttl和type函数
 | 
								// 通过lua获取 ttl,type.ttl2,type2格式,以便下面切割获取ttl和type。避免多次调用ttl和type函数
 | 
				
			||||||
		keyInfos, _ := ri.Cli.Eval(keyInfoLua, keys).Result()
 | 
								keyInfos, err := cmd.Eval(ctx, keyInfosLua, keys).Result()
 | 
				
			||||||
 | 
								biz.ErrIsNilAppendErr(err, "执行lua脚本获取key信息失败: %s")
 | 
				
			||||||
			keyInfoSplit = strings.Split(keyInfos.(string), ".")
 | 
								keyInfoSplit = strings.Split(keyInfos.(string), ".")
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	kis := make([]*vo.KeyInfo, 0)
 | 
					 | 
				
			||||||
		for i, k := range keys {
 | 
							for i, k := range keys {
 | 
				
			||||||
			ttlType := strings.Split(keyInfoSplit[i], ",")
 | 
								ttlType := strings.Split(keyInfoSplit[i], ",")
 | 
				
			||||||
			ttl, _ := strconv.Atoi(ttlType[0])
 | 
								ttl, _ := strconv.Atoi(ttlType[0])
 | 
				
			||||||
			ki := &vo.KeyInfo{Key: k, Type: ttlType[1], Ttl: int64(ttl)}
 | 
								ki := &vo.KeyInfo{Key: k, Type: ttlType[1], Ttl: int64(ttl)}
 | 
				
			||||||
			kis = append(kis, ki)
 | 
								kis = append(kis, ki)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
 | 
						} else if ri.Mode == entity.RedisModeCluster {
 | 
				
			||||||
 | 
							var keys []string
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	size, _ := ri.Cli.DBSize().Result()
 | 
							mu := &sync.Mutex{}
 | 
				
			||||||
	rc.ResData = &vo.Keys{Cursor: cursor, Keys: kis, DbSize: size}
 | 
							// 遍历所有master节点,并执行scan命令,合并keys
 | 
				
			||||||
 | 
							ri.ClusterCli.ForEachMaster(ctx, func(ctx context.Context, client *redis.Client) error {
 | 
				
			||||||
 | 
								redisAddr := client.Options().Addr
 | 
				
			||||||
 | 
								ks, cursor, _ := client.Scan(ctx, form.Cursor[redisAddr], form.Match, form.Count).Result()
 | 
				
			||||||
 | 
								// 遍历节点的内部回调函数使用异步调用,如不加锁会导致集合并发错误
 | 
				
			||||||
 | 
								mu.Lock()
 | 
				
			||||||
 | 
								cursorRes[redisAddr] = cursor
 | 
				
			||||||
 | 
								keys = append(keys, ks...)
 | 
				
			||||||
 | 
								mu.Unlock()
 | 
				
			||||||
 | 
								return nil
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							// 因为redis集群模式执行lua脚本key必须位于同一slot中,故单机获取的方式不适合
 | 
				
			||||||
 | 
							// 使用lua获取key的ttl以及类型,减少网络调用
 | 
				
			||||||
 | 
							keyInfoLua := `local ttl = redis.call('ttl', KEYS[1]);
 | 
				
			||||||
 | 
										   local keyType = redis.call('type', KEYS[1]);
 | 
				
			||||||
 | 
										   return string.format("%d,%s", ttl, keyType['ok'])`
 | 
				
			||||||
 | 
							for _, k := range keys {
 | 
				
			||||||
 | 
								keyInfo, err := cmd.Eval(ctx, keyInfoLua, []string{k}).Result()
 | 
				
			||||||
 | 
								biz.ErrIsNilAppendErr(err, "执行lua脚本获取key信息失败: %s")
 | 
				
			||||||
 | 
								ttlType := strings.Split(keyInfo.(string), ",")
 | 
				
			||||||
 | 
								ttl, _ := strconv.Atoi(ttlType[0])
 | 
				
			||||||
 | 
								ki := &vo.KeyInfo{Key: k, Type: ttlType[1], Ttl: int64(ttl)}
 | 
				
			||||||
 | 
								kis = append(kis, ki)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						size, _ := cmd.DBSize(context.TODO()).Result()
 | 
				
			||||||
 | 
						rc.ResData = &vo.Keys{Cursor: cursorRes, Keys: kis, DbSize: size}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (r *Redis) DeleteKey(rc *ctx.ReqCtx) {
 | 
					func (r *Redis) DeleteKey(rc *ctx.ReqCtx) {
 | 
				
			||||||
@@ -129,7 +256,7 @@ func (r *Redis) DeleteKey(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
						biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	rc.ReqParam = key
 | 
						rc.ReqParam = key
 | 
				
			||||||
	ri.Cli.Del(key)
 | 
						ri.GetCmdable().Del(context.Background(), key)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (r *Redis) checkKey(rc *ctx.ReqCtx) (*application.RedisInstance, string) {
 | 
					func (r *Redis) checkKey(rc *ctx.ReqCtx) (*application.RedisInstance, string) {
 | 
				
			||||||
@@ -145,14 +272,14 @@ func (r *Redis) checkKey(rc *ctx.ReqCtx) (*application.RedisInstance, string) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
func (r *Redis) GetStringValue(rc *ctx.ReqCtx) {
 | 
					func (r *Redis) GetStringValue(rc *ctx.ReqCtx) {
 | 
				
			||||||
	ri, key := r.checkKey(rc)
 | 
						ri, key := r.checkKey(rc)
 | 
				
			||||||
	str, err := ri.Cli.Get(key).Result()
 | 
						str, err := ri.GetCmdable().Get(context.TODO(), key).Result()
 | 
				
			||||||
	biz.ErrIsNilAppendErr(err, "获取字符串值失败: %s")
 | 
						biz.ErrIsNilAppendErr(err, "获取字符串值失败: %s")
 | 
				
			||||||
	rc.ResData = str
 | 
						rc.ResData = str
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (r *Redis) GetHashValue(rc *ctx.ReqCtx) {
 | 
					func (r *Redis) GetHashValue(rc *ctx.ReqCtx) {
 | 
				
			||||||
	ri, key := r.checkKey(rc)
 | 
						ri, key := r.checkKey(rc)
 | 
				
			||||||
	res, err := ri.Cli.HGetAll(key).Result()
 | 
						res, err := ri.GetCmdable().HGetAll(context.TODO(), key).Result()
 | 
				
			||||||
	biz.ErrIsNilAppendErr(err, "获取hash值失败: %s")
 | 
						biz.ErrIsNilAppendErr(err, "获取hash值失败: %s")
 | 
				
			||||||
	rc.ResData = res
 | 
						rc.ResData = res
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -165,7 +292,7 @@ func (r *Redis) SetStringValue(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
						ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
				
			||||||
	biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
						biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	str, err := ri.Cli.Set(keyValue.Key, keyValue.Value, time.Second*time.Duration(keyValue.Timed)).Result()
 | 
						str, err := ri.GetCmdable().Set(context.TODO(), keyValue.Key, keyValue.Value, time.Second*time.Duration(keyValue.Timed)).Result()
 | 
				
			||||||
	biz.ErrIsNilAppendErr(err, "保存字符串值失败: %s")
 | 
						biz.ErrIsNilAppendErr(err, "保存字符串值失败: %s")
 | 
				
			||||||
	rc.ResData = str
 | 
						rc.ResData = str
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -178,21 +305,22 @@ func (r *Redis) SetHashValue(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
						ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
				
			||||||
	biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
						biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						cmd := ri.GetCmdable()
 | 
				
			||||||
	key := hashValue.Key
 | 
						key := hashValue.Key
 | 
				
			||||||
	// 简单处理->先删除,后新增
 | 
						// 简单处理->先删除,后新增
 | 
				
			||||||
	ri.Cli.Del(key)
 | 
						cmd.Del(context.TODO(), key)
 | 
				
			||||||
	for _, v := range hashValue.Value {
 | 
						for _, v := range hashValue.Value {
 | 
				
			||||||
		res := ri.Cli.HSet(key, v["key"].(string), v["value"])
 | 
							res := cmd.HSet(context.TODO(), key, v["key"].(string), v["value"])
 | 
				
			||||||
		biz.ErrIsNilAppendErr(res.Err(), "保存hash值失败: %s")
 | 
							biz.ErrIsNilAppendErr(res.Err(), "保存hash值失败: %s")
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	if hashValue.Timed != -1 {
 | 
						if hashValue.Timed != -1 {
 | 
				
			||||||
		ri.Cli.Expire(key, time.Second*time.Duration(hashValue.Timed))
 | 
							cmd.Expire(context.TODO(), key, time.Second*time.Duration(hashValue.Timed))
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (r *Redis) GetSetValue(rc *ctx.ReqCtx) {
 | 
					func (r *Redis) GetSetValue(rc *ctx.ReqCtx) {
 | 
				
			||||||
	ri, key := r.checkKey(rc)
 | 
						ri, key := r.checkKey(rc)
 | 
				
			||||||
	res, err := ri.Cli.SMembers(key).Result()
 | 
						res, err := ri.GetCmdable().SMembers(context.TODO(), key).Result()
 | 
				
			||||||
	biz.ErrIsNilAppendErr(err, "获取set值失败: %s")
 | 
						biz.ErrIsNilAppendErr(err, "获取set值失败: %s")
 | 
				
			||||||
	rc.ResData = res
 | 
						rc.ResData = res
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -204,13 +332,14 @@ func (r *Redis) SetSetValue(rc *ctx.ReqCtx) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
	ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
						ri := r.RedisApp.GetRedisInstance(uint64(ginx.PathParamInt(g, "id")))
 | 
				
			||||||
	biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
						biz.ErrIsNilAppendErr(r.ProjectApp.CanAccess(rc.LoginAccount.Id, ri.ProjectId), "%s")
 | 
				
			||||||
 | 
						cmd := ri.GetCmdable()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	key := keyvalue.Key
 | 
						key := keyvalue.Key
 | 
				
			||||||
	// 简单处理->先删除,后新增
 | 
						// 简单处理->先删除,后新增
 | 
				
			||||||
	ri.Cli.Del(key)
 | 
						cmd.Del(context.TODO(), key)
 | 
				
			||||||
	ri.Cli.SAdd(key, keyvalue.Value...)
 | 
						cmd.SAdd(context.TODO(), key, keyvalue.Value...)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	if keyvalue.Timed != -1 {
 | 
						if keyvalue.Timed != -1 {
 | 
				
			||||||
		ri.Cli.Expire(key, time.Second*time.Duration(keyvalue.Timed))
 | 
							cmd.Expire(context.TODO(), key, time.Second*time.Duration(keyvalue.Timed))
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -9,6 +9,7 @@ type SelectDataDbVO struct {
 | 
				
			|||||||
	Host       *string    `json:"host"`
 | 
						Host       *string    `json:"host"`
 | 
				
			||||||
	Port       *int       `json:"port"`
 | 
						Port       *int       `json:"port"`
 | 
				
			||||||
	Type       *string    `json:"type"`
 | 
						Type       *string    `json:"type"`
 | 
				
			||||||
 | 
						Params     *string    `json:"params"`
 | 
				
			||||||
	Database   *string    `json:"database"`
 | 
						Database   *string    `json:"database"`
 | 
				
			||||||
	Username   *string    `json:"username"`
 | 
						Username   *string    `json:"username"`
 | 
				
			||||||
	ProjectId  *int64     `json:"projectId"`
 | 
						ProjectId  *int64     `json:"projectId"`
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -9,6 +9,8 @@ type Redis struct {
 | 
				
			|||||||
	Db         int        `json:"db"`
 | 
						Db         int        `json:"db"`
 | 
				
			||||||
	ProjectId  *int64     `json:"projectId"`
 | 
						ProjectId  *int64     `json:"projectId"`
 | 
				
			||||||
	Project    *string    `json:"project"`
 | 
						Project    *string    `json:"project"`
 | 
				
			||||||
 | 
						Mode       *string    `json:"mode"`
 | 
				
			||||||
 | 
						Remark     *string    `json:"remark"`
 | 
				
			||||||
	Env        *string    `json:"env"`
 | 
						Env        *string    `json:"env"`
 | 
				
			||||||
	EnvId      *int64     `json:"envId"`
 | 
						EnvId      *int64     `json:"envId"`
 | 
				
			||||||
	CreateTime *time.Time `json:"createTime"`
 | 
						CreateTime *time.Time `json:"createTime"`
 | 
				
			||||||
@@ -17,7 +19,7 @@ type Redis struct {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Keys struct {
 | 
					type Keys struct {
 | 
				
			||||||
	Cursor uint64     `json:"cursor"`
 | 
						Cursor map[string]uint64 `json:"cursor"`
 | 
				
			||||||
	Keys   []*KeyInfo        `json:"keys"`
 | 
						Keys   []*KeyInfo        `json:"keys"`
 | 
				
			||||||
	DbSize int64             `json:"dbSize"`
 | 
						DbSize int64             `json:"dbSize"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -56,6 +56,7 @@ type MachineFileInfo struct {
 | 
				
			|||||||
	Path string `json:"path"`
 | 
						Path string `json:"path"`
 | 
				
			||||||
	Size int64  `json:"size"`
 | 
						Size int64  `json:"size"`
 | 
				
			||||||
	Type string `json:"type"`
 | 
						Type string `json:"type"`
 | 
				
			||||||
 | 
						Mode string `json:"mode"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type RoleVO struct {
 | 
					type RoleVO struct {
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -17,6 +17,8 @@ import (
 | 
				
			|||||||
	"strings"
 | 
						"strings"
 | 
				
			||||||
	"sync"
 | 
						"sync"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						_ "github.com/lib/pq"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Db interface {
 | 
					type Db interface {
 | 
				
			||||||
@@ -223,14 +225,11 @@ func (d *DbInstance) SelectData(execSql string) ([]string, []map[string]interfac
 | 
				
			|||||||
	execSql = strings.Trim(execSql, " ")
 | 
						execSql = strings.Trim(execSql, " ")
 | 
				
			||||||
	isSelect := strings.HasPrefix(execSql, "SELECT") || strings.HasPrefix(execSql, "select")
 | 
						isSelect := strings.HasPrefix(execSql, "SELECT") || strings.HasPrefix(execSql, "select")
 | 
				
			||||||
	isShow := strings.HasPrefix(execSql, "show")
 | 
						isShow := strings.HasPrefix(execSql, "show")
 | 
				
			||||||
 | 
						isExplain := strings.HasPrefix(execSql, "explain")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	if !isSelect && !isShow {
 | 
						if !isSelect && !isShow && !isExplain {
 | 
				
			||||||
		return nil, nil, errors.New("该sql非查询语句")
 | 
							return nil, nil, errors.New("该sql非查询语句")
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	// 没加limit,则默认限制50条
 | 
					 | 
				
			||||||
	if isSelect && !strings.Contains(execSql, "limit") && !strings.Contains(execSql, "LIMIT") {
 | 
					 | 
				
			||||||
		execSql = execSql + " LIMIT 50"
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	rows, err := d.db.Query(execSql)
 | 
						rows, err := d.db.Query(execSql)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
@@ -272,14 +271,13 @@ func (d *DbInstance) SelectData(execSql string) ([]string, []map[string]interfac
 | 
				
			|||||||
			colName := colType.Name()
 | 
								colName := colType.Name()
 | 
				
			||||||
			// 字段类型名
 | 
								// 字段类型名
 | 
				
			||||||
			colScanType := colType.ScanType().Name()
 | 
								colScanType := colType.ScanType().Name()
 | 
				
			||||||
 | 
					 | 
				
			||||||
			// 如果是密码字段,则脱敏显示
 | 
					 | 
				
			||||||
			if colName == "password" {
 | 
					 | 
				
			||||||
				v = []byte("******")
 | 
					 | 
				
			||||||
			}
 | 
					 | 
				
			||||||
			if isFirst {
 | 
								if isFirst {
 | 
				
			||||||
				colNames = append(colNames, colName)
 | 
									colNames = append(colNames, colName)
 | 
				
			||||||
			}
 | 
								}
 | 
				
			||||||
 | 
								if v == nil {
 | 
				
			||||||
 | 
									rowData[colName] = nil
 | 
				
			||||||
 | 
									continue
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
			// 这里把[]byte数据转成string
 | 
								// 这里把[]byte数据转成string
 | 
				
			||||||
			stringV := string(v)
 | 
								stringV := string(v)
 | 
				
			||||||
			if stringV == "" {
 | 
								if stringV == "" {
 | 
				
			||||||
@@ -335,8 +333,21 @@ func (d *DbInstance) Close() {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
// 获取dataSourceName
 | 
					// 获取dataSourceName
 | 
				
			||||||
func getDsn(d *entity.Db) string {
 | 
					func getDsn(d *entity.Db) string {
 | 
				
			||||||
 | 
						var dsn string
 | 
				
			||||||
	if d.Type == "mysql" {
 | 
						if d.Type == "mysql" {
 | 
				
			||||||
		return fmt.Sprintf("%s:%s@%s(%s:%d)/%s?timeout=8s", d.Username, d.Password, d.Network, d.Host, d.Port, d.Database)
 | 
							dsn = fmt.Sprintf("%s:%s@%s(%s:%d)/%s?timeout=8s", d.Username, d.Password, d.Network, d.Host, d.Port, d.Database)
 | 
				
			||||||
 | 
							if d.Params != "" {
 | 
				
			||||||
 | 
								dsn = fmt.Sprintf("%s&%s", dsn, d.Params)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							return dsn
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if d.Type == "postgres" {
 | 
				
			||||||
 | 
							dsn = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", d.Host, d.Port, d.Username, d.Password, d.Database)
 | 
				
			||||||
 | 
							if d.Params != "" {
 | 
				
			||||||
 | 
								dsn = fmt.Sprintf("%s %s", dsn, strings.Join(strings.Split(d.Params, "&"), " "))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							return dsn
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	return ""
 | 
						return ""
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -352,37 +363,85 @@ const (
 | 
				
			|||||||
	// mysql 表信息元数据
 | 
						// mysql 表信息元数据
 | 
				
			||||||
	MYSQL_TABLE_MA = `SELECT table_name tableName, engine, table_comment tableComment, 
 | 
						MYSQL_TABLE_MA = `SELECT table_name tableName, engine, table_comment tableComment, 
 | 
				
			||||||
	create_time createTime from information_schema.tables
 | 
						create_time createTime from information_schema.tables
 | 
				
			||||||
	WHERE table_schema = (SELECT database())`
 | 
						WHERE table_schema = (SELECT database()) LIMIT 2000`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// mysql 表信息
 | 
						// mysql 表信息
 | 
				
			||||||
	MYSQL_TABLE_INFO = `SELECT table_name tableName, table_comment tableComment, table_rows tableRows,
 | 
						MYSQL_TABLE_INFO = `SELECT table_name tableName, table_comment tableComment, table_rows tableRows,
 | 
				
			||||||
	data_length dataLength, index_length indexLength, create_time createTime 
 | 
						data_length dataLength, index_length indexLength, create_time createTime 
 | 
				
			||||||
	FROM information_schema.tables 
 | 
						FROM information_schema.tables 
 | 
				
			||||||
    WHERE table_schema = (SELECT database())`
 | 
					    WHERE table_schema = (SELECT database()) LIMIT 2000`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// mysql 索引信息
 | 
						// mysql 索引信息
 | 
				
			||||||
	MYSQL_INDEX_INFO = `SELECT index_name indexName, column_name columnName, index_type indexType,
 | 
						MYSQL_INDEX_INFO = `SELECT index_name indexName, column_name columnName, index_type indexType,
 | 
				
			||||||
	SEQ_IN_INDEX seqInIndex, INDEX_COMMENT indexComment
 | 
						SEQ_IN_INDEX seqInIndex, INDEX_COMMENT indexComment
 | 
				
			||||||
	FROM information_schema.STATISTICS 
 | 
						FROM information_schema.STATISTICS 
 | 
				
			||||||
    WHERE table_schema = (SELECT database()) AND table_name = '%s'`
 | 
					    WHERE table_schema = (SELECT database()) AND table_name = '%s' LIMIT 500`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// 默认每次查询列元信息数量
 | 
						// 默认每次查询列元信息数量
 | 
				
			||||||
	DEFAULT_COLUMN_SIZE = 2000
 | 
						DEFAULT_COLUMN_SIZE = 2000
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// mysql 列信息元数据
 | 
						// mysql 列信息元数据
 | 
				
			||||||
	MYSQL_COLOUMN_MA = `SELECT table_name tableName, column_name columnName, column_type columnType,
 | 
						MYSQL_COLUMN_MA = `SELECT table_name tableName, column_name columnName, column_type columnType,
 | 
				
			||||||
	column_comment columnComment, column_key columnKey, extra, is_nullable nullable from information_schema.columns
 | 
						column_comment columnComment, column_key columnKey, extra, is_nullable nullable from information_schema.columns
 | 
				
			||||||
	WHERE table_name in (%s) AND table_schema = (SELECT database()) ORDER BY tableName, ordinal_position limit %d, %d`
 | 
						WHERE table_name in (%s) AND table_schema = (SELECT database()) ORDER BY tableName, ordinal_position LIMIT %d, %d`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// mysql 列信息元数据总数
 | 
						// mysql 列信息元数据总数
 | 
				
			||||||
	MYSQL_COLOUMN_MA_COUNT = `SELECT COUNT(*) maNum from information_schema.columns
 | 
						MYSQL_COLOUMN_MA_COUNT = `SELECT COUNT(*) maNum from information_schema.columns
 | 
				
			||||||
	WHERE table_name in (%s) AND table_schema = (SELECT database())`
 | 
						WHERE table_name in (%s) AND table_schema = (SELECT database())`
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						// postgres 表信息元数据
 | 
				
			||||||
 | 
						PGSQL_TABLE_MA = `SELECT obj_description(c.oid) AS "tableComment", c.relname AS "tableName" FROM pg_class c 
 | 
				
			||||||
 | 
						JOIN pg_namespace n ON c.relnamespace = n.oid WHERE n.nspname = (select current_schema()) AND c.reltype > 0`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						PGSQL_TABLE_INFO = `SELECT obj_description(c.oid) AS "tableComment", c.relname AS "tableName" FROM pg_class c 
 | 
				
			||||||
 | 
						JOIN pg_namespace n ON c.relnamespace = n.oid WHERE n.nspname = (select current_schema()) AND c.reltype > 0`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						PGSQL_INDEX_INFO = `SELECT indexname AS "indexName", indexdef AS "indexComment"
 | 
				
			||||||
 | 
						FROM pg_indexes WHERE schemaname =  (select current_schema()) AND tablename = '%s'`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						PGSQL_COLUMN_MA = `SELECT
 | 
				
			||||||
 | 
							C.relname AS "tableName",
 | 
				
			||||||
 | 
							A.attname AS "columnName",
 | 
				
			||||||
 | 
							concat_ws ( '', t.typname, SUBSTRING ( format_type ( a.atttypid, a.atttypmod ) FROM '\(.*\)' ) ) AS "columnType",
 | 
				
			||||||
 | 
							d.description AS "columnComment" 
 | 
				
			||||||
 | 
						FROM
 | 
				
			||||||
 | 
							pg_attribute a LEFT JOIN pg_description d ON d.objoid = a.attrelid 
 | 
				
			||||||
 | 
							AND d.objsubid = A.attnum
 | 
				
			||||||
 | 
							LEFT JOIN pg_class c ON A.attrelid = c.oid
 | 
				
			||||||
 | 
							LEFT JOIN pg_namespace pn ON c.relnamespace = pn.oid
 | 
				
			||||||
 | 
							LEFT JOIN pg_type t ON a.atttypid = t.oid 
 | 
				
			||||||
 | 
						WHERE
 | 
				
			||||||
 | 
							A.attnum >= 0 
 | 
				
			||||||
 | 
							AND pn.nspname = (select current_schema())
 | 
				
			||||||
 | 
							AND C.relname in (%s)
 | 
				
			||||||
 | 
						ORDER BY
 | 
				
			||||||
 | 
							C.relname DESC,
 | 
				
			||||||
 | 
							A.attnum ASC
 | 
				
			||||||
 | 
						OFFSET %d LIMIT %d	
 | 
				
			||||||
 | 
						`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						PGSQL_COLUMN_MA_COUNT = `SELECT COUNT(*) "maNum"
 | 
				
			||||||
 | 
						FROM
 | 
				
			||||||
 | 
							pg_attribute a LEFT JOIN pg_description d ON d.objoid = a.attrelid 
 | 
				
			||||||
 | 
							AND d.objsubid = A.attnum
 | 
				
			||||||
 | 
							LEFT JOIN pg_class c ON A.attrelid = c.oid
 | 
				
			||||||
 | 
							LEFT JOIN pg_namespace pn ON c.relnamespace = pn.oid
 | 
				
			||||||
 | 
							LEFT JOIN pg_type t ON a.atttypid = t.oid 
 | 
				
			||||||
 | 
						WHERE
 | 
				
			||||||
 | 
							A.attnum >= 0 
 | 
				
			||||||
 | 
							AND pn.nspname = (select current_schema())
 | 
				
			||||||
 | 
							AND C.relname in (%s)
 | 
				
			||||||
 | 
						`
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (d *DbInstance) GetTableMetedatas() []map[string]interface{} {
 | 
					func (d *DbInstance) GetTableMetedatas() []map[string]interface{} {
 | 
				
			||||||
	var sql string
 | 
						var sql string
 | 
				
			||||||
	if d.Type == "mysql" {
 | 
						if d.Type == "mysql" {
 | 
				
			||||||
		sql = MYSQL_TABLE_MA
 | 
							sql = MYSQL_TABLE_MA
 | 
				
			||||||
 | 
						} else if d.Type == "postgres" {
 | 
				
			||||||
 | 
							sql = PGSQL_TABLE_MA
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	_, res, _ := d.SelectData(sql)
 | 
						_, res, _ := d.SelectData(sql)
 | 
				
			||||||
	return res
 | 
						return res
 | 
				
			||||||
@@ -401,7 +460,10 @@ func (d *DbInstance) GetColumnMetadatas(tableNames ...string) []map[string]inter
 | 
				
			|||||||
	var sqlTmp string
 | 
						var sqlTmp string
 | 
				
			||||||
	if d.Type == "mysql" {
 | 
						if d.Type == "mysql" {
 | 
				
			||||||
		countSqlTmp = MYSQL_COLOUMN_MA_COUNT
 | 
							countSqlTmp = MYSQL_COLOUMN_MA_COUNT
 | 
				
			||||||
		sqlTmp = MYSQL_COLOUMN_MA
 | 
							sqlTmp = MYSQL_COLUMN_MA
 | 
				
			||||||
 | 
						} else if d.Type == "postgres" {
 | 
				
			||||||
 | 
							countSqlTmp = PGSQL_COLUMN_MA_COUNT
 | 
				
			||||||
 | 
							sqlTmp = PGSQL_COLUMN_MA
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	countSql := fmt.Sprintf(countSqlTmp, tableName)
 | 
						countSql := fmt.Sprintf(countSqlTmp, tableName)
 | 
				
			||||||
@@ -433,6 +495,8 @@ func (d *DbInstance) GetTableInfos() []map[string]interface{} {
 | 
				
			|||||||
	var sql string
 | 
						var sql string
 | 
				
			||||||
	if d.Type == "mysql" {
 | 
						if d.Type == "mysql" {
 | 
				
			||||||
		sql = MYSQL_TABLE_INFO
 | 
							sql = MYSQL_TABLE_INFO
 | 
				
			||||||
 | 
						} else if d.Type == "postgres" {
 | 
				
			||||||
 | 
							sql = PGSQL_TABLE_INFO
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	_, res, _ := d.SelectData(sql)
 | 
						_, res, _ := d.SelectData(sql)
 | 
				
			||||||
	return res
 | 
						return res
 | 
				
			||||||
@@ -442,6 +506,8 @@ func (d *DbInstance) GetTableIndex(tableName string) []map[string]interface{} {
 | 
				
			|||||||
	var sql string
 | 
						var sql string
 | 
				
			||||||
	if d.Type == "mysql" {
 | 
						if d.Type == "mysql" {
 | 
				
			||||||
		sql = fmt.Sprintf(MYSQL_INDEX_INFO, tableName)
 | 
							sql = fmt.Sprintf(MYSQL_INDEX_INFO, tableName)
 | 
				
			||||||
 | 
						} else if d.Type == "postgres" {
 | 
				
			||||||
 | 
							sql = fmt.Sprintf(PGSQL_INDEX_INFO, tableName)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	_, res, _ := d.SelectData(sql)
 | 
						_, res, _ := d.SelectData(sql)
 | 
				
			||||||
	return res
 | 
						return res
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,6 +1,7 @@
 | 
				
			|||||||
package application
 | 
					package application
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
	"io"
 | 
						"io"
 | 
				
			||||||
	"io/fs"
 | 
						"io/fs"
 | 
				
			||||||
	"mayfly-go/internal/devops/domain/entity"
 | 
						"mayfly-go/internal/devops/domain/entity"
 | 
				
			||||||
@@ -30,6 +31,12 @@ type MachineFile interface {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
	/**  sftp 相关操作 **/
 | 
						/**  sftp 相关操作 **/
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 创建目录
 | 
				
			||||||
 | 
						MkDir(fid uint64, path string)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 创建文件
 | 
				
			||||||
 | 
						CreateFile(fid uint64, path string)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// 读取目录
 | 
						// 读取目录
 | 
				
			||||||
	ReadDir(fid uint64, path string) []fs.FileInfo
 | 
						ReadDir(fid uint64, path string) []fs.FileInfo
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -100,6 +107,25 @@ func (m *machineFileAppImpl) ReadDir(fid uint64, path string) []fs.FileInfo {
 | 
				
			|||||||
	return fis
 | 
						return fis
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (m *machineFileAppImpl) MkDir(fid uint64, path string) {
 | 
				
			||||||
 | 
						path, machineId := m.checkAndReturnPathMid(fid, path)
 | 
				
			||||||
 | 
						if !strings.HasSuffix(path, "/") {
 | 
				
			||||||
 | 
							path = path + "/"
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						sftpCli := m.getSftpCli(machineId)
 | 
				
			||||||
 | 
						err := sftpCli.Mkdir(path)
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "创建目录失败: %s")
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (m *machineFileAppImpl) CreateFile(fid uint64, path string) {
 | 
				
			||||||
 | 
						path, machineId := m.checkAndReturnPathMid(fid, path)
 | 
				
			||||||
 | 
						sftpCli := m.getSftpCli(machineId)
 | 
				
			||||||
 | 
						file, err := sftpCli.Create(path)
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "创建文件失败: %s")
 | 
				
			||||||
 | 
						defer file.Close()
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (m *machineFileAppImpl) ReadFile(fileId uint64, path string) *sftp.File {
 | 
					func (m *machineFileAppImpl) ReadFile(fileId uint64, path string) *sftp.File {
 | 
				
			||||||
	path, machineId := m.checkAndReturnPathMid(fileId, path)
 | 
						path, machineId := m.checkAndReturnPathMid(fileId, path)
 | 
				
			||||||
	sftpCli := m.getSftpCli(machineId)
 | 
						sftpCli := m.getSftpCli(machineId)
 | 
				
			||||||
@@ -148,6 +174,11 @@ func (m *machineFileAppImpl) RemoveFile(fileId uint64, path string) {
 | 
				
			|||||||
	fi, _ := file.Stat()
 | 
						fi, _ := file.Stat()
 | 
				
			||||||
	if fi.IsDir() {
 | 
						if fi.IsDir() {
 | 
				
			||||||
		err = sftpCli.RemoveDirectory(path)
 | 
							err = sftpCli.RemoveDirectory(path)
 | 
				
			||||||
 | 
							// 如果文件夹有内容会删除失败,则使用rm -rf命令删除
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								MachineApp.GetCli(machineId).Run(fmt.Sprintf("rm -rf %s", path))
 | 
				
			||||||
 | 
								err = nil
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
	} else {
 | 
						} else {
 | 
				
			||||||
		err = sftpCli.Remove(path)
 | 
							err = sftpCli.Remove(path)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,6 +1,7 @@
 | 
				
			|||||||
package application
 | 
					package application
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"mayfly-go/internal/devops/domain/entity"
 | 
						"mayfly-go/internal/devops/domain/entity"
 | 
				
			||||||
	"mayfly-go/internal/devops/domain/repository"
 | 
						"mayfly-go/internal/devops/domain/repository"
 | 
				
			||||||
@@ -9,9 +10,10 @@ import (
 | 
				
			|||||||
	"mayfly-go/pkg/cache"
 | 
						"mayfly-go/pkg/cache"
 | 
				
			||||||
	"mayfly-go/pkg/global"
 | 
						"mayfly-go/pkg/global"
 | 
				
			||||||
	"mayfly-go/pkg/model"
 | 
						"mayfly-go/pkg/model"
 | 
				
			||||||
 | 
						"strings"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/go-redis/redis"
 | 
						"github.com/go-redis/redis/v8"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Redis interface {
 | 
					type Redis interface {
 | 
				
			||||||
@@ -63,7 +65,10 @@ func (r *redisAppImpl) GetRedisBy(condition *entity.Redis, cols ...string) error
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (r *redisAppImpl) Save(re *entity.Redis) {
 | 
					func (r *redisAppImpl) Save(re *entity.Redis) {
 | 
				
			||||||
 | 
						// ’修改信息且密码不为空‘ or ‘新增’需要测试是否可连接
 | 
				
			||||||
 | 
						if (re.Id != 0 && re.Password != "") || re.Id == 0 {
 | 
				
			||||||
		TestRedisConnection(re)
 | 
							TestRedisConnection(re)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// 查找是否存在该库
 | 
						// 查找是否存在该库
 | 
				
			||||||
	oldRedis := &entity.Redis{Host: re.Host, Db: re.Db}
 | 
						oldRedis := &entity.Redis{Host: re.Host, Db: re.Db}
 | 
				
			||||||
@@ -102,24 +107,53 @@ func (r *redisAppImpl) GetRedisInstance(id uint64) *RedisInstance {
 | 
				
			|||||||
	// 缓存不存在,则回调获取redis信息
 | 
						// 缓存不存在,则回调获取redis信息
 | 
				
			||||||
	re := r.GetById(id)
 | 
						re := r.GetById(id)
 | 
				
			||||||
	biz.NotNil(re, "redis信息不存在")
 | 
						biz.NotNil(re, "redis信息不存在")
 | 
				
			||||||
	global.Log.Infof("连接redis: %s", re.Host)
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	rcli := redis.NewClient(&redis.Options{
 | 
						redisMode := re.Mode
 | 
				
			||||||
		Addr:     re.Host,
 | 
						ri := &RedisInstance{Id: id, ProjectId: re.ProjectId, Mode: redisMode}
 | 
				
			||||||
		Password: re.Password, // no password set
 | 
						if redisMode == "" || redisMode == entity.RedisModeStandalone {
 | 
				
			||||||
		DB:       re.Db,       // use default DB
 | 
							rcli := getRedisCient(re)
 | 
				
			||||||
	})
 | 
					 | 
				
			||||||
		// 测试连接
 | 
							// 测试连接
 | 
				
			||||||
	_, e := rcli.Ping().Result()
 | 
							_, e := rcli.Ping(context.Background()).Result()
 | 
				
			||||||
	biz.ErrIsNilAppendErr(e, "redis连接失败: %s")
 | 
							if e != nil {
 | 
				
			||||||
 | 
								rcli.Close()
 | 
				
			||||||
 | 
								panic(biz.NewBizErr(fmt.Sprintf("redis连接失败: %s", e.Error())))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							ri.Cli = rcli
 | 
				
			||||||
 | 
						} else if redisMode == entity.RedisModeCluster {
 | 
				
			||||||
 | 
							ccli := getRedisClusterClient(re)
 | 
				
			||||||
 | 
							// 测试连接
 | 
				
			||||||
 | 
							_, e := ccli.Ping(context.Background()).Result()
 | 
				
			||||||
 | 
							if e != nil {
 | 
				
			||||||
 | 
								ccli.Close()
 | 
				
			||||||
 | 
								panic(biz.NewBizErr(fmt.Sprintf("redis集群连接失败: %s", e.Error())))
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							ri.ClusterCli = ccli
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	ri := &RedisInstance{Id: id, ProjectId: re.ProjectId, Cli: rcli}
 | 
						global.Log.Infof("连接redis: %s", re.Host)
 | 
				
			||||||
	if needCache {
 | 
						if needCache {
 | 
				
			||||||
		redisCache.Put(re.Id, ri)
 | 
							redisCache.Put(re.Id, ri)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	return ri
 | 
						return ri
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func getRedisCient(re *entity.Redis) *redis.Client {
 | 
				
			||||||
 | 
						return redis.NewClient(&redis.Options{
 | 
				
			||||||
 | 
							Addr:        re.Host,
 | 
				
			||||||
 | 
							Password:    re.Password, // no password set
 | 
				
			||||||
 | 
							DB:          re.Db,       // use default DB
 | 
				
			||||||
 | 
							DialTimeout: 8 * time.Second,
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func getRedisClusterClient(re *entity.Redis) *redis.ClusterClient {
 | 
				
			||||||
 | 
						return redis.NewClusterClient(&redis.ClusterOptions{
 | 
				
			||||||
 | 
							Addrs:       strings.Split(re.Host, ","),
 | 
				
			||||||
 | 
							Password:    re.Password,
 | 
				
			||||||
 | 
							DialTimeout: 8 * time.Second,
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
//------------------------------------------------------------------------------
 | 
					//------------------------------------------------------------------------------
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// redis客户端连接缓存,30分钟内没有访问则会被关闭
 | 
					// redis客户端连接缓存,30分钟内没有访问则会被关闭
 | 
				
			||||||
@@ -127,35 +161,64 @@ var redisCache = cache.NewTimedCache(30*time.Minute, 5*time.Second).
 | 
				
			|||||||
	WithUpdateAccessTime(true).
 | 
						WithUpdateAccessTime(true).
 | 
				
			||||||
	OnEvicted(func(key interface{}, value interface{}) {
 | 
						OnEvicted(func(key interface{}, value interface{}) {
 | 
				
			||||||
		global.Log.Info(fmt.Sprintf("删除redis连接缓存 id = %d", key))
 | 
							global.Log.Info(fmt.Sprintf("删除redis连接缓存 id = %d", key))
 | 
				
			||||||
		value.(*RedisInstance).Cli.Close()
 | 
							value.(*RedisInstance).Close()
 | 
				
			||||||
	})
 | 
						})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// redis实例
 | 
					 | 
				
			||||||
type RedisInstance struct {
 | 
					 | 
				
			||||||
	Id        uint64
 | 
					 | 
				
			||||||
	ProjectId uint64
 | 
					 | 
				
			||||||
	Cli       *redis.Client
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// 移除redis连接缓存并关闭redis连接
 | 
					// 移除redis连接缓存并关闭redis连接
 | 
				
			||||||
func CloseRedis(id uint64) {
 | 
					func CloseRedis(id uint64) {
 | 
				
			||||||
	redisCache.Delete(id)
 | 
						redisCache.Delete(id)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func TestRedisConnection(re *entity.Redis) {
 | 
					func TestRedisConnection(re *entity.Redis) {
 | 
				
			||||||
	rcli := redis.NewClient(&redis.Options{
 | 
						var cmd redis.Cmdable
 | 
				
			||||||
		Addr:     re.Host,
 | 
						if re.Mode == "" || re.Mode == entity.RedisModeStandalone {
 | 
				
			||||||
		Password: re.Password, // no password set
 | 
							rcli := getRedisCient(re)
 | 
				
			||||||
		DB:       re.Db,       // use default DB
 | 
					 | 
				
			||||||
	})
 | 
					 | 
				
			||||||
		defer rcli.Close()
 | 
							defer rcli.Close()
 | 
				
			||||||
 | 
							cmd = rcli
 | 
				
			||||||
 | 
						} else if re.Mode == entity.RedisModeCluster {
 | 
				
			||||||
 | 
							ccli := getRedisClusterClient(re)
 | 
				
			||||||
 | 
							defer ccli.Close()
 | 
				
			||||||
 | 
							cmd = ccli
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// 测试连接
 | 
						// 测试连接
 | 
				
			||||||
	_, e := rcli.Ping().Result()
 | 
						_, e := cmd.Ping(context.Background()).Result()
 | 
				
			||||||
	biz.ErrIsNilAppendErr(e, "Redis连接失败: %s")
 | 
						biz.ErrIsNilAppendErr(e, "Redis连接失败: %s")
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// redis实例
 | 
				
			||||||
 | 
					type RedisInstance struct {
 | 
				
			||||||
 | 
						Id         uint64
 | 
				
			||||||
 | 
						ProjectId  uint64
 | 
				
			||||||
 | 
						Mode       string
 | 
				
			||||||
 | 
						Cli        *redis.Client
 | 
				
			||||||
 | 
						ClusterCli *redis.ClusterClient
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 获取命令执行接口的具体实现
 | 
				
			||||||
 | 
					func (r *RedisInstance) GetCmdable() redis.Cmdable {
 | 
				
			||||||
 | 
						redisMode := r.Mode
 | 
				
			||||||
 | 
						if redisMode == "" || redisMode == entity.RedisModeStandalone {
 | 
				
			||||||
 | 
							return r.Cli
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if r.Mode == entity.RedisModeCluster {
 | 
				
			||||||
 | 
							return r.ClusterCli
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (r *RedisInstance) Scan(cursor uint64, match string, count int64) ([]string, uint64) {
 | 
					func (r *RedisInstance) Scan(cursor uint64, match string, count int64) ([]string, uint64) {
 | 
				
			||||||
	keys, newcursor, err := r.Cli.Scan(cursor, match, count).Result()
 | 
						keys, newcursor, err := r.GetCmdable().Scan(context.Background(), cursor, match, count).Result()
 | 
				
			||||||
	biz.ErrIsNilAppendErr(err, "scan失败: %s")
 | 
						biz.ErrIsNilAppendErr(err, "scan失败: %s")
 | 
				
			||||||
	return keys, newcursor
 | 
						return keys, newcursor
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (r *RedisInstance) Close() {
 | 
				
			||||||
 | 
						if r.Mode == entity.RedisModeStandalone {
 | 
				
			||||||
 | 
							r.Cli.Close()
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if r.Mode == entity.RedisModeCluster {
 | 
				
			||||||
 | 
							r.ClusterCli.Close()
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -15,6 +15,7 @@ type Db struct {
 | 
				
			|||||||
	Username  string `orm:"column(username)" json:"username"`
 | 
						Username  string `orm:"column(username)" json:"username"`
 | 
				
			||||||
	Password  string `orm:"column(password)" json:"-"`
 | 
						Password  string `orm:"column(password)" json:"-"`
 | 
				
			||||||
	Database  string `orm:"column(database)" json:"database"`
 | 
						Database  string `orm:"column(database)" json:"database"`
 | 
				
			||||||
 | 
						Params    string `json:"params"`
 | 
				
			||||||
	ProjectId uint64
 | 
						ProjectId uint64
 | 
				
			||||||
	Project   string
 | 
						Project   string
 | 
				
			||||||
	EnvId     uint64
 | 
						EnvId     uint64
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -8,10 +8,17 @@ type Redis struct {
 | 
				
			|||||||
	model.Model
 | 
						model.Model
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	Host      string `orm:"column(host)" json:"host"`
 | 
						Host      string `orm:"column(host)" json:"host"`
 | 
				
			||||||
 | 
						Mode      string `json:"mode"`
 | 
				
			||||||
	Password  string `orm:"column(password)" json:"-"`
 | 
						Password  string `orm:"column(password)" json:"-"`
 | 
				
			||||||
	Db        int    `orm:"column(database)" json:"db"`
 | 
						Db        int    `orm:"column(database)" json:"db"`
 | 
				
			||||||
 | 
						Remark    string
 | 
				
			||||||
	ProjectId uint64
 | 
						ProjectId uint64
 | 
				
			||||||
	Project   string
 | 
						Project   string
 | 
				
			||||||
	EnvId     uint64
 | 
						EnvId     uint64
 | 
				
			||||||
	Env       string
 | 
						Env       string
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						RedisModeStandalone = "standalone"
 | 
				
			||||||
 | 
						RedisModeCluster    = "cluster"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -24,14 +24,14 @@ func InitDbRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			rc.Handle(d.Dbs)
 | 
								rc.Handle(d.Dbs)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		saveDb := ctx.NewLogInfo("保存数据库信息")
 | 
							saveDb := ctx.NewLogInfo("保存数据库信息").WithSave(true)
 | 
				
			||||||
		db.POST("", func(c *gin.Context) {
 | 
							db.POST("", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
				WithLog(saveDb).
 | 
									WithLog(saveDb).
 | 
				
			||||||
				Handle(d.Save)
 | 
									Handle(d.Save)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		deleteDb := ctx.NewLogInfo("删除数据库信息")
 | 
							deleteDb := ctx.NewLogInfo("删除数据库信息").WithSave(true)
 | 
				
			||||||
		db.DELETE(":dbId", func(c *gin.Context) {
 | 
							db.DELETE(":dbId", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
				WithLog(deleteDb).
 | 
									WithLog(deleteDb).
 | 
				
			||||||
@@ -50,15 +50,24 @@ func InitDbRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(d.GetCreateTableDdl)
 | 
								ctx.NewReqCtxWithGin(c).Handle(d.GetCreateTableDdl)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// db.GET(":dbId/exec-sql", controllers.SelectData)
 | 
							execSqlLog := ctx.NewLogInfo("执行Sql语句")
 | 
				
			||||||
		db.POST(":dbId/exec-sql", func(g *gin.Context) {
 | 
							db.POST(":dbId/exec-sql", func(g *gin.Context) {
 | 
				
			||||||
			rc := ctx.NewReqCtxWithGin(g).WithLog(ctx.NewLogInfo("执行Sql语句"))
 | 
								rc := ctx.NewReqCtxWithGin(g).WithLog(execSqlLog)
 | 
				
			||||||
			rc.Handle(d.ExecSql)
 | 
								rc.Handle(d.ExecSql)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							execSqlFileLog := ctx.NewLogInfo("执行Sql文件").WithSave(true)
 | 
				
			||||||
		db.POST(":dbId/exec-sql-file", func(g *gin.Context) {
 | 
							db.POST(":dbId/exec-sql-file", func(g *gin.Context) {
 | 
				
			||||||
			rc := ctx.NewReqCtxWithGin(g).WithLog(ctx.NewLogInfo("执行Sql文件"))
 | 
								ctx.NewReqCtxWithGin(g).
 | 
				
			||||||
			rc.Handle(d.ExecSqlFile)
 | 
									WithLog(execSqlFileLog).
 | 
				
			||||||
 | 
									Handle(d.ExecSqlFile)
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							dumpLog := ctx.NewLogInfo("导出sql文件").WithSave(true)
 | 
				
			||||||
 | 
							db.GET(":dbId/dump", func(g *gin.Context) {
 | 
				
			||||||
 | 
								ctx.NewReqCtxWithGin(g).
 | 
				
			||||||
 | 
									WithLog(dumpLog).
 | 
				
			||||||
 | 
									Handle(d.DumpSql)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		db.GET(":dbId/t-metadata", func(c *gin.Context) {
 | 
							db.GET(":dbId/t-metadata", func(c *gin.Context) {
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -29,7 +29,7 @@ func InitMachineRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 终止进程
 | 
							// 终止进程
 | 
				
			||||||
		killProcessL := ctx.NewLogInfo("终止进程")
 | 
							killProcessL := ctx.NewLogInfo("终止进程").WithSave(true)
 | 
				
			||||||
		killProcessP := ctx.NewPermission("machine:killprocess")
 | 
							killProcessP := ctx.NewPermission("machine:killprocess")
 | 
				
			||||||
		machines.DELETE(":machineId/process", func(c *gin.Context) {
 | 
							machines.DELETE(":machineId/process", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
@@ -38,28 +38,28 @@ func InitMachineRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(m.KillProcess)
 | 
									Handle(m.KillProcess)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		saveMachine := ctx.NewLogInfo("保存机器信息")
 | 
							saveMachine := ctx.NewLogInfo("保存机器信息").WithSave(true)
 | 
				
			||||||
		machines.POST("", func(c *gin.Context) {
 | 
							machines.POST("", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
				WithLog(saveMachine).
 | 
									WithLog(saveMachine).
 | 
				
			||||||
				Handle(m.SaveMachine)
 | 
									Handle(m.SaveMachine)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		changeStatus := ctx.NewLogInfo("调整机器状态")
 | 
							changeStatus := ctx.NewLogInfo("调整机器状态").WithSave(true)
 | 
				
			||||||
		machines.PUT(":machineId/:status", func(c *gin.Context) {
 | 
							machines.PUT(":machineId/:status", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
				WithLog(changeStatus).
 | 
									WithLog(changeStatus).
 | 
				
			||||||
				Handle(m.ChangeStatus)
 | 
									Handle(m.ChangeStatus)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		delMachine := ctx.NewLogInfo("删除机器")
 | 
							delMachine := ctx.NewLogInfo("删除机器").WithSave(true)
 | 
				
			||||||
		machines.DELETE(":machineId", func(c *gin.Context) {
 | 
							machines.DELETE(":machineId", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
				WithLog(delMachine).
 | 
									WithLog(delMachine).
 | 
				
			||||||
				Handle(m.DeleteMachine)
 | 
									Handle(m.DeleteMachine)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		closeCli := ctx.NewLogInfo("关闭机器客户端")
 | 
							closeCli := ctx.NewLogInfo("关闭机器客户端").WithSave(true)
 | 
				
			||||||
		machines.DELETE(":machineId/close-cli", func(c *gin.Context) {
 | 
							machines.DELETE(":machineId/close-cli", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(closeCli).Handle(m.CloseCli)
 | 
								ctx.NewReqCtxWithGin(c).WithLog(closeCli).Handle(m.CloseCli)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -24,7 +24,7 @@ func InitMachineFileRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 新增修改机器文件
 | 
							// 新增修改机器文件
 | 
				
			||||||
		addFileConf := ctx.NewLogInfo("新增机器文件配置")
 | 
							addFileConf := ctx.NewLogInfo("新增机器文件配置").WithSave(true)
 | 
				
			||||||
		afcP := ctx.NewPermission("machine:file:add")
 | 
							afcP := ctx.NewPermission("machine:file:add")
 | 
				
			||||||
		machineFile.POST(":machineId/files", func(c *gin.Context) {
 | 
							machineFile.POST(":machineId/files", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(addFileConf).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(addFileConf).
 | 
				
			||||||
@@ -33,7 +33,7 @@ func InitMachineFileRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 删除机器文件
 | 
							// 删除机器文件
 | 
				
			||||||
		delFileConf := ctx.NewLogInfo("删除机器文件配置")
 | 
							delFileConf := ctx.NewLogInfo("删除机器文件配置").WithSave(true)
 | 
				
			||||||
		dfcP := ctx.NewPermission("machine:file:del")
 | 
							dfcP := ctx.NewPermission("machine:file:del")
 | 
				
			||||||
		machineFile.DELETE(":machineId/files/:fileId", func(c *gin.Context) {
 | 
							machineFile.DELETE(":machineId/files/:fileId", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(delFileConf).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(delFileConf).
 | 
				
			||||||
@@ -41,19 +41,19 @@ func InitMachineFileRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(mf.DeleteFile)
 | 
									Handle(mf.DeleteFile)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		getContent := ctx.NewLogInfo("读取机器文件内容")
 | 
							getContent := ctx.NewLogInfo("读取机器文件内容").WithSave(true)
 | 
				
			||||||
		machineFile.GET(":machineId/files/:fileId/read", func(c *gin.Context) {
 | 
							machineFile.GET(":machineId/files/:fileId/read", func(c *gin.Context) {
 | 
				
			||||||
			rc := ctx.NewReqCtxWithGin(c).WithLog(getContent)
 | 
								ctx.NewReqCtxWithGin(c).WithLog(getContent).
 | 
				
			||||||
			rc.Handle(mf.ReadFileContent)
 | 
									Handle(mf.ReadFileContent)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		getDir := ctx.NewLogInfo("读取机器目录")
 | 
							getDir := ctx.NewLogInfo("读取机器目录")
 | 
				
			||||||
		machineFile.GET(":machineId/files/:fileId/read-dir", func(c *gin.Context) {
 | 
							machineFile.GET(":machineId/files/:fileId/read-dir", func(c *gin.Context) {
 | 
				
			||||||
			rc := ctx.NewReqCtxWithGin(c).WithLog(getDir)
 | 
								ctx.NewReqCtxWithGin(c).WithLog(getDir).
 | 
				
			||||||
			rc.Handle(mf.GetDirEntry)
 | 
									Handle(mf.GetDirEntry)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		writeFile := ctx.NewLogInfo("写入or下载文件内容")
 | 
							writeFile := ctx.NewLogInfo("写入or下载文件内容").WithSave(true)
 | 
				
			||||||
		wfP := ctx.NewPermission("machine:file:write")
 | 
							wfP := ctx.NewPermission("machine:file:write")
 | 
				
			||||||
		machineFile.POST(":machineId/files/:fileId/write", func(c *gin.Context) {
 | 
							machineFile.POST(":machineId/files/:fileId/write", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(writeFile).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(writeFile).
 | 
				
			||||||
@@ -61,7 +61,14 @@ func InitMachineFileRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(mf.WriteFileContent)
 | 
									Handle(mf.WriteFileContent)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		uploadFile := ctx.NewLogInfo("文件上传")
 | 
							createFile := ctx.NewLogInfo("创建机器文件or目录").WithSave(true)
 | 
				
			||||||
 | 
							machineFile.POST(":machineId/files/:fileId/create-file", func(c *gin.Context) {
 | 
				
			||||||
 | 
								ctx.NewReqCtxWithGin(c).WithLog(createFile).
 | 
				
			||||||
 | 
									WithRequiredPermission(wfP).
 | 
				
			||||||
 | 
									Handle(mf.CreateFile)
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							uploadFile := ctx.NewLogInfo("文件上传").WithSave(true)
 | 
				
			||||||
		ufP := ctx.NewPermission("machine:file:upload")
 | 
							ufP := ctx.NewPermission("machine:file:upload")
 | 
				
			||||||
		machineFile.POST(":machineId/files/:fileId/upload", func(c *gin.Context) {
 | 
							machineFile.POST(":machineId/files/:fileId/upload", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(uploadFile).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(uploadFile).
 | 
				
			||||||
@@ -69,7 +76,7 @@ func InitMachineFileRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(mf.UploadFile)
 | 
									Handle(mf.UploadFile)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		removeFile := ctx.NewLogInfo("删除文件or文件夹")
 | 
							removeFile := ctx.NewLogInfo("删除文件or文件夹").WithSave(true)
 | 
				
			||||||
		rfP := ctx.NewPermission("machine:file:rm")
 | 
							rfP := ctx.NewPermission("machine:file:rm")
 | 
				
			||||||
		machineFile.DELETE(":machineId/files/:fileId/remove", func(c *gin.Context) {
 | 
							machineFile.DELETE(":machineId/files/:fileId/remove", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(removeFile).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(removeFile).
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -22,7 +22,7 @@ func InitMachineScriptRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(ms.MachineScripts)
 | 
								ctx.NewReqCtxWithGin(c).Handle(ms.MachineScripts)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		saveMachienScriptLog := ctx.NewLogInfo("保存脚本")
 | 
							saveMachienScriptLog := ctx.NewLogInfo("保存脚本").WithSave(true)
 | 
				
			||||||
		smsP := ctx.NewPermission("machine:script:save")
 | 
							smsP := ctx.NewPermission("machine:script:save")
 | 
				
			||||||
		// 保存脚本
 | 
							// 保存脚本
 | 
				
			||||||
		machines.POST(":machineId/scripts", func(c *gin.Context) {
 | 
							machines.POST(":machineId/scripts", func(c *gin.Context) {
 | 
				
			||||||
@@ -31,7 +31,7 @@ func InitMachineScriptRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(ms.SaveMachineScript)
 | 
									Handle(ms.SaveMachineScript)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		deleteLog := ctx.NewLogInfo("删除脚本")
 | 
							deleteLog := ctx.NewLogInfo("删除脚本").WithSave(true)
 | 
				
			||||||
		dP := ctx.NewPermission("machine:script:del")
 | 
							dP := ctx.NewPermission("machine:script:del")
 | 
				
			||||||
		// 保存脚本
 | 
							// 保存脚本
 | 
				
			||||||
		machines.DELETE(":machineId/scripts/:scriptId", func(c *gin.Context) {
 | 
							machines.DELETE(":machineId/scripts/:scriptId", func(c *gin.Context) {
 | 
				
			||||||
@@ -40,7 +40,7 @@ func InitMachineScriptRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(ms.DeleteMachineScript)
 | 
									Handle(ms.DeleteMachineScript)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		runLog := ctx.NewLogInfo("执行机器脚本")
 | 
							runLog := ctx.NewLogInfo("执行机器脚本").WithSave(true)
 | 
				
			||||||
		rP := ctx.NewPermission("machine:script:run")
 | 
							rP := ctx.NewPermission("machine:script:run")
 | 
				
			||||||
		// 运行脚本
 | 
							// 运行脚本
 | 
				
			||||||
		machines.GET(":machineId/scripts/:scriptId/run", func(c *gin.Context) {
 | 
							machines.GET(":machineId/scripts/:scriptId/run", func(c *gin.Context) {
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -25,7 +25,7 @@ func InitProjectRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(m.GetProjects)
 | 
								ctx.NewReqCtxWithGin(c).Handle(m.GetProjects)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		saveProjectLog := ctx.NewLogInfo("保存项目信息")
 | 
							saveProjectLog := ctx.NewLogInfo("保存项目信息").WithSave(true)
 | 
				
			||||||
		savePP := ctx.NewPermission("project:save")
 | 
							savePP := ctx.NewPermission("project:save")
 | 
				
			||||||
		// 保存项目下的环境信息
 | 
							// 保存项目下的环境信息
 | 
				
			||||||
		project.POST("", func(c *gin.Context) {
 | 
							project.POST("", func(c *gin.Context) {
 | 
				
			||||||
@@ -34,7 +34,7 @@ func InitProjectRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(m.SaveProject)
 | 
									Handle(m.SaveProject)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		delProjectLog := ctx.NewLogInfo("删除项目信息")
 | 
							delProjectLog := ctx.NewLogInfo("删除项目信息").WithSave(true)
 | 
				
			||||||
		delPP := ctx.NewPermission("project:del")
 | 
							delPP := ctx.NewPermission("project:del")
 | 
				
			||||||
		// 删除项目
 | 
							// 删除项目
 | 
				
			||||||
		project.DELETE("", func(c *gin.Context) {
 | 
							project.DELETE("", func(c *gin.Context) {
 | 
				
			||||||
@@ -48,7 +48,7 @@ func InitProjectRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(m.GetProjectEnvs)
 | 
								ctx.NewReqCtxWithGin(c).Handle(m.GetProjectEnvs)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		saveProjectEnvLog := ctx.NewLogInfo("新增项目环境信息")
 | 
							saveProjectEnvLog := ctx.NewLogInfo("新增项目环境信息").WithSave(true)
 | 
				
			||||||
		savePeP := ctx.NewPermission("project:env:add")
 | 
							savePeP := ctx.NewPermission("project:env:add")
 | 
				
			||||||
		// 保存项目下的环境信息
 | 
							// 保存项目下的环境信息
 | 
				
			||||||
		project.POST("/:projectId/envs", func(c *gin.Context) {
 | 
							project.POST("/:projectId/envs", func(c *gin.Context) {
 | 
				
			||||||
@@ -63,7 +63,7 @@ func InitProjectRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 保存项目成员
 | 
							// 保存项目成员
 | 
				
			||||||
		saveProjectMemLog := ctx.NewLogInfo("新增项目成员")
 | 
							saveProjectMemLog := ctx.NewLogInfo("新增项目成员").WithSave(true)
 | 
				
			||||||
		savePmP := ctx.NewPermission("project:member:add")
 | 
							savePmP := ctx.NewPermission("project:member:add")
 | 
				
			||||||
		project.POST("/:projectId/members", func(c *gin.Context) {
 | 
							project.POST("/:projectId/members", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(saveProjectMemLog).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(saveProjectMemLog).
 | 
				
			||||||
@@ -72,7 +72,7 @@ func InitProjectRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 删除项目成员
 | 
							// 删除项目成员
 | 
				
			||||||
		delProjectMemLog := ctx.NewLogInfo("删除项目成员")
 | 
							delProjectMemLog := ctx.NewLogInfo("删除项目成员").WithSave(true)
 | 
				
			||||||
		savePmdP := ctx.NewPermission("project:member:del")
 | 
							savePmdP := ctx.NewPermission("project:member:del")
 | 
				
			||||||
		project.DELETE("/:projectId/members/:accountId", func(c *gin.Context) {
 | 
							project.DELETE("/:projectId/members/:accountId", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(delProjectMemLog).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(delProjectMemLog).
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -21,12 +21,12 @@ func InitRedisRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(rs.RedisList)
 | 
								ctx.NewReqCtxWithGin(c).Handle(rs.RedisList)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		save := ctx.NewLogInfo("保存redis信息")
 | 
							save := ctx.NewLogInfo("保存redis信息").WithSave(true)
 | 
				
			||||||
		redis.POST("", func(c *gin.Context) {
 | 
							redis.POST("", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(save).Handle(rs.Save)
 | 
								ctx.NewReqCtxWithGin(c).WithLog(save).Handle(rs.Save)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		delRedis := ctx.NewLogInfo("删除redis信息")
 | 
							delRedis := ctx.NewLogInfo("删除redis信息").WithSave(true)
 | 
				
			||||||
		redis.DELETE(":id", func(c *gin.Context) {
 | 
							redis.DELETE(":id", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(delRedis).Handle(rs.DeleteRedis)
 | 
								ctx.NewReqCtxWithGin(c).WithLog(delRedis).Handle(rs.DeleteRedis)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
@@ -35,14 +35,17 @@ func InitRedisRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(rs.RedisInfo)
 | 
								ctx.NewReqCtxWithGin(c).Handle(rs.RedisInfo)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							redis.GET(":id/cluster-info", func(c *gin.Context) {
 | 
				
			||||||
 | 
								ctx.NewReqCtxWithGin(c).Handle(rs.ClusterInfo)
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 获取指定redis keys
 | 
							// 获取指定redis keys
 | 
				
			||||||
		redis.GET(":id/scan/:cursor/:count", func(c *gin.Context) {
 | 
							redis.POST(":id/scan", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).Handle(rs.Scan)
 | 
								ctx.NewReqCtxWithGin(c).Handle(rs.Scan)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 删除key
 | 
							// 删除key
 | 
				
			||||||
		deleteKeyL := ctx.NewLogInfo("redis删除key")
 | 
							deleteKeyL := ctx.NewLogInfo("redis删除key").WithSave(true)
 | 
				
			||||||
		// deleteKey := ctx.NewPermission("project:save")
 | 
					 | 
				
			||||||
		redis.DELETE(":id/key", func(c *gin.Context) {
 | 
							redis.DELETE(":id/key", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(deleteKeyL).Handle(rs.DeleteKey)
 | 
								ctx.NewReqCtxWithGin(c).WithLog(deleteKeyL).Handle(rs.DeleteKey)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -10,7 +10,9 @@ import (
 | 
				
			|||||||
	"mayfly-go/pkg/captcha"
 | 
						"mayfly-go/pkg/captcha"
 | 
				
			||||||
	"mayfly-go/pkg/ctx"
 | 
						"mayfly-go/pkg/ctx"
 | 
				
			||||||
	"mayfly-go/pkg/ginx"
 | 
						"mayfly-go/pkg/ginx"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/model"
 | 
				
			||||||
	"mayfly-go/pkg/utils"
 | 
						"mayfly-go/pkg/utils"
 | 
				
			||||||
 | 
						"regexp"
 | 
				
			||||||
	"strconv"
 | 
						"strconv"
 | 
				
			||||||
	"strings"
 | 
						"strings"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
@@ -29,15 +31,20 @@ type Account struct {
 | 
				
			|||||||
func (a *Account) Login(rc *ctx.ReqCtx) {
 | 
					func (a *Account) Login(rc *ctx.ReqCtx) {
 | 
				
			||||||
	loginForm := &form.LoginForm{}
 | 
						loginForm := &form.LoginForm{}
 | 
				
			||||||
	ginx.BindJsonAndValid(rc.GinCtx, loginForm)
 | 
						ginx.BindJsonAndValid(rc.GinCtx, loginForm)
 | 
				
			||||||
	rc.ReqParam = loginForm.Username
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// 校验验证码
 | 
						// 校验验证码
 | 
				
			||||||
	biz.IsTrue(captcha.Verify(loginForm.Cid, loginForm.Captcha), "验证码错误")
 | 
						biz.IsTrue(captcha.Verify(loginForm.Cid, loginForm.Captcha), "验证码错误")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	account := &entity.Account{Username: loginForm.Username, Password: utils.Md5(loginForm.Password)}
 | 
						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"), "用户名或密码错误")
 | 
						biz.ErrIsNil(a.AccountApp.GetAccount(account, "Id", "Username", "Status", "LastLoginTime", "LastLoginIp"), "用户名或密码错误")
 | 
				
			||||||
	biz.IsTrue(account.IsEnable(), "该账号不可用")
 | 
						biz.IsTrue(account.IsEnable(), "该账号不可用")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 校验密码强度是否符合
 | 
				
			||||||
 | 
						biz.IsTrueBy(CheckPasswordLever(originPwd), biz.NewBizErrCode(401, "您的密码安全等级较低,请修改后重新登录"))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	var resources vo.AccountResourceVOList
 | 
						var resources vo.AccountResourceVOList
 | 
				
			||||||
	// 获取账号菜单资源
 | 
						// 获取账号菜单资源
 | 
				
			||||||
	a.ResourceApp.GetAccountResources(account.Id, &resources)
 | 
						a.ResourceApp.GetAccountResources(account.Id, &resources)
 | 
				
			||||||
@@ -54,8 +61,13 @@ func (a *Account) Login(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	// 保存该账号的权限codes
 | 
						// 保存该账号的权限codes
 | 
				
			||||||
	ctx.SavePermissionCodes(account.Id, permissions)
 | 
						ctx.SavePermissionCodes(account.Id, permissions)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						clientIp := rc.GinCtx.ClientIP()
 | 
				
			||||||
	// 保存登录消息
 | 
						// 保存登录消息
 | 
				
			||||||
	go a.saveLogin(account, rc.GinCtx.ClientIP())
 | 
						go a.saveLogin(account, clientIp)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						rc.ReqParam = fmt.Sprintln("登录ip: ", clientIp)
 | 
				
			||||||
 | 
						// 赋值loginAccount 主要用于记录操作日志,因为操作日志保存请求上下文没有该信息不保存日志
 | 
				
			||||||
 | 
						rc.LoginAccount = &model.LoginAccount{Id: account.Id, Username: account.Username}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	rc.ResData = map[string]interface{}{
 | 
						rc.ResData = map[string]interface{}{
 | 
				
			||||||
		"token":         ctx.CreateToken(account.Id, account.Username),
 | 
							"token":         ctx.CreateToken(account.Id, account.Username),
 | 
				
			||||||
@@ -67,6 +79,48 @@ func (a *Account) Login(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *Account) ChangePassword(rc *ctx.ReqCtx) {
 | 
				
			||||||
 | 
						form := new(form.AccountChangePasswordForm)
 | 
				
			||||||
 | 
						ginx.BindJsonAndValid(rc.GinCtx, form)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						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"), "旧密码不正确")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						originNewPwd, err := utils.DefaultRsaDecrypt(form.NewPassword, true)
 | 
				
			||||||
 | 
						biz.ErrIsNilAppendErr(err, "解密新密码错误: %s")
 | 
				
			||||||
 | 
						biz.IsTrue(CheckPasswordLever(originNewPwd), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						updateAccount := new(entity.Account)
 | 
				
			||||||
 | 
						updateAccount.Id = account.Id
 | 
				
			||||||
 | 
						updateAccount.Password = utils.Md5(originNewPwd)
 | 
				
			||||||
 | 
						a.AccountApp.Update(updateAccount)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 赋值loginAccount 主要用于记录操作日志,因为操作日志保存请求上下文没有该信息不保存日志
 | 
				
			||||||
 | 
						rc.LoginAccount = &model.LoginAccount{Id: account.Id, Username: account.Username}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func CheckPasswordLever(ps string) bool {
 | 
				
			||||||
 | 
						if len(ps) < 8 {
 | 
				
			||||||
 | 
							return false
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						num := `[0-9]{1}`
 | 
				
			||||||
 | 
						a_z := `[a-zA-Z]{1}`
 | 
				
			||||||
 | 
						symbol := `[!@#~$%^&*()+|_.,]{1}`
 | 
				
			||||||
 | 
						if b, err := regexp.MatchString(num, ps); !b || err != nil {
 | 
				
			||||||
 | 
							return false
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if b, err := regexp.MatchString(a_z, ps); !b || err != nil {
 | 
				
			||||||
 | 
							return false
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if b, err := regexp.MatchString(symbol, ps); !b || err != nil {
 | 
				
			||||||
 | 
							return false
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						return true
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 保存更新账号登录信息
 | 
					// 保存更新账号登录信息
 | 
				
			||||||
func (a *Account) saveLogin(account *entity.Account, ip string) {
 | 
					func (a *Account) saveLogin(account *entity.Account, ip string) {
 | 
				
			||||||
	// 更新账号最后登录时间
 | 
						// 更新账号最后登录时间
 | 
				
			||||||
@@ -100,7 +154,7 @@ func (a *Account) saveLogin(account *entity.Account, ip string) {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 获取个人账号信息
 | 
					// 获取个人账号信息
 | 
				
			||||||
func (a Account) AccountInfo(rc *ctx.ReqCtx) {
 | 
					func (a *Account) AccountInfo(rc *ctx.ReqCtx) {
 | 
				
			||||||
	ap := new(vo.AccountPersonVO)
 | 
						ap := new(vo.AccountPersonVO)
 | 
				
			||||||
	// 角色信息
 | 
						// 角色信息
 | 
				
			||||||
	roles := new([]vo.AccountRoleVO)
 | 
						roles := new([]vo.AccountRoleVO)
 | 
				
			||||||
@@ -111,7 +165,7 @@ func (a Account) AccountInfo(rc *ctx.ReqCtx) {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 更新个人账号信息
 | 
					// 更新个人账号信息
 | 
				
			||||||
func (a Account) UpdateAccount(rc *ctx.ReqCtx) {
 | 
					func (a *Account) UpdateAccount(rc *ctx.ReqCtx) {
 | 
				
			||||||
	updateForm := &form.AccountUpdateForm{}
 | 
						updateForm := &form.AccountUpdateForm{}
 | 
				
			||||||
	ginx.BindJsonAndValid(rc.GinCtx, updateForm)
 | 
						ginx.BindJsonAndValid(rc.GinCtx, updateForm)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -121,13 +175,14 @@ func (a Account) UpdateAccount(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	updateAccount.Id = rc.LoginAccount.Id
 | 
						updateAccount.Id = rc.LoginAccount.Id
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	if updateAccount.Password != "" {
 | 
						if updateAccount.Password != "" {
 | 
				
			||||||
 | 
							biz.IsTrue(CheckPasswordLever(updateAccount.Password), "密码强度必须8位以上且包含字⺟⼤⼩写+数字+特殊符号")
 | 
				
			||||||
		updateAccount.Password = utils.Md5(updateAccount.Password)
 | 
							updateAccount.Password = utils.Md5(updateAccount.Password)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	a.AccountApp.Update(updateAccount)
 | 
						a.AccountApp.Update(updateAccount)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 获取账号接收的消息列表
 | 
					// 获取账号接收的消息列表
 | 
				
			||||||
func (a Account) GetMsgs(rc *ctx.ReqCtx) {
 | 
					func (a *Account) GetMsgs(rc *ctx.ReqCtx) {
 | 
				
			||||||
	condition := &entity.Msg{
 | 
						condition := &entity.Msg{
 | 
				
			||||||
		RecipientId: int64(rc.LoginAccount.Id),
 | 
							RecipientId: int64(rc.LoginAccount.Id),
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -7,3 +7,9 @@ type AccountCreateForm struct {
 | 
				
			|||||||
type AccountUpdateForm struct {
 | 
					type AccountUpdateForm struct {
 | 
				
			||||||
	Password *string `json:"password" binding:"min=6,max=16"`
 | 
						Password *string `json:"password" binding:"min=6,max=16"`
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type AccountChangePasswordForm struct {
 | 
				
			||||||
 | 
						Username    string `json:"username"`
 | 
				
			||||||
 | 
						OldPassword string `json:"oldPassword"`
 | 
				
			||||||
 | 
						NewPassword string `json:"newPassword"`
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -29,6 +29,7 @@ func (r *Role) SaveRole(rc *ctx.ReqCtx) {
 | 
				
			|||||||
	g := rc.GinCtx
 | 
						g := rc.GinCtx
 | 
				
			||||||
	form := &form.RoleForm{}
 | 
						form := &form.RoleForm{}
 | 
				
			||||||
	ginx.BindJsonAndValid(g, form)
 | 
						ginx.BindJsonAndValid(g, form)
 | 
				
			||||||
 | 
						rc.ReqParam = form
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	role := new(entity.Role)
 | 
						role := new(entity.Role)
 | 
				
			||||||
	utils.Copy(role, form)
 | 
						utils.Copy(role, form)
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										21
									
								
								server/internal/sys/api/syslog.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								server/internal/sys/api/syslog.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,21 @@
 | 
				
			|||||||
 | 
					package api
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/application"
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/domain/entity"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/ctx"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/ginx"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type Syslog struct {
 | 
				
			||||||
 | 
						SyslogApp application.Syslog
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (r *Syslog) Syslogs(rc *ctx.ReqCtx) {
 | 
				
			||||||
 | 
						g := rc.GinCtx
 | 
				
			||||||
 | 
						condition := &entity.Syslog{
 | 
				
			||||||
 | 
							Type:      int8(ginx.QueryInt(g, "type", 0)),
 | 
				
			||||||
 | 
							CreatorId: uint64(ginx.QueryInt(g, "creatorId", 0)),
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						rc.ResData = r.SyslogApp.GetPageList(condition, ginx.GetPageParam(g), new([]entity.Syslog), "create_time DESC")
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										79
									
								
								server/internal/sys/application/syslog_app.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										79
									
								
								server/internal/sys/application/syslog_app.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,79 @@
 | 
				
			|||||||
 | 
					package application
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"encoding/json"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/domain/entity"
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/domain/repository"
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/infrastructure/persistence"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/biz"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/ctx"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/model"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/utils"
 | 
				
			||||||
 | 
						"reflect"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type Syslog interface {
 | 
				
			||||||
 | 
						GetPageList(condition *entity.Syslog, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 从请求上下文的参数保存系统日志
 | 
				
			||||||
 | 
						SaveFromReq(req *ctx.ReqCtx)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type syslogAppImpl struct {
 | 
				
			||||||
 | 
						syslogRepo repository.Syslog
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 实现类单例
 | 
				
			||||||
 | 
					var SyslogApp Syslog = &syslogAppImpl{
 | 
				
			||||||
 | 
						syslogRepo: persistence.SyslogDao,
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (m *syslogAppImpl) GetPageList(condition *entity.Syslog, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult {
 | 
				
			||||||
 | 
						return m.syslogRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (m *syslogAppImpl) SaveFromReq(req *ctx.ReqCtx) {
 | 
				
			||||||
 | 
						lg := req.LoginAccount
 | 
				
			||||||
 | 
						if lg == nil {
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						syslog := new(entity.Syslog)
 | 
				
			||||||
 | 
						syslog.CreateTime = time.Now()
 | 
				
			||||||
 | 
						syslog.Creator = lg.Username
 | 
				
			||||||
 | 
						syslog.CreatorId = lg.Id
 | 
				
			||||||
 | 
						syslog.Description = req.LogInfo.Description
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if req.LogInfo.LogResp {
 | 
				
			||||||
 | 
							respB, _ := json.Marshal(req.ResData)
 | 
				
			||||||
 | 
							syslog.Resp = string(respB)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						reqParam := req.ReqParam
 | 
				
			||||||
 | 
						if !utils.IsBlank(reflect.ValueOf(reqParam)) {
 | 
				
			||||||
 | 
							// 如果是字符串类型,则不使用json序列化
 | 
				
			||||||
 | 
							if reqStr, ok := reqParam.(string); ok {
 | 
				
			||||||
 | 
								syslog.ReqParam = reqStr
 | 
				
			||||||
 | 
							} else {
 | 
				
			||||||
 | 
								reqB, _ := json.Marshal(reqParam)
 | 
				
			||||||
 | 
								syslog.ReqParam = string(reqB)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if err := req.Err; err != nil {
 | 
				
			||||||
 | 
							syslog.Type = entity.SyslogTypeError
 | 
				
			||||||
 | 
							var errMsg string
 | 
				
			||||||
 | 
							switch t := err.(type) {
 | 
				
			||||||
 | 
							case *biz.BizError:
 | 
				
			||||||
 | 
								errMsg = fmt.Sprintf("errCode: %d, errMsg: %s", t.Code(), t.Error())
 | 
				
			||||||
 | 
							case error:
 | 
				
			||||||
 | 
								errMsg = t.Error()
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							syslog.Resp = errMsg
 | 
				
			||||||
 | 
						} else {
 | 
				
			||||||
 | 
							syslog.Type = entity.SyslogTypeNorman
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						m.syslogRepo.Insert(syslog)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										25
									
								
								server/internal/sys/domain/entity/syslog.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								server/internal/sys/domain/entity/syslog.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,25 @@
 | 
				
			|||||||
 | 
					package entity
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import "time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 系统操作日志
 | 
				
			||||||
 | 
					type Syslog struct {
 | 
				
			||||||
 | 
						Id         uint64    `json:"id"`
 | 
				
			||||||
 | 
						CreateTime time.Time `json:"createTime"`
 | 
				
			||||||
 | 
						CreatorId  uint64    `json:"creatorId"`
 | 
				
			||||||
 | 
						Creator    string    `json:"creator"`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						Type        int8   `json:"type"`
 | 
				
			||||||
 | 
						Description string `json:"description"`
 | 
				
			||||||
 | 
						ReqParam    string `json:"reqParam"` // 请求参数
 | 
				
			||||||
 | 
						Resp        string `json:"resp"`     // 响应结构
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (a *Syslog) TableName() string {
 | 
				
			||||||
 | 
						return "t_sys_log"
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						SyslogTypeNorman int8 = 1 // 正常状态
 | 
				
			||||||
 | 
						SyslogTypeError  int8 = 2 // 错误状态
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
							
								
								
									
										12
									
								
								server/internal/sys/domain/repository/syslog.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								server/internal/sys/domain/repository/syslog.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,12 @@
 | 
				
			|||||||
 | 
					package repository
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/domain/entity"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/model"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type Syslog interface {
 | 
				
			||||||
 | 
						GetPageList(condition *entity.Syslog, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						Insert(log *entity.Syslog)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -0,0 +1,19 @@
 | 
				
			|||||||
 | 
					package persistence
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/domain/entity"
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/domain/repository"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/model"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type syslogRepo struct{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var SyslogDao repository.Syslog = &syslogRepo{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (m *syslogRepo) GetPageList(condition *entity.Syslog, pageParam *model.PageParam, toEntity interface{}, orderBy ...string) *model.PageResult {
 | 
				
			||||||
 | 
						return model.GetPage(pageParam, condition, toEntity, orderBy...)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (m *syslogRepo) Insert(syslog *entity.Syslog) {
 | 
				
			||||||
 | 
						model.Insert(syslog)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -18,9 +18,20 @@ func InitAccountRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
	}
 | 
						}
 | 
				
			||||||
	{
 | 
						{
 | 
				
			||||||
		// 用户登录
 | 
							// 用户登录
 | 
				
			||||||
 | 
							loginLog := ctx.NewLogInfo("用户登录").WithSave(true)
 | 
				
			||||||
		account.POST("login", func(g *gin.Context) {
 | 
							account.POST("login", func(g *gin.Context) {
 | 
				
			||||||
			rc := ctx.NewReqCtxWithGin(g).WithNeedToken(false).WithLog(ctx.NewLogInfo("用户登录"))
 | 
								ctx.NewReqCtxWithGin(g).
 | 
				
			||||||
			rc.Handle(a.Login)
 | 
									WithNeedToken(false).
 | 
				
			||||||
 | 
									WithLog(loginLog).
 | 
				
			||||||
 | 
									Handle(a.Login)
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							changePwdLog := ctx.NewLogInfo("用户修改密码").WithSave(true)
 | 
				
			||||||
 | 
							account.POST("change-pwd", func(g *gin.Context) {
 | 
				
			||||||
 | 
								ctx.NewReqCtxWithGin(g).
 | 
				
			||||||
 | 
									WithNeedToken(false).
 | 
				
			||||||
 | 
									WithLog(changePwdLog).
 | 
				
			||||||
 | 
									Handle(a.ChangePassword)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 获取个人账号信息
 | 
							// 获取个人账号信息
 | 
				
			||||||
@@ -44,7 +55,7 @@ func InitAccountRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(a.Accounts)
 | 
								ctx.NewReqCtxWithGin(c).Handle(a.Accounts)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		createAccount := ctx.NewLogInfo("创建账号")
 | 
							createAccount := ctx.NewLogInfo("创建账号").WithSave(true)
 | 
				
			||||||
		addAccountPermission := ctx.NewPermission("account:add")
 | 
							addAccountPermission := ctx.NewPermission("account:add")
 | 
				
			||||||
		account.POST("", func(c *gin.Context) {
 | 
							account.POST("", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
@@ -53,14 +64,14 @@ func InitAccountRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(a.CreateAccount)
 | 
									Handle(a.CreateAccount)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		changeStatus := ctx.NewLogInfo("修改账号状态")
 | 
							changeStatus := ctx.NewLogInfo("修改账号状态").WithSave(true)
 | 
				
			||||||
		account.PUT("change-status/:id/:status", func(c *gin.Context) {
 | 
							account.PUT("change-status/:id/:status", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
				WithLog(changeStatus).
 | 
									WithLog(changeStatus).
 | 
				
			||||||
				Handle(a.ChangeStatus)
 | 
									Handle(a.ChangeStatus)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		delAccount := ctx.NewLogInfo("删除账号")
 | 
							delAccount := ctx.NewLogInfo("删除账号").WithSave(true)
 | 
				
			||||||
		delAccountPermission := ctx.NewPermission("account:del")
 | 
							delAccountPermission := ctx.NewPermission("account:del")
 | 
				
			||||||
		account.DELETE(":id", func(c *gin.Context) {
 | 
							account.DELETE(":id", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
@@ -75,7 +86,7 @@ func InitAccountRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		// 保存用户角色
 | 
							// 保存用户角色
 | 
				
			||||||
		saveAccountRole := ctx.NewLogInfo("保存用户角色")
 | 
							saveAccountRole := ctx.NewLogInfo("保存用户角色").WithSave(true)
 | 
				
			||||||
		sarPermission := ctx.NewPermission("account:saveRoles")
 | 
							sarPermission := ctx.NewPermission("account:saveRoles")
 | 
				
			||||||
		account.POST("/roles", func(c *gin.Context) {
 | 
							account.POST("/roles", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(saveAccountRole).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(saveAccountRole).
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -12,10 +12,6 @@ func InitResourceRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
	r := &api.Resource{ResourceApp: application.ResourceApp}
 | 
						r := &api.Resource{ResourceApp: application.ResourceApp}
 | 
				
			||||||
	db := router.Group("sys/resources")
 | 
						db := router.Group("sys/resources")
 | 
				
			||||||
	{
 | 
						{
 | 
				
			||||||
		// db.GET("/account", func(c *gin.Context) {
 | 
					 | 
				
			||||||
		// 	ctx.NewReqCtxWithGin(c).Handle(r.ResourceTree)
 | 
					 | 
				
			||||||
		// })
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
		db.GET("", func(c *gin.Context) {
 | 
							db.GET("", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).Handle(r.GetAllResourceTree)
 | 
								ctx.NewReqCtxWithGin(c).Handle(r.GetAllResourceTree)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
@@ -24,7 +20,7 @@ func InitResourceRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(r.GetById)
 | 
								ctx.NewReqCtxWithGin(c).Handle(r.GetById)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		saveResource := ctx.NewLogInfo("保存资源")
 | 
							saveResource := ctx.NewLogInfo("保存资源").WithSave(true)
 | 
				
			||||||
		srPermission := ctx.NewPermission("resource:add")
 | 
							srPermission := ctx.NewPermission("resource:add")
 | 
				
			||||||
		db.POST("", func(c *gin.Context) {
 | 
							db.POST("", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
@@ -33,7 +29,7 @@ func InitResourceRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(r.SaveResource)
 | 
									Handle(r.SaveResource)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		changeStatus := ctx.NewLogInfo("修改资源状态")
 | 
							changeStatus := ctx.NewLogInfo("修改资源状态").WithSave(true)
 | 
				
			||||||
		csPermission := ctx.NewPermission("resource:changeStatus")
 | 
							csPermission := ctx.NewPermission("resource:changeStatus")
 | 
				
			||||||
		db.PUT(":id/:status", func(c *gin.Context) {
 | 
							db.PUT(":id/:status", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
@@ -42,7 +38,7 @@ func InitResourceRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(r.ChangeStatus)
 | 
									Handle(r.ChangeStatus)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		delResource := ctx.NewLogInfo("删除资源")
 | 
							delResource := ctx.NewLogInfo("删除资源").WithSave(true)
 | 
				
			||||||
		dePermission := ctx.NewPermission("resource:delete")
 | 
							dePermission := ctx.NewPermission("resource:delete")
 | 
				
			||||||
		db.DELETE(":id", func(c *gin.Context) {
 | 
							db.DELETE(":id", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).
 | 
								ctx.NewReqCtxWithGin(c).
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -20,7 +20,7 @@ func InitRoleRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(r.Roles)
 | 
								ctx.NewReqCtxWithGin(c).Handle(r.Roles)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		saveRole := ctx.NewLogInfo("保存角色")
 | 
							saveRole := ctx.NewLogInfo("保存角色").WithSave(true)
 | 
				
			||||||
		sPermission := ctx.NewPermission("role:add")
 | 
							sPermission := ctx.NewPermission("role:add")
 | 
				
			||||||
		db.POST("", func(c *gin.Context) {
 | 
							db.POST("", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(saveRole).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(saveRole).
 | 
				
			||||||
@@ -28,7 +28,7 @@ func InitRoleRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
				Handle(r.SaveRole)
 | 
									Handle(r.SaveRole)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		delRole := ctx.NewLogInfo("删除角色")
 | 
							delRole := ctx.NewLogInfo("删除角色").WithSave(true)
 | 
				
			||||||
		drPermission := ctx.NewPermission("role:del")
 | 
							drPermission := ctx.NewPermission("role:del")
 | 
				
			||||||
		db.DELETE(":id", func(c *gin.Context) {
 | 
							db.DELETE(":id", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(delRole).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(delRole).
 | 
				
			||||||
@@ -44,7 +44,7 @@ func InitRoleRouter(router *gin.RouterGroup) {
 | 
				
			|||||||
			ctx.NewReqCtxWithGin(c).Handle(r.RoleResource)
 | 
								ctx.NewReqCtxWithGin(c).Handle(r.RoleResource)
 | 
				
			||||||
		})
 | 
							})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
		saveResource := ctx.NewLogInfo("保存角色资源")
 | 
							saveResource := ctx.NewLogInfo("保存角色资源").WithSave(true)
 | 
				
			||||||
		srPermission := ctx.NewPermission("role:saveResources")
 | 
							srPermission := ctx.NewPermission("role:saveResources")
 | 
				
			||||||
		db.POST(":id/resources", func(c *gin.Context) {
 | 
							db.POST(":id/resources", func(c *gin.Context) {
 | 
				
			||||||
			ctx.NewReqCtxWithGin(c).WithLog(saveResource).
 | 
								ctx.NewReqCtxWithGin(c).WithLog(saveResource).
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										21
									
								
								server/internal/sys/router/syslog.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								server/internal/sys/router/syslog.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,21 @@
 | 
				
			|||||||
 | 
					package router
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/api"
 | 
				
			||||||
 | 
						"mayfly-go/internal/sys/application"
 | 
				
			||||||
 | 
						"mayfly-go/pkg/ctx"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						"github.com/gin-gonic/gin"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func InitSyslogRouter(router *gin.RouterGroup) {
 | 
				
			||||||
 | 
						s := &api.Syslog{
 | 
				
			||||||
 | 
							SyslogApp: application.SyslogApp,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						sys := router.Group("syslogs")
 | 
				
			||||||
 | 
						{
 | 
				
			||||||
 | 
							sys.GET("", func(c *gin.Context) {
 | 
				
			||||||
 | 
								ctx.NewReqCtxWithGin(c).Handle(s.Syslogs)
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -22,12 +22,13 @@ DROP TABLE IF EXISTS `t_db`;
 | 
				
			|||||||
CREATE TABLE `t_db` (
 | 
					CREATE TABLE `t_db` (
 | 
				
			||||||
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 | 
					  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 | 
				
			||||||
  `name` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '数据库实例名称',
 | 
					  `name` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '数据库实例名称',
 | 
				
			||||||
  `host` varchar(20) COLLATE utf8mb4_bin NOT NULL,
 | 
					  `host` varchar(50) COLLATE utf8mb4_bin NOT NULL,
 | 
				
			||||||
  `port` int(8) NOT NULL,
 | 
					  `port` int(8) NOT NULL,
 | 
				
			||||||
  `username` varchar(255) COLLATE utf8mb4_bin NOT NULL,
 | 
					  `username` varchar(255) COLLATE utf8mb4_bin NOT NULL,
 | 
				
			||||||
  `password` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
					  `password` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
				
			||||||
  `type` varchar(20) COLLATE utf8mb4_bin NOT NULL COMMENT '数据库实例类型(mysql...)',
 | 
					  `type` varchar(20) COLLATE utf8mb4_bin NOT NULL COMMENT '数据库实例类型(mysql...)',
 | 
				
			||||||
  `database` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '数据库,空格分割多个数据库',
 | 
					  `database` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '数据库,空格分割多个数据库',
 | 
				
			||||||
 | 
					  `params` varchar(125) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '其他连接参数',
 | 
				
			||||||
  `network` varchar(8) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
					  `network` varchar(8) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
				
			||||||
  `project_id` bigint(20) DEFAULT NULL,
 | 
					  `project_id` bigint(20) DEFAULT NULL,
 | 
				
			||||||
  `project` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
					  `project` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
				
			||||||
@@ -103,7 +104,7 @@ CREATE TABLE `t_machine` (
 | 
				
			|||||||
  `project_id` bigint(20) DEFAULT NULL,
 | 
					  `project_id` bigint(20) DEFAULT NULL,
 | 
				
			||||||
  `project_name` varchar(36) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
					  `project_name` varchar(36) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
				
			||||||
  `name` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
					  `name` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
				
			||||||
  `ip` varchar(18) COLLATE utf8mb4_bin NOT NULL,
 | 
					  `ip` varchar(36) COLLATE utf8mb4_bin NOT NULL,
 | 
				
			||||||
  `port` int(12) NOT NULL,
 | 
					  `port` int(12) NOT NULL,
 | 
				
			||||||
  `username` varchar(12) COLLATE utf8mb4_bin NOT NULL,
 | 
					  `username` varchar(12) COLLATE utf8mb4_bin NOT NULL,
 | 
				
			||||||
  `password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
					  `password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
				
			||||||
@@ -253,9 +254,11 @@ CREATE TABLE `t_project_member` (
 | 
				
			|||||||
DROP TABLE IF EXISTS `t_redis`;
 | 
					DROP TABLE IF EXISTS `t_redis`;
 | 
				
			||||||
CREATE TABLE `t_redis` (
 | 
					CREATE TABLE `t_redis` (
 | 
				
			||||||
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 | 
					  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 | 
				
			||||||
  `host` varchar(32) COLLATE utf8mb4_bin NOT NULL,
 | 
					  `host` varchar(255) COLLATE utf8mb4_bin NOT NULL,
 | 
				
			||||||
  `password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
					  `password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
				
			||||||
  `db` int(32) DEFAULT NULL,
 | 
					  `db` int(32) DEFAULT NULL,
 | 
				
			||||||
 | 
					  `mode` varchar(32) DEFAULT NULL,
 | 
				
			||||||
 | 
					  `remark` varchar(125) DEFAULT NULL,
 | 
				
			||||||
  `project_id` bigint(20) DEFAULT NULL,
 | 
					  `project_id` bigint(20) DEFAULT NULL,
 | 
				
			||||||
  `project` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
					  `project` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL,
 | 
				
			||||||
  `env_id` bigint(20) DEFAULT NULL,
 | 
					  `env_id` bigint(20) DEFAULT NULL,
 | 
				
			||||||
@@ -360,12 +363,11 @@ CREATE TABLE `t_sys_resource` (
 | 
				
			|||||||
-- Records of t_sys_resource
 | 
					-- Records of t_sys_resource
 | 
				
			||||||
-- ----------------------------
 | 
					-- ----------------------------
 | 
				
			||||||
BEGIN;
 | 
					BEGIN;
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (1, 0, 1, 1, '首页', '/home', 1, '{\"component\":\"Home\",\"icon\":\"Home\",\"isAffix\":true,\"isKeepAlive\":true,\"routeName\":\"Home\"}', 1, 'admin', 1, 'admin', '2021-05-25 16:44:41', '2021-05-27 09:12:56');
 | 
					INSERT INTO `t_sys_resource` VALUES (1, 0, 1, 1, '首页', '/home', 1, '{\"component\":\"Home\",\"icon\":\"HomeFilled\",\"isAffix\":true,\"isKeepAlive\":true,\"routeName\":\"Home\"}', 1, 'admin', 1, 'admin', '2021-05-25 16:44:41', '2021-05-27 09:12:56');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (2, 0, 1, 1, '运维', '/ops', 3, '{\"icon\":\"Monitor\",\"isKeepAlive\":true,\"redirect\":\"machine/list\",\"routeName\":\"Ops\"}', 1, 'admin', 1, 'admin', '2021-05-25 16:48:16', '2021-06-08 14:20:24');
 | 
					INSERT INTO `t_sys_resource` VALUES (2, 0, 1, 1, '运维', '/ops', 3, '{\"icon\":\"Monitor\",\"isKeepAlive\":true,\"redirect\":\"machine/list\",\"routeName\":\"Ops\"}', 1, 'admin', 1, 'admin', '2021-05-25 16:48:16', '2021-06-08 14:20:24');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (3, 2, 1, 1, '机器列表', 'machines', 2, '{\"component\":\"MachineList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"MachineList\"}', 2, 'admin', 1, 'admin', '2021-05-25 16:50:04', '2021-06-30 16:20:08');
 | 
					INSERT INTO `t_sys_resource` VALUES (3, 2, 1, 1, '机器列表', 'machines', 2, '{\"component\":\"MachineList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"MachineList\"}', 2, 'admin', 1, 'admin', '2021-05-25 16:50:04', '2021-06-30 16:20:08');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (4, 0, 1, 1, '系统管理', '/sys', 5, '{\"icon\":\"Setting\",\"isKeepAlive\":true,\"redirect\":\"/sys/resources\",\"routeName\":\"sys\"}', 1, 'admin', 1, 'admin', '2021-05-26 15:20:20', '2021-07-29 18:03:06');
 | 
					INSERT INTO `t_sys_resource` VALUES (4, 0, 1, 1, '系统管理', '/sys', 5, '{\"icon\":\"Setting\",\"isKeepAlive\":true,\"redirect\":\"/sys/resources\",\"routeName\":\"sys\"}', 1, 'admin', 1, 'admin', '2021-05-26 15:20:20', '2021-07-29 18:03:06');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (5, 4, 1, 1, '资源管理', 'resources', 3, '{\"component\":\"ResourceList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"ResourceList\"}', 1, 'admin', 1, 'admin', '2021-05-26 15:23:07', '2021-06-08 11:27:55');
 | 
					INSERT INTO `t_sys_resource` VALUES (5, 4, 1, 1, '资源管理', 'resources', 3, '{\"component\":\"ResourceList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"ResourceList\"}', 1, 'admin', 1, 'admin', '2021-05-26 15:23:07', '2021-06-08 11:27:55');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (9, 0, 1, 1, 'iframes', '/iframes', 6, '{\"component\":\"RouterParent\",\"icon\":\"Menu\",\"isIframe\":true,\"isKeepAlive\":true,\"link\":\"https://www.baidu.com\",\"routeName\":\"Iframe\"}', 1, 'admin', 1, 'admin', '2021-05-27 09:58:37', '2021-07-29 18:03:13');
 | 
					 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (11, 4, 1, 1, '角色管理', 'roles', 2, '{\"component\":\"RoleList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"RoleList\"}', 1, 'admin', 1, 'admin', '2021-05-27 11:15:35', '2021-06-03 09:59:41');
 | 
					INSERT INTO `t_sys_resource` VALUES (11, 4, 1, 1, '角色管理', 'roles', 2, '{\"component\":\"RoleList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"RoleList\"}', 1, 'admin', 1, 'admin', '2021-05-27 11:15:35', '2021-06-03 09:59:41');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (12, 3, 2, 1, '机器终端按钮', 'machine:terminal', 4, '', 1, 'admin', 1, 'admin', '2021-05-28 14:06:02', '2021-05-31 17:47:59');
 | 
					INSERT INTO `t_sys_resource` VALUES (12, 3, 2, 1, '机器终端按钮', 'machine:terminal', 4, '', 1, 'admin', 1, 'admin', '2021-05-28 14:06:02', '2021-05-31 17:47:59');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (14, 4, 1, 1, '账号管理', 'accounts', 1, '{\"component\":\"AccountList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"AccountList\"}', 1, 'admin', 1, 'admin', '2021-05-28 14:56:25', '2021-06-03 09:39:22');
 | 
					INSERT INTO `t_sys_resource` VALUES (14, 4, 1, 1, '账号管理', 'accounts', 1, '{\"component\":\"AccountList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"AccountList\"}', 1, 'admin', 1, 'admin', '2021-05-28 14:56:25', '2021-06-03 09:39:22');
 | 
				
			||||||
@@ -380,7 +382,7 @@ INSERT INTO `t_sys_resource` VALUES (22, 11, 2, 1, '角色删除按钮', 'role:d
 | 
				
			|||||||
INSERT INTO `t_sys_resource` VALUES (23, 11, 2, 1, '角色新增按钮', 'role:add', 3, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:02:44', '2021-05-31 19:33:39');
 | 
					INSERT INTO `t_sys_resource` VALUES (23, 11, 2, 1, '角色新增按钮', 'role:add', 3, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:02:44', '2021-05-31 19:33:39');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (24, 11, 2, 1, '角色编辑按钮', 'role:update', 4, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:02:57', '2021-05-31 19:33:40');
 | 
					INSERT INTO `t_sys_resource` VALUES (24, 11, 2, 1, '角色编辑按钮', 'role:update', 4, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:02:57', '2021-05-31 19:33:40');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (25, 5, 2, 1, '资源新增按钮', 'resource:add', 1, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:03:33', '2021-05-31 19:31:47');
 | 
					INSERT INTO `t_sys_resource` VALUES (25, 5, 2, 1, '资源新增按钮', 'resource:add', 1, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:03:33', '2021-05-31 19:31:47');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (26, 5, 2, 1, '资源删除按钮', 'resource:del', 2, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:03:47', '2021-05-31 19:29:40');
 | 
					INSERT INTO `t_sys_resource` VALUES (26, 5, 2, 1, '资源删除按钮', 'resource:delete', 2, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:03:47', '2021-05-31 19:29:40');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (27, 5, 2, 1, '资源编辑按钮', 'resource:update', 3, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:04:03', '2021-05-31 19:29:40');
 | 
					INSERT INTO `t_sys_resource` VALUES (27, 5, 2, 1, '资源编辑按钮', 'resource:update', 3, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:04:03', '2021-05-31 19:29:40');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (28, 5, 2, 1, '资源禁用启用按钮', 'resource:changeStatus', 4, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:04:33', '2021-05-31 18:04:33');
 | 
					INSERT INTO `t_sys_resource` VALUES (28, 5, 2, 1, '资源禁用启用按钮', 'resource:changeStatus', 4, NULL, 1, 'admin', 1, 'admin', '2021-05-31 18:04:33', '2021-05-31 18:04:33');
 | 
				
			||||||
INSERT INTO `t_sys_resource` VALUES (29, 14, 2, 1, '账号添加按钮', 'account:add', 3, NULL, 1, 'admin', 1, 'admin', '2021-05-31 19:23:42', '2021-05-31 19:23:42');
 | 
					INSERT INTO `t_sys_resource` VALUES (29, 14, 2, 1, '账号添加按钮', 'account:add', 3, NULL, 1, 'admin', 1, 'admin', '2021-05-31 19:23:42', '2021-05-31 19:23:42');
 | 
				
			||||||
@@ -426,6 +428,8 @@ INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `wei
 | 
				
			|||||||
INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`) VALUES (81, 80, 2, 1, '基本权限', 'mongo:base', 1, 'null', 1, 'admin', 1, 'admin', '2022-05-13 14:04:16', '2022-05-13 14:04:16');
 | 
					INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`) VALUES (81, 80, 2, 1, '基本权限', 'mongo:base', 1, 'null', 1, 'admin', 1, 'admin', '2022-05-13 14:04:16', '2022-05-13 14:04:16');
 | 
				
			||||||
INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`) VALUES (82, 79, 1, 1, 'Mongo管理', 'mongo-manage', 2, '{\"component\":\"MongoList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"MongoList\"}', 1, 'admin', 1, 'admin', '2022-05-16 18:13:06', '2022-05-16 18:13:06');
 | 
					INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`) VALUES (82, 79, 1, 1, 'Mongo管理', 'mongo-manage', 2, '{\"component\":\"MongoList\",\"icon\":\"Menu\",\"isKeepAlive\":true,\"routeName\":\"MongoList\"}', 1, 'admin', 1, 'admin', '2022-05-16 18:13:06', '2022-05-16 18:13:06');
 | 
				
			||||||
INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`) VALUES (83, 82, 2, 1, '基本权限', 'mongo:manage:base', 1, 'null', 1, 'admin', 1, 'admin', '2022-05-16 18:13:25', '2022-05-16 18:13:25');
 | 
					INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`) VALUES (83, 82, 2, 1, '基本权限', 'mongo:manage:base', 1, 'null', 1, 'admin', 1, 'admin', '2022-05-16 18:13:25', '2022-05-16 18:13:25');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`) VALUES (84, 4, 1, 1, '操作日志', 'syslogs', 4, '{\"component\":\"SyslogList\",\"icon\":\"Tickets\",\"routeName\":\"SyslogList\"}', 1, 'admin', 1, 'admin', '2022-07-13 19:57:07', '2022-07-13 22:58:19');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_resource`(`id`, `pid`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`) VALUES (85, 84, 2, 1, '操作日志基本权限', 'syslog', 1, 'null', 1, 'admin', 1, 'admin', '2022-07-13 19:57:55', '2022-07-13 19:57:55');
 | 
				
			||||||
COMMIT;
 | 
					COMMIT;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
-- ----------------------------
 | 
					-- ----------------------------
 | 
				
			||||||
@@ -622,8 +626,34 @@ INSERT INTO `t_sys_role_resource` VALUES (496, 8, 61, 1, 'admin', '2021-11-05 15
 | 
				
			|||||||
INSERT INTO `t_sys_role_resource` VALUES (497, 8, 62, 1, 'admin', '2021-11-05 15:59:16');
 | 
					INSERT INTO `t_sys_role_resource` VALUES (497, 8, 62, 1, 'admin', '2021-11-05 15:59:16');
 | 
				
			||||||
INSERT INTO `t_sys_role_resource` VALUES (498, 8, 63, 1, 'admin', '2021-11-05 15:59:16');
 | 
					INSERT INTO `t_sys_role_resource` VALUES (498, 8, 63, 1, 'admin', '2021-11-05 15:59:16');
 | 
				
			||||||
INSERT INTO `t_sys_role_resource` VALUES (499, 8, 64, 1, 'admin', '2021-11-05 15:59:16');
 | 
					INSERT INTO `t_sys_role_resource` VALUES (499, 8, 64, 1, 'admin', '2021-11-05 15:59:16');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (500, 1, 72, 1, 'admin', '2022-07-14 11:03:09');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (501, 1, 71, 1, 'admin', '2022-07-14 11:03:09');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (502, 1, 79, 1, 'admin', '2022-07-14 11:03:09');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (503, 1, 80, 1, 'admin', '2022-07-14 11:03:09');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (504, 1, 81, 1, 'admin', '2022-07-14 11:03:09');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (505, 1, 82, 1, 'admin', '2022-07-14 11:03:09');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (506, 1, 83, 1, 'admin', '2022-07-14 11:03:09');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (507, 1, 84, 1, 'admin', '2022-07-14 11:10:11');
 | 
				
			||||||
 | 
					INSERT INTO `t_sys_role_resource`(`id`, `role_id`, `resource_id`, `creator_id`, `creator`, `create_time`) VALUES (508, 1, 85, 1, 'admin', '2022-07-14 11:10:11');
 | 
				
			||||||
COMMIT;
 | 
					COMMIT;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					-- ----------------------------
 | 
				
			||||||
 | 
					-- 表结构: t_sys_log 
 | 
				
			||||||
 | 
					-- ----------------------------
 | 
				
			||||||
 | 
					DROP TABLE IF EXISTS `t_sys_log`;
 | 
				
			||||||
 | 
					CREATE TABLE `t_sys_log` (
 | 
				
			||||||
 | 
					  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 | 
				
			||||||
 | 
					  `type` tinyint(4) NOT NULL COMMENT '类型',
 | 
				
			||||||
 | 
					  `description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '描述',
 | 
				
			||||||
 | 
					  `req_param` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '请求信息',
 | 
				
			||||||
 | 
					  `resp` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '响应信息',
 | 
				
			||||||
 | 
					  `creator` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '调用者',
 | 
				
			||||||
 | 
					  `creator_id` bigint(20) NOT NULL COMMENT '调用者id',
 | 
				
			||||||
 | 
					  `create_time` datetime NOT NULL COMMENT '操作时间',
 | 
				
			||||||
 | 
					  PRIMARY KEY (`id`),
 | 
				
			||||||
 | 
					  KEY `idx_creator_id` (`creator_id`) USING BTREE
 | 
				
			||||||
 | 
					) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='系统操作日志';
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
-- ----------------------------
 | 
					-- ----------------------------
 | 
				
			||||||
-- Table structure for t_mongo
 | 
					-- Table structure for t_mongo
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -7,28 +7,28 @@ type BizError struct {
 | 
				
			|||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
var (
 | 
					var (
 | 
				
			||||||
	Success       *BizError = NewBizErrCode(200, "success")
 | 
						Success       BizError = NewBizErrCode(200, "success")
 | 
				
			||||||
	BizErr        *BizError = NewBizErrCode(400, "biz error")
 | 
						BizErr        BizError = NewBizErrCode(400, "biz error")
 | 
				
			||||||
	ServerError   *BizError = NewBizErrCode(500, "server error")
 | 
						ServerError   BizError = NewBizErrCode(500, "server error")
 | 
				
			||||||
	PermissionErr *BizError = NewBizErrCode(501, "token error")
 | 
						PermissionErr BizError = NewBizErrCode(501, "token error")
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 错误消息
 | 
					// 错误消息
 | 
				
			||||||
func (e *BizError) Error() string {
 | 
					func (e BizError) Error() string {
 | 
				
			||||||
	return e.err
 | 
						return e.err
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 错误码
 | 
					// 错误码
 | 
				
			||||||
func (e *BizError) Code() int16 {
 | 
					func (e BizError) Code() int16 {
 | 
				
			||||||
	return e.code
 | 
						return e.code
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 创建业务逻辑错误结构体,默认为业务逻辑错误
 | 
					// 创建业务逻辑错误结构体,默认为业务逻辑错误
 | 
				
			||||||
func NewBizErr(msg string) *BizError {
 | 
					func NewBizErr(msg string) BizError {
 | 
				
			||||||
	return &BizError{code: BizErr.code, err: msg}
 | 
						return BizError{code: BizErr.code, err: msg}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// 创建业务逻辑错误结构体,可设置指定错误code
 | 
					// 创建业务逻辑错误结构体,可设置指定错误code
 | 
				
			||||||
func NewBizErrCode(code int16, msg string) *BizError {
 | 
					func NewBizErrCode(code int16, msg string) BizError {
 | 
				
			||||||
	return &BizError{code: code, err: msg}
 | 
						return BizError{code: code, err: msg}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -12,20 +12,38 @@ import (
 | 
				
			|||||||
	"github.com/sirupsen/logrus"
 | 
						"github.com/sirupsen/logrus"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type SaveLogFunc func(*ReqCtx)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					var saveLog SaveLogFunc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 设置保存日志处理函数
 | 
				
			||||||
 | 
					func SetSaveLogFunc(sl SaveLogFunc) {
 | 
				
			||||||
 | 
						saveLog = sl
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type LogInfo struct {
 | 
					type LogInfo struct {
 | 
				
			||||||
	LogResp     bool   // 是否记录返回结果
 | 
						LogResp     bool   // 是否记录返回结果
 | 
				
			||||||
	Description string // 请求描述
 | 
						Description string // 请求描述
 | 
				
			||||||
 | 
						Save        bool   // 是否保存日志
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 新建日志信息
 | 
				
			||||||
func NewLogInfo(description string) *LogInfo {
 | 
					func NewLogInfo(description string) *LogInfo {
 | 
				
			||||||
	return &LogInfo{Description: description, LogResp: false}
 | 
						return &LogInfo{Description: description, LogResp: false}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 是否记录返回结果
 | 
				
			||||||
func (i *LogInfo) WithLogResp(logResp bool) *LogInfo {
 | 
					func (i *LogInfo) WithLogResp(logResp bool) *LogInfo {
 | 
				
			||||||
	i.LogResp = logResp
 | 
						i.LogResp = logResp
 | 
				
			||||||
	return i
 | 
						return i
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 是否保存日志
 | 
				
			||||||
 | 
					func (i *LogInfo) WithSave(saveLog bool) *LogInfo {
 | 
				
			||||||
 | 
						i.Save = saveLog
 | 
				
			||||||
 | 
						return i
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func LogHandler(rc *ReqCtx) error {
 | 
					func LogHandler(rc *ReqCtx) error {
 | 
				
			||||||
	li := rc.LogInfo
 | 
						li := rc.LogInfo
 | 
				
			||||||
	if li == nil {
 | 
						if li == nil {
 | 
				
			||||||
@@ -41,6 +59,10 @@ func LogHandler(rc *ReqCtx) error {
 | 
				
			|||||||
	req := rc.GinCtx.Request
 | 
						req := rc.GinCtx.Request
 | 
				
			||||||
	lfs[req.Method] = req.URL.Path
 | 
						lfs[req.Method] = req.URL.Path
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// 如果需要保存日志,并且保存日志处理函数存在则执行保存日志函数
 | 
				
			||||||
 | 
						if li.Save && saveLog != nil {
 | 
				
			||||||
 | 
							go saveLog(rc)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
	if err := rc.Err; err != nil {
 | 
						if err := rc.Err; err != nil {
 | 
				
			||||||
		logger.Log.WithFields(lfs).Error(getErrMsg(rc, err))
 | 
							logger.Log.WithFields(lfs).Error(getErrMsg(rc, err))
 | 
				
			||||||
		return nil
 | 
							return nil
 | 
				
			||||||
@@ -73,7 +95,7 @@ func getErrMsg(rc *ReqCtx, err interface{}) string {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
	var errMsg string
 | 
						var errMsg string
 | 
				
			||||||
	switch t := err.(type) {
 | 
						switch t := err.(type) {
 | 
				
			||||||
	case *biz.BizError:
 | 
						case biz.BizError:
 | 
				
			||||||
		errMsg = fmt.Sprintf("\n<-e errCode: %d, errMsg: %s", t.Code(), t.Error())
 | 
							errMsg = fmt.Sprintf("\n<-e errCode: %d, errMsg: %s", t.Code(), t.Error())
 | 
				
			||||||
	case error:
 | 
						case error:
 | 
				
			||||||
		errMsg = fmt.Sprintf("\n<-e errMsg: %s\n%s", t.Error(), string(debug.Stack()))
 | 
							errMsg = fmt.Sprintf("\n<-e errMsg: %s\n%s", t.Error(), string(debug.Stack()))
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -16,7 +16,6 @@ type HandlerFunc func(*ReqCtx)
 | 
				
			|||||||
type ReqCtx struct {
 | 
					type ReqCtx struct {
 | 
				
			||||||
	GinCtx *gin.Context // gin context
 | 
						GinCtx *gin.Context // gin context
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// NeedToken          bool                // 是否需要token
 | 
					 | 
				
			||||||
	RequiredPermission *Permission         // 需要的权限信息,默认为nil,需要校验token
 | 
						RequiredPermission *Permission         // 需要的权限信息,默认为nil,需要校验token
 | 
				
			||||||
	LoginAccount       *model.LoginAccount // 登录账号信息,只有校验token后才会有值
 | 
						LoginAccount       *model.LoginAccount // 登录账号信息,只有校验token后才会有值
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -26,7 +25,7 @@ type ReqCtx struct {
 | 
				
			|||||||
	Err      interface{} // 请求错误
 | 
						Err      interface{} // 请求错误
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	timed int64 // 执行时间
 | 
						timed int64 // 执行时间
 | 
				
			||||||
	noRes bool  // 无需返回结果,即文件下载等
 | 
						NoRes bool  // 无需返回结果,即文件下载等
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (rc *ReqCtx) Handle(handler HandlerFunc) {
 | 
					func (rc *ReqCtx) Handle(handler HandlerFunc) {
 | 
				
			||||||
@@ -54,14 +53,14 @@ func (rc *ReqCtx) Handle(handler HandlerFunc) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
	begin := time.Now()
 | 
						begin := time.Now()
 | 
				
			||||||
	handler(rc)
 | 
						handler(rc)
 | 
				
			||||||
	rc.timed = time.Now().Sub(begin).Milliseconds()
 | 
						rc.timed = time.Since(begin).Milliseconds()
 | 
				
			||||||
	if !rc.noRes {
 | 
						if !rc.NoRes {
 | 
				
			||||||
		ginx.SuccessRes(ginCtx, rc.ResData)
 | 
							ginx.SuccessRes(ginCtx, rc.ResData)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func (rc *ReqCtx) Download(reader io.Reader, filename string) {
 | 
					func (rc *ReqCtx) Download(reader io.Reader, filename string) {
 | 
				
			||||||
	rc.noRes = true
 | 
						rc.NoRes = true
 | 
				
			||||||
	ginx.Download(rc.GinCtx, reader, filename)
 | 
						ginx.Download(rc.GinCtx, reader, filename)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -62,7 +62,7 @@ func SuccessRes(g *gin.Context, data interface{}) {
 | 
				
			|||||||
// 返回失败结果集
 | 
					// 返回失败结果集
 | 
				
			||||||
func ErrorRes(g *gin.Context, err interface{}) {
 | 
					func ErrorRes(g *gin.Context, err interface{}) {
 | 
				
			||||||
	switch t := err.(type) {
 | 
						switch t := err.(type) {
 | 
				
			||||||
	case *biz.BizError:
 | 
						case biz.BizError:
 | 
				
			||||||
		g.JSON(http.StatusOK, model.Error(t))
 | 
							g.JSON(http.StatusOK, model.Error(t))
 | 
				
			||||||
	case error:
 | 
						case error:
 | 
				
			||||||
		g.JSON(http.StatusOK, model.ServerError())
 | 
							g.JSON(http.StatusOK, model.ServerError())
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,7 +1,7 @@
 | 
				
			|||||||
package global
 | 
					package global
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"github.com/go-redis/redis"
 | 
						"github.com/go-redis/redis/v8"
 | 
				
			||||||
	"github.com/sirupsen/logrus"
 | 
						"github.com/sirupsen/logrus"
 | 
				
			||||||
	"gorm.io/gorm"
 | 
						"gorm.io/gorm"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -44,7 +44,7 @@ func SuccessNoData() *Result {
 | 
				
			|||||||
	return &Result{Code: SuccessCode, Msg: SuccessMsg}
 | 
						return &Result{Code: SuccessCode, Msg: SuccessMsg}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func Error(bizerr *biz.BizError) *Result {
 | 
					func Error(bizerr biz.BizError) *Result {
 | 
				
			||||||
	return &Result{Code: bizerr.Code(), Msg: bizerr.Error()}
 | 
						return &Result{Code: bizerr.Code(), Msg: bizerr.Error()}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,10 +1,11 @@
 | 
				
			|||||||
package rediscli
 | 
					package rediscli
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/go-redis/redis"
 | 
						"github.com/go-redis/redis/v8"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
var cli *redis.Client
 | 
					var cli *redis.Client
 | 
				
			||||||
@@ -19,7 +20,7 @@ func GetCli() *redis.Client {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
// get key value
 | 
					// get key value
 | 
				
			||||||
func Get(key string) string {
 | 
					func Get(key string) string {
 | 
				
			||||||
	val, err := cli.Get(key).Result()
 | 
						val, err := cli.Get(context.TODO(), key).Result()
 | 
				
			||||||
	switch {
 | 
						switch {
 | 
				
			||||||
	case err == redis.Nil:
 | 
						case err == redis.Nil:
 | 
				
			||||||
		fmt.Println("key does not exist")
 | 
							fmt.Println("key does not exist")
 | 
				
			||||||
@@ -33,32 +34,32 @@ func Get(key string) string {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
// set key value
 | 
					// set key value
 | 
				
			||||||
func Set(key string, val string, expiration time.Duration) {
 | 
					func Set(key string, val string, expiration time.Duration) {
 | 
				
			||||||
	cli.Set(key, val, expiration)
 | 
						cli.Set(context.TODO(), key, val, expiration)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func HSet(key string, field string, val interface{}) {
 | 
					func HSet(key string, field string, val interface{}) {
 | 
				
			||||||
	cli.HSet(key, field, val)
 | 
						cli.HSet(context.TODO(), key, field, val)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// hget
 | 
					// hget
 | 
				
			||||||
func HGet(key string, field string) string {
 | 
					func HGet(key string, field string) string {
 | 
				
			||||||
	val, _ := cli.HGet(key, field).Result()
 | 
						val, _ := cli.HGet(context.TODO(), key, field).Result()
 | 
				
			||||||
	return val
 | 
						return val
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// hget
 | 
					// hget
 | 
				
			||||||
func HExist(key string, field string) bool {
 | 
					func HExist(key string, field string) bool {
 | 
				
			||||||
	val, _ := cli.HExists(key, field).Result()
 | 
						val, _ := cli.HExists(context.TODO(), key, field).Result()
 | 
				
			||||||
	return val
 | 
						return val
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// hgetall
 | 
					// hgetall
 | 
				
			||||||
func HGetAll(key string) map[string]string {
 | 
					func HGetAll(key string) map[string]string {
 | 
				
			||||||
	vals, _ := cli.HGetAll(key).Result()
 | 
						vals, _ := cli.HGetAll(context.TODO(), key).Result()
 | 
				
			||||||
	return vals
 | 
						return vals
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// hdel
 | 
					// hdel
 | 
				
			||||||
func HDel(key string, fields ...string) int {
 | 
					func HDel(key string, fields ...string) int {
 | 
				
			||||||
	return int(cli.HDel(key, fields...).Val())
 | 
						return int(cli.HDel(context.TODO(), key, fields...).Val())
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,11 +1,12 @@
 | 
				
			|||||||
package starter
 | 
					package starter
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"mayfly-go/pkg/config"
 | 
						"mayfly-go/pkg/config"
 | 
				
			||||||
	"mayfly-go/pkg/global"
 | 
						"mayfly-go/pkg/global"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"github.com/go-redis/redis"
 | 
						"github.com/go-redis/redis/v8"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
func InitRedis() {
 | 
					func InitRedis() {
 | 
				
			||||||
@@ -26,7 +27,7 @@ func ConnRedis() *redis.Client {
 | 
				
			|||||||
		DB:       redisConf.Db,       // use default DB
 | 
							DB:       redisConf.Db,       // use default DB
 | 
				
			||||||
	})
 | 
						})
 | 
				
			||||||
	// 测试连接
 | 
						// 测试连接
 | 
				
			||||||
	_, e := rdb.Ping().Result()
 | 
						_, e := rdb.Ping(context.TODO()).Result()
 | 
				
			||||||
	if e != nil {
 | 
						if e != nil {
 | 
				
			||||||
		global.Log.Panic(fmt.Sprintf("连接redis失败! [%s:%d]", redisConf.Host, redisConf.Port))
 | 
							global.Log.Panic(fmt.Sprintf("连接redis失败! [%s:%d]", redisConf.Host, redisConf.Port))
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -13,6 +13,9 @@ func RunWebServer() {
 | 
				
			|||||||
	ctx.UseBeforeHandlerInterceptor(ctx.PermissionHandler)
 | 
						ctx.UseBeforeHandlerInterceptor(ctx.PermissionHandler)
 | 
				
			||||||
	// 日志处理器
 | 
						// 日志处理器
 | 
				
			||||||
	ctx.UseAfterHandlerInterceptor(ctx.LogHandler)
 | 
						ctx.UseAfterHandlerInterceptor(ctx.LogHandler)
 | 
				
			||||||
 | 
						// 设置日志保存函数
 | 
				
			||||||
 | 
						ctx.SetSaveLogFunc(initialize.InitSaveLogFunc())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// 注册路由
 | 
						// 注册路由
 | 
				
			||||||
	web := initialize.InitRouter()
 | 
						web := initialize.InitRouter()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,8 +1,15 @@
 | 
				
			|||||||
package utils
 | 
					package utils
 | 
				
			||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
 | 
						"bytes"
 | 
				
			||||||
	"crypto/md5"
 | 
						"crypto/md5"
 | 
				
			||||||
 | 
						"crypto/rand"
 | 
				
			||||||
 | 
						"crypto/rsa"
 | 
				
			||||||
 | 
						"crypto/x509"
 | 
				
			||||||
 | 
						"encoding/base64"
 | 
				
			||||||
	"encoding/hex"
 | 
						"encoding/hex"
 | 
				
			||||||
 | 
						"encoding/pem"
 | 
				
			||||||
 | 
						"errors"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// md5
 | 
					// md5
 | 
				
			||||||
@@ -11,3 +18,115 @@ func Md5(str string) string {
 | 
				
			|||||||
	h.Write([]byte(str))
 | 
						h.Write([]byte(str))
 | 
				
			||||||
	return hex.EncodeToString(h.Sum(nil))
 | 
						return hex.EncodeToString(h.Sum(nil))
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 系统统一RSA秘钥对
 | 
				
			||||||
 | 
					var RsaPair []string
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 生成RSA私钥和公钥字符串
 | 
				
			||||||
 | 
					// bits 证书大小
 | 
				
			||||||
 | 
					// @return privateKeyStr publicKeyStr error
 | 
				
			||||||
 | 
					func GenerateRSAKey(bits int) (string, string, error) {
 | 
				
			||||||
 | 
						var privateKeyStr, publicKeyStr string
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						//GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
 | 
				
			||||||
 | 
						//Reader是一个全局、共享的密码用强随机数生成器
 | 
				
			||||||
 | 
						privateKey, err := rsa.GenerateKey(rand.Reader, bits)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return privateKeyStr, publicKeyStr, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						//保存私钥
 | 
				
			||||||
 | 
						//通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串
 | 
				
			||||||
 | 
						X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
 | 
				
			||||||
 | 
						//构建一个pem.Block结构体对象
 | 
				
			||||||
 | 
						privateBlock := pem.Block{Type: "RSA Private Key", Bytes: X509PrivateKey}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						privateBuf := new(bytes.Buffer)
 | 
				
			||||||
 | 
						pem.Encode(privateBuf, &privateBlock)
 | 
				
			||||||
 | 
						privateKeyStr = privateBuf.String()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						//保存公钥
 | 
				
			||||||
 | 
						//获取公钥的数据
 | 
				
			||||||
 | 
						publicKey := privateKey.PublicKey
 | 
				
			||||||
 | 
						//X509对公钥编码
 | 
				
			||||||
 | 
						X509PublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return publicKeyStr, privateKeyStr, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						//创建一个pem.Block结构体对象
 | 
				
			||||||
 | 
						publicBlock := pem.Block{Type: "RSA Public Key", Bytes: X509PublicKey}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						publicBuf := new(bytes.Buffer)
 | 
				
			||||||
 | 
						pem.Encode(publicBuf, &publicBlock)
 | 
				
			||||||
 | 
						publicKeyStr = publicBuf.String()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return privateKeyStr, publicKeyStr, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// rsa解密
 | 
				
			||||||
 | 
					func RsaDecrypt(privateKeyStr string, data []byte) ([]byte, error) {
 | 
				
			||||||
 | 
						block, _ := pem.Decode([]byte(privateKeyStr))
 | 
				
			||||||
 | 
						if block == nil {
 | 
				
			||||||
 | 
							return nil, errors.New("private key error")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return nil, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						return rsa.DecryptPKCS1v15(rand.Reader, priv, data)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 使用系统默认的私钥解密
 | 
				
			||||||
 | 
					// @param base64 字符串是否使用base64编码
 | 
				
			||||||
 | 
					func DefaultRsaDecrypt(data string, useBase64 bool) (string, error) {
 | 
				
			||||||
 | 
						// 空字符串不解密
 | 
				
			||||||
 | 
						if data == "" {
 | 
				
			||||||
 | 
							return "", nil
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						if useBase64 {
 | 
				
			||||||
 | 
							if decodeBase64, err := base64.StdEncoding.DecodeString(data); err != nil {
 | 
				
			||||||
 | 
								return "", err
 | 
				
			||||||
 | 
							} else {
 | 
				
			||||||
 | 
								data = string(decodeBase64)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						priKey, err := GetRsaPrivateKey()
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return "", err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						val, err := RsaDecrypt(priKey, []byte(data))
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return "", err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						return string(val), nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 获取系统的RSA公钥
 | 
				
			||||||
 | 
					func GetRsaPublicKey() (string, error) {
 | 
				
			||||||
 | 
						if len(RsaPair) == 2 {
 | 
				
			||||||
 | 
							return RsaPair[1], nil
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						privateKey, publicKey, err := GenerateRSAKey(1024)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return "", err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						RsaPair = append(RsaPair, privateKey)
 | 
				
			||||||
 | 
						RsaPair = append(RsaPair, publicKey)
 | 
				
			||||||
 | 
						return publicKey, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// 获取系统私钥
 | 
				
			||||||
 | 
					func GetRsaPrivateKey() (string, error) {
 | 
				
			||||||
 | 
						if len(RsaPair) == 2 {
 | 
				
			||||||
 | 
							return RsaPair[0], nil
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						privateKey, publicKey, err := GenerateRSAKey(1024)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return "", err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						RsaPair = append(RsaPair, privateKey)
 | 
				
			||||||
 | 
						RsaPair = append(RsaPair, publicKey)
 | 
				
			||||||
 | 
						return privateKey, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -2,6 +2,8 @@ package utils
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"bytes"
 | 
						"bytes"
 | 
				
			||||||
 | 
						"encoding/json"
 | 
				
			||||||
 | 
						"strconv"
 | 
				
			||||||
	"strings"
 | 
						"strings"
 | 
				
			||||||
	"text/template"
 | 
						"text/template"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
@@ -107,3 +109,45 @@ func ReverStrTemplate(temp, str string, res map[string]interface{}) {
 | 
				
			|||||||
		ReverStrTemplate(next, StrTrim(SubString(str, UnicodeIndex(str, value)+StrLen(value), StrLen(str))), res)
 | 
							ReverStrTemplate(next, StrTrim(SubString(str, UnicodeIndex(str, value)+StrLen(value), StrLen(str))), res)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func ToString(value interface{}) string {
 | 
				
			||||||
 | 
						// interface 转 string
 | 
				
			||||||
 | 
						var key string
 | 
				
			||||||
 | 
						if value == nil {
 | 
				
			||||||
 | 
							return key
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						switch it := value.(type) {
 | 
				
			||||||
 | 
						case float64:
 | 
				
			||||||
 | 
							return strconv.FormatFloat(it, 'f', -1, 64)
 | 
				
			||||||
 | 
						case float32:
 | 
				
			||||||
 | 
							return strconv.FormatFloat(float64(it), 'f', -1, 64)
 | 
				
			||||||
 | 
						case int:
 | 
				
			||||||
 | 
							return strconv.Itoa(it)
 | 
				
			||||||
 | 
						case uint:
 | 
				
			||||||
 | 
							return strconv.Itoa(int(it))
 | 
				
			||||||
 | 
						case int8:
 | 
				
			||||||
 | 
							return strconv.Itoa(int(it))
 | 
				
			||||||
 | 
						case uint8:
 | 
				
			||||||
 | 
							return strconv.Itoa(int(it))
 | 
				
			||||||
 | 
						case int16:
 | 
				
			||||||
 | 
							return strconv.Itoa(int(it))
 | 
				
			||||||
 | 
						case uint16:
 | 
				
			||||||
 | 
							return strconv.Itoa(int(it))
 | 
				
			||||||
 | 
						case int32:
 | 
				
			||||||
 | 
							return strconv.Itoa(int(it))
 | 
				
			||||||
 | 
						case uint32:
 | 
				
			||||||
 | 
							return strconv.Itoa(int(it))
 | 
				
			||||||
 | 
						case int64:
 | 
				
			||||||
 | 
							return strconv.FormatInt(it, 10)
 | 
				
			||||||
 | 
						case uint64:
 | 
				
			||||||
 | 
							return strconv.FormatUint(it, 10)
 | 
				
			||||||
 | 
						case string:
 | 
				
			||||||
 | 
							return it
 | 
				
			||||||
 | 
						case []byte:
 | 
				
			||||||
 | 
							return string(value.([]byte))
 | 
				
			||||||
 | 
						default:
 | 
				
			||||||
 | 
							newValue, _ := json.Marshal(value)
 | 
				
			||||||
 | 
							return string(newValue)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,7 +1,8 @@
 | 
				
			|||||||
后端配置:
 | 
					相关配置文件: 
 | 
				
			||||||
  服务端口,mysql等信息在config.yml里配置即可。
 | 
					  后端:
 | 
				
			||||||
前端配置:
 | 
					    config.yml: 服务端口,mysql等信息在此配置即可。
 | 
				
			||||||
  static/config.js中的api地址配成启动后的后端服务的真实地址即可
 | 
					  前端:
 | 
				
			||||||
 | 
					    static/config.js: 若前后端分开部署则将该文件中的api地址配成后端服务的真实地址即可,否则无需修改。
 | 
				
			||||||
 | 
					
 | 
				
			||||||
服务启动:./startup.sh
 | 
					服务启动:./startup.sh
 | 
				
			||||||
服务关闭:./shutdown.sh
 | 
					服务关闭:./shutdown.sh
 | 
				
			||||||
 
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user