mirror of
https://gitee.com/dromara/mayfly-go
synced 2025-11-02 15:30:25 +08:00
1
.gitignore
vendored
1
.gitignore
vendored
@@ -17,4 +17,5 @@
|
||||
*/node_modules/
|
||||
**/vendor/
|
||||
.idea
|
||||
.vscode
|
||||
out
|
||||
|
||||
@@ -106,7 +106,7 @@ function buildDocker() {
|
||||
imageVersion=$1
|
||||
cd ${server_folder}
|
||||
imageName="mayflygo/mayfly-go:${imageVersion}"
|
||||
docker build -t "${imageName}" .
|
||||
docker build --platform linux/amd64 -t "${imageName}" .
|
||||
echo_green "docker镜像构建完成->[${imageName}]"
|
||||
echo_yellow "-------------------构建docker镜像结束-------------------"
|
||||
}
|
||||
@@ -197,4 +197,4 @@ function runBuild() {
|
||||
rm -rf ${server_folder}/static/static/index.html
|
||||
}
|
||||
|
||||
runBuild
|
||||
runBuild
|
||||
|
||||
@@ -6,6 +6,7 @@ export default {
|
||||
changePwd: (param: any) => request.post('/sys/accounts/change-pwd', param),
|
||||
getPublicKey: () => request.get('/common/public-key'),
|
||||
getConfigValue: (params: any) => request.get('/sys/configs/value', params),
|
||||
oauthConfig: () => request.get('/sys/configs/auth'),
|
||||
captcha: () => request.get('/sys/captcha'),
|
||||
logout: () => request.post('/sys/accounts/logout/{token}'),
|
||||
getPermissions: () => request.get('/sys/accounts/permissions'),
|
||||
|
||||
@@ -2,37 +2,24 @@
|
||||
<div>
|
||||
<el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="login-content-form" size="large">
|
||||
<el-form-item prop="username">
|
||||
<el-input type="text" placeholder="请输入用户名" prefix-icon="user" v-model="loginForm.username" clearable autocomplete="off"> </el-input>
|
||||
<el-input type="text" placeholder="请输入用户名" prefix-icon="user" v-model="loginForm.username" clearable
|
||||
autocomplete="off"> </el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="password">
|
||||
<el-input
|
||||
type="password"
|
||||
placeholder="请输入密码"
|
||||
prefix-icon="lock"
|
||||
v-model="loginForm.password"
|
||||
autocomplete="off"
|
||||
@keyup.enter="login"
|
||||
show-password
|
||||
>
|
||||
<el-input type="password" placeholder="请输入密码" prefix-icon="lock" v-model="loginForm.password"
|
||||
autocomplete="off" @keyup.enter="login" show-password>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="accountLoginSecurity.useCaptcha" prop="captcha">
|
||||
<el-row :gutter="15">
|
||||
<el-col :span="16">
|
||||
<el-input
|
||||
type="text"
|
||||
maxlength="6"
|
||||
placeholder="请输入验证码"
|
||||
prefix-icon="position"
|
||||
v-model="loginForm.captcha"
|
||||
clearable
|
||||
autocomplete="off"
|
||||
@keyup.enter="login"
|
||||
></el-input>
|
||||
<el-input type="text" maxlength="6" placeholder="请输入验证码" prefix-icon="position"
|
||||
v-model="loginForm.captcha" clearable autocomplete="off" @keyup.enter="login"></el-input>
|
||||
</el-col>
|
||||
<el-col :span="8">
|
||||
<div class="login-content-code">
|
||||
<img class="login-content-code-img" @click="getCaptcha" width="130px" height="40px" :src="captchaImage" style="cursor: pointer" />
|
||||
<img class="login-content-code-img" @click="getCaptcha" width="130px" height="40px"
|
||||
:src="captchaImage" style="cursor: pointer" />
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
@@ -47,21 +34,19 @@
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<el-dialog title="修改密码" v-model="changePwdDialog.visible" :close-on-click-modal="false" width="450px" :destroy-on-close="true">
|
||||
<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="auto">
|
||||
<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-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-input v-model.trim="changePwdDialog.form.newPassword" placeholder="须为8位以上且包含字⺟⼤⼩写+数字+特殊符号"
|
||||
type="password" autocomplete="new-password"></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
@@ -73,28 +58,17 @@
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
title="OTP校验"
|
||||
v-model="otpDialog.visible"
|
||||
@close="loading.signIn = false"
|
||||
:close-on-click-modal="false"
|
||||
width="350px"
|
||||
:destroy-on-close="true"
|
||||
>
|
||||
<el-form ref="otpFormRef" :model="otpDialog.form" :rules="otpDialog.rules" @submit.native.prevent label-width="auto">
|
||||
<el-dialog title="OTP校验" v-model="otpDialog.visible" @close="loading.signIn = false" :close-on-click-modal="false"
|
||||
width="350px" :destroy-on-close="true">
|
||||
<el-form ref="otpFormRef" :model="otpDialog.form" :rules="otpDialog.rules" @submit.native.prevent
|
||||
label-width="auto">
|
||||
<el-form-item v-if="otpDialog.otpUrl" label="二维码">
|
||||
<qrcode-vue :value="otpDialog.otpUrl" :size="200" level="H" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item prop="code" label="OTP" required>
|
||||
<el-input
|
||||
style="width: 220px"
|
||||
ref="otpCodeInputRef"
|
||||
v-model.trim="otpDialog.form.code"
|
||||
clearable
|
||||
@keyup.enter="otpVerify"
|
||||
placeholder="请输入令牌APP中显示的授权码"
|
||||
></el-input>
|
||||
<el-input style="width: 220px" ref="otpCodeInputRef" v-model.trim="otpDialog.form.code" clearable
|
||||
@keyup.enter="otpVerify" placeholder="请输入令牌APP中显示的授权码"></el-input>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
@@ -265,10 +239,14 @@ const onSignIn = async () => {
|
||||
return;
|
||||
}
|
||||
state.showLoginFailTips = false;
|
||||
loginResDeal(loginRes);
|
||||
}
|
||||
|
||||
const loginResDeal = (loginRes: any) => {
|
||||
// 用户信息
|
||||
const userInfos = {
|
||||
name: loginRes.name,
|
||||
username: state.loginForm.username,
|
||||
username: loginRes.username,
|
||||
// 头像
|
||||
photo: letterAvatar(state.loginForm.username),
|
||||
time: new Date().getTime(),
|
||||
@@ -297,6 +275,10 @@ const onSignIn = async () => {
|
||||
}, 400);
|
||||
};
|
||||
|
||||
defineExpose({
|
||||
loginResDeal
|
||||
});
|
||||
|
||||
// 登录成功后的跳转
|
||||
const signInSuccess = async (accessToken: string = '') => {
|
||||
// 存储 token 到浏览器缓存
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<el-tabs v-model="tabsActiveName" @tab-click="onTabsClick">
|
||||
<el-tab-pane label="账号密码登录" name="account" :disabled="tabsActiveName === 'account'">
|
||||
<transition name="el-zoom-in-center">
|
||||
<Account v-show="isTabPaneShow" />
|
||||
<Account v-show="isTabPaneShow" ref="loginForm" />
|
||||
</transition>
|
||||
</el-tab-pane>
|
||||
<!-- <el-tab-pane label="手机号登录" name="mobile" :disabled="tabsActiveName === 'mobile'">
|
||||
@@ -18,10 +18,19 @@
|
||||
</transition>
|
||||
</el-tab-pane> -->
|
||||
</el-tabs>
|
||||
<!-- <div class="mt10">
|
||||
<div class="mt10" v-show="authConfig.oauth2">
|
||||
<el-button type="text" size="small">第三方登录</el-button>
|
||||
<el-button type="text" size="small">友情链接</el-button>
|
||||
</div> -->
|
||||
<!-- <el-button type="text" size="small">友情链接</el-button> -->
|
||||
</div>
|
||||
<div class="mt10" v-show="authConfig.oauth2">
|
||||
<el-tooltip content="使用OAuth2登录" placement="top-start">
|
||||
<el-button type="text" size="small" @click="oauth2Login">
|
||||
<el-icon :size="18">
|
||||
<Menu />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- <div class="login-copyright">
|
||||
@@ -32,23 +41,58 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { toRefs, reactive } from 'vue';
|
||||
import { toRefs, reactive, onMounted, h, ref } from 'vue';
|
||||
import Account from '@/views/login/component/AccountLogin.vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useThemeConfig } from '@/store/themeConfig';
|
||||
import openApi from '@/common/openApi';
|
||||
import config from '@/common/config';
|
||||
|
||||
const { themeConfig } = storeToRefs(useThemeConfig());
|
||||
const state = reactive({
|
||||
tabsActiveName: 'account',
|
||||
isTabPaneShow: true,
|
||||
authConfig: {
|
||||
oauth2: false,
|
||||
},
|
||||
});
|
||||
|
||||
const { isTabPaneShow, tabsActiveName } = toRefs(state);
|
||||
const loginForm = ref<{ loginResDeal: (data: any) => void } | null>(null);
|
||||
|
||||
const { isTabPaneShow, tabsActiveName, authConfig, } = toRefs(state);
|
||||
|
||||
// 切换密码、手机登录
|
||||
const onTabsClick = () => {
|
||||
state.isTabPaneShow = !state.isTabPaneShow;
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
state.authConfig = await openApi.oauthConfig();
|
||||
|
||||
});
|
||||
|
||||
const oauth2Login = () => {
|
||||
// 小窗口打开oauth2鉴权
|
||||
let oauthWindoe = window.open(config.baseApiUrl + "/sys/auth/oauth2/login", "oauth2", "width=600,height=600");
|
||||
if (oauthWindoe) {
|
||||
const handler = (e: any) => {
|
||||
if (e.data.action === "oauthLogin") {
|
||||
oauthWindoe!.close();
|
||||
window.removeEventListener("message", handler);
|
||||
// 处理登录token
|
||||
console.log(e.data);
|
||||
loginForm.value!.loginResDeal(e.data);
|
||||
}
|
||||
}
|
||||
window.addEventListener("message", handler);
|
||||
setInterval(() => {
|
||||
if (oauthWindoe!.closed) {
|
||||
window.removeEventListener("message", handler);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
|
||||
@@ -3,5 +3,6 @@ import Api from '@/common/Api';
|
||||
export const personApi = {
|
||||
accountInfo: Api.newGet('/sys/accounts/self'),
|
||||
updateAccount: Api.newPut('/sys/accounts/self'),
|
||||
authStatus: Api.newGet('/sys/auth/status'),
|
||||
getMsgs: Api.newGet('/msgs/self'),
|
||||
};
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
</div>
|
||||
<div class="personal-user-right">
|
||||
<el-row>
|
||||
<el-col :span="24" class="personal-title mb18"
|
||||
>{{ currentTime }},{{ userInfo.name }},生活变的再糟糕,也不妨碍我变得更好!
|
||||
<el-col :span="24" class="personal-title mb18">{{ currentTime }},{{ userInfo.name
|
||||
}},生活变的再糟糕,也不妨碍我变得更好!
|
||||
</el-col>
|
||||
<el-col :span="24">
|
||||
<el-row>
|
||||
@@ -77,16 +77,9 @@
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-row type="flex" class="mt5" justify="center">
|
||||
<el-pagination
|
||||
small
|
||||
@current-change="getMsgs"
|
||||
style="text-align: center"
|
||||
background
|
||||
layout="prev, pager, next, total, jumper"
|
||||
:total="msgDialog.msgs.total"
|
||||
v-model:current-page="msgDialog.query.pageNum"
|
||||
:page-size="msgDialog.query.pageSize"
|
||||
/>
|
||||
<el-pagination small @current-change="getMsgs" style="text-align: center" background
|
||||
layout="prev, pager, next, total, jumper" :total="msgDialog.msgs.total"
|
||||
v-model:current-page="msgDialog.query.pageNum" :page-size="msgDialog.query.pageSize" />
|
||||
</el-row>
|
||||
</el-dialog>
|
||||
|
||||
@@ -115,7 +108,8 @@
|
||||
<el-row :gutter="35">
|
||||
<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
|
||||
<el-form-item label="密码">
|
||||
<el-input type="password" show-password v-model="accountForm.password" placeholder="请输入新密码" clearable></el-input>
|
||||
<el-input type="password" show-password v-model="accountForm.password"
|
||||
placeholder="请输入新密码" clearable></el-input>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<!-- -->
|
||||
@@ -160,18 +154,20 @@
|
||||
<el-button type="text">立即设置</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="personal-edit-safe-box">
|
||||
</div> -->
|
||||
<div v-show="authStatus.enable.oauth2" class="personal-edit-safe-box">
|
||||
<div class="personal-edit-safe-item">
|
||||
<div class="personal-edit-safe-item-left">
|
||||
<div class="personal-edit-safe-item-left-label">绑定QQ</div>
|
||||
<div class="personal-edit-safe-item-left-value">已绑定QQ:110****566</div>
|
||||
<div class="personal-edit-safe-item-left-label">绑定OAuth2</div>
|
||||
<div class="personal-edit-safe-item-left-value">
|
||||
{{ authStatus.bind.oauth2 ? '已绑定' : '未绑定' }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="personal-edit-safe-item-right">
|
||||
<el-button type="text">立即设置</el-button>
|
||||
<el-button type="text" @click="bindOAuth2" :disabled="authStatus.bind.oauth2">立即绑定</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div> -->
|
||||
</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
</el-row>
|
||||
@@ -186,6 +182,8 @@ import { personApi } from './api';
|
||||
import { dateFormat } from '@/common/utils/date';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useUserInfo } from '@/store/userInfo';
|
||||
import config from '@/common/config';
|
||||
import { getSession } from '@/common/utils/storage';
|
||||
|
||||
const { userInfo } = storeToRefs(useUserInfo());
|
||||
const state = reactive({
|
||||
@@ -208,9 +206,13 @@ const state = reactive({
|
||||
accountForm: {
|
||||
password: '',
|
||||
},
|
||||
authStatus: {
|
||||
enable: { oauth2: false },
|
||||
bind: { oauth2: false }
|
||||
}
|
||||
});
|
||||
|
||||
const { msgDialog, accountForm } = toRefs(state);
|
||||
const { msgDialog, accountForm, authStatus } = toRefs(state);
|
||||
|
||||
// 当前时间提示语
|
||||
const currentTime = computed(() => {
|
||||
@@ -228,9 +230,10 @@ const roleInfo = computed(() => {
|
||||
return state.accountInfo.roles.map((val: any) => val.name).join('、');
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
onMounted(async () => {
|
||||
getAccountInfo();
|
||||
getMsgs();
|
||||
state.authStatus = await personApi.authStatus.request()
|
||||
});
|
||||
|
||||
const getAccountInfo = async () => {
|
||||
@@ -242,6 +245,31 @@ const updateAccount = async () => {
|
||||
ElMessage.success('更新成功');
|
||||
};
|
||||
|
||||
const bindOAuth2 = () => {
|
||||
// 小窗口打开oauth2鉴权
|
||||
let oauthWindoe = window.open(config.baseApiUrl + "/sys/auth/oauth2/bind?token=" + getSession('token'), "oauth2", "width=600,height=600");
|
||||
if (oauthWindoe) {
|
||||
const handler = (e: any) => {
|
||||
if (e.data.action === "oauthBind") {
|
||||
oauthWindoe!.close();
|
||||
window.removeEventListener("message", handler);
|
||||
// 处理登录token
|
||||
console.log(e.data);
|
||||
ElMessage.success('绑定成功');
|
||||
setTimeout(() => {
|
||||
location.reload();
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
window.addEventListener("message", handler);
|
||||
setInterval(() => {
|
||||
if (oauthWindoe!.closed) {
|
||||
window.removeEventListener("message", handler);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
const getMsgs = async () => {
|
||||
const res = await personApi.getMsgs.request(state.msgDialog.query);
|
||||
state.msgDialog.msgs = res;
|
||||
|
||||
@@ -43,3 +43,8 @@ export const configApi = {
|
||||
export const logApi = {
|
||||
list: Api.newGet('/syslogs'),
|
||||
};
|
||||
|
||||
export const authApi = {
|
||||
info: Api.newGet('/sys/auth'),
|
||||
saveOAuth2: Api.newPut('/sys/auth/oauth2'),
|
||||
};
|
||||
|
||||
105
mayfly_go_web/src/views/system/auth/AuthInfo.vue
Normal file
105
mayfly_go_web/src/views/system/auth/AuthInfo.vue
Normal file
@@ -0,0 +1,105 @@
|
||||
<template>
|
||||
<el-card>
|
||||
<template #header>
|
||||
<el-space>
|
||||
<span>登录认证</span>
|
||||
<el-text type="info">管理三方登录认证平台</el-text>
|
||||
</el-space>
|
||||
</template>
|
||||
<el-card>
|
||||
<template #header>
|
||||
<el-space>
|
||||
<span>OAuth2.0</span>
|
||||
<el-text type="info">自定义oauth2.0 server登录</el-text>
|
||||
</el-space>
|
||||
</template>
|
||||
<el-form ref="oauth2Form" :model="oauth2" label-width="160px" status-icon>
|
||||
<el-form-item prop="clientID" label="Client ID" required>
|
||||
<el-input v-model="oauth2.clientID" placeholder="客户端id"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="clientSecret" label="Client secret" required>
|
||||
<el-input v-model="oauth2.clientSecret" placeholder="客户端密钥"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="authorizationURL" label="Authorization URL" required>
|
||||
<el-input v-model="oauth2.authorizationURL"
|
||||
placeholder="授权码获取地址 例如: https://example.com/oauth/authorize"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="accessTokenURL" label="Access token URL" required>
|
||||
<el-input v-model="oauth2.accessTokenURL"
|
||||
placeholder="访问token获取地址 例如: https://example.com/oauth/token"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="resourceURL" label="Resource URL" required>
|
||||
<el-input v-model="oauth2.resourceURL"
|
||||
placeholder="获取用户信息地址 例如: https://example.com/api/v4/user"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="redirectURL" label="Redirect URL" required>
|
||||
<el-input v-model="oauth2.redirectURL" placeholder="mayfly地址 例如: http://localhost:8889/"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="userIdentifier" label="User identifier" required>
|
||||
<el-input v-model="oauth2.userIdentifier"
|
||||
placeholder="用户唯一标识key 例如:username,如果有多层可以写为: data.username"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="scopes" label="Scopes" required>
|
||||
<el-input v-model="oauth2.scopes" placeholder="read_user,read_api 多个使用,分割"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="autoRegister" label="自动注册">
|
||||
<el-checkbox v-model="oauth2.autoRegister" label="开启自动注册将会自动注册账号, 否则需要手动创建账号后再进行绑定" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="onSubmit" :loading="btnLoading">保存</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</el-card>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { onMounted, reactive, ref, toRefs } from 'vue';
|
||||
import { authApi } from '../api';
|
||||
import { ElMessage, FormInstance } from 'element-plus';
|
||||
|
||||
|
||||
const oauth2Form = ref<FormInstance>();
|
||||
|
||||
const state = reactive({
|
||||
oauth2: {
|
||||
clientID: '',
|
||||
clientSecret: '',
|
||||
authorizationURL: '',
|
||||
accessTokenURL: '',
|
||||
resourceURL: '',
|
||||
redirectURL: '',
|
||||
userIdentifier: '',
|
||||
scopes: '',
|
||||
autoRegister: false,
|
||||
},
|
||||
btnLoading: false,
|
||||
});
|
||||
|
||||
|
||||
const { oauth2, btnLoading } = toRefs(state);
|
||||
|
||||
onMounted(async () => {
|
||||
const resp = await authApi.info.request();
|
||||
console.log(resp);
|
||||
if (resp.oauth2) {
|
||||
state.oauth2 = resp.oauth2;
|
||||
}
|
||||
});
|
||||
|
||||
const onSubmit = () => {
|
||||
oauth2Form.value?.validate(async (valid) => {
|
||||
if (valid) {
|
||||
state.btnLoading = true;
|
||||
try {
|
||||
await authApi.saveOAuth2.request(oauth2.value);
|
||||
} catch (e) {
|
||||
}
|
||||
state.btnLoading = false;
|
||||
ElMessage.success('保存成功');
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
<style lang="scss"></style>
|
||||
@@ -29,12 +29,17 @@
|
||||
<el-form v-if="paramsDialog.paramsFormItem.length > 0" ref="paramsFormRef" :model="paramsDialog.params" label-width="auto">
|
||||
<el-form-item v-for="item in paramsDialog.paramsFormItem" :key="item.name" :prop="item.model" :label="item.name" required>
|
||||
<el-input
|
||||
v-if="!item.options"
|
||||
v-if="!item.options && !item.type"
|
||||
v-model="paramsDialog.params[item.model]"
|
||||
:placeholder="item.placeholder"
|
||||
autocomplete="off"
|
||||
clearable
|
||||
></el-input>
|
||||
<el-checkbox v-else-if="item.type == 'checkbox'"
|
||||
v-model="paramsDialog.params[item.model]"
|
||||
autocomplete="off"
|
||||
:label="item.placeholder"
|
||||
clearable/>
|
||||
<el-select
|
||||
v-else
|
||||
v-model="paramsDialog.params[item.model]"
|
||||
|
||||
2
server/.gitignore
vendored
Normal file
2
server/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
static/static
|
||||
config.yml
|
||||
@@ -24,6 +24,11 @@ require (
|
||||
gorm.io/gorm v1.25.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.0
|
||||
golang.org/x/oauth2 v0.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
|
||||
github.com/bytedance/sonic v1.9.1 // indirect
|
||||
@@ -37,6 +42,7 @@ require (
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/golang/snappy v0.0.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
@@ -59,9 +65,10 @@ require (
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/image v0.0.0-20220302094943-723b81ca9867 // indirect
|
||||
golang.org/x/net v0.10.0 // indirect
|
||||
golang.org/x/net v0.12.0 // indirect
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
|
||||
golang.org/x/sys v0.10.0 // indirect
|
||||
golang.org/x/text v0.11.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
google.golang.org/appengine v1.6.7 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
)
|
||||
|
||||
@@ -10,9 +10,9 @@ type AuthCert struct {
|
||||
model.Model
|
||||
|
||||
Name string `json:"name"`
|
||||
AuthMethod int8 `json:"authMethod"` // 1.密码 2.秘钥
|
||||
Password string `json:"password"` // 密码or私钥
|
||||
Passphrase string `json:"passphrase"` // 私钥口令
|
||||
AuthMethod int8 `json:"authMethod"` // 1.密码 2.秘钥
|
||||
Password string `json:"password" gorm:"column:password;type:varchar(4200)"` // 密码or私钥
|
||||
Passphrase string `json:"passphrase"` // 私钥口令
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ type MachineScript struct {
|
||||
Name string `json:"name"`
|
||||
MachineId uint64 `json:"machineId"` // 机器id
|
||||
Type int `json:"type"`
|
||||
Description string `json:"description"` // 脚本描述
|
||||
Params string `json:"params"` // 参数列表json
|
||||
Script string `json:"script"` // 脚本内容
|
||||
Description string `json:"description"` // 脚本描述
|
||||
Params string `json:"params"` // 参数列表json
|
||||
Script string `json:"script" gorm:"column:script;type:text"` // 脚本内容
|
||||
}
|
||||
|
||||
@@ -91,50 +91,59 @@ func (a *Account) Login(rc *req.Ctx) {
|
||||
|
||||
// 默认为不校验otp
|
||||
otpStatus := OtpStatusNone
|
||||
var token string
|
||||
// 访问系统使用的token
|
||||
accessToken := req.CreateToken(account.Id, username)
|
||||
// 若系统配置中设置开启otp双因素校验,则进行otp校验
|
||||
if accountLoginSecurity.UseOtp {
|
||||
account.OtpSecretDecrypt()
|
||||
otpSecret := account.OtpSecret
|
||||
// 修改状态为已注册
|
||||
otpStatus = OtpStatusReg
|
||||
// 该token用于otp双因素校验
|
||||
token = stringx.Rand(32)
|
||||
// 未注册otp secret或重置了秘钥
|
||||
if otpSecret == "" || otpSecret == "-" {
|
||||
otpStatus = OtpStatusNoReg
|
||||
key, err := otp.NewTOTP(otp.GenerateOpts{
|
||||
AccountName: username,
|
||||
Issuer: accountLoginSecurity.OtpIssuer,
|
||||
})
|
||||
biz.ErrIsNilAppendErr(err, "otp生成失败: %s")
|
||||
res["otpUrl"] = key.URL()
|
||||
otpSecret = key.Secret()
|
||||
otpInfo, otpurl, otpToken := useOtp(account, accountLoginSecurity.OtpIssuer, accessToken)
|
||||
otpStatus = otpInfo.OptStatus
|
||||
if otpurl != "" {
|
||||
res["otpUrl"] = otpurl
|
||||
}
|
||||
// 缓存otpInfo, 只有双因素校验通过才可返回真正的accessToken
|
||||
otpInfo := &OtpVerifyInfo{
|
||||
AccountId: account.Id,
|
||||
Username: username,
|
||||
OptStatus: otpStatus,
|
||||
OtpSecret: otpSecret,
|
||||
AccessToken: accessToken,
|
||||
}
|
||||
cache.SetStr(fmt.Sprintf("otp:token:%s", token), jsonx.ToStr(otpInfo), time.Minute*time.Duration(3))
|
||||
accessToken = otpToken
|
||||
} else {
|
||||
// 不进行otp二次校验则直接返回accessToken
|
||||
token = accessToken
|
||||
// 保存登录消息
|
||||
go a.saveLogin(account, getIpAndRegion(rc))
|
||||
go saveLogin(a.AccountApp, a.MsgApp, account, clientIp)
|
||||
}
|
||||
|
||||
// 赋值otp状态
|
||||
res["otp"] = otpStatus
|
||||
res["token"] = token
|
||||
res["token"] = accessToken
|
||||
rc.ResData = res
|
||||
}
|
||||
|
||||
func useOtp(account *entity.Account, otpIssuer, accessToken string) (*OtpVerifyInfo, string, string) {
|
||||
account.OtpSecretDecrypt()
|
||||
otpSecret := account.OtpSecret
|
||||
// 修改状态为已注册
|
||||
otpStatus := OtpStatusReg
|
||||
otpUrl := ""
|
||||
// 该token用于otp双因素校验
|
||||
token := stringx.Rand(32)
|
||||
// 未注册otp secret或重置了秘钥
|
||||
if otpSecret == "" || otpSecret == "-" {
|
||||
otpStatus = OtpStatusNoReg
|
||||
key, err := otp.NewTOTP(otp.GenerateOpts{
|
||||
AccountName: account.Username,
|
||||
Issuer: otpIssuer,
|
||||
})
|
||||
biz.ErrIsNilAppendErr(err, "otp生成失败: %s")
|
||||
otpUrl = key.URL()
|
||||
otpSecret = key.Secret()
|
||||
}
|
||||
// 缓存otpInfo, 只有双因素校验通过才可返回真正的accessToken
|
||||
otpInfo := &OtpVerifyInfo{
|
||||
AccountId: account.Id,
|
||||
Username: account.Username,
|
||||
OptStatus: otpStatus,
|
||||
OtpSecret: otpSecret,
|
||||
AccessToken: accessToken,
|
||||
}
|
||||
cache.SetStr(fmt.Sprintf("otp:token:%s", token), jsonx.ToStr(otpInfo), time.Minute*time.Duration(3))
|
||||
return otpInfo, otpUrl, token
|
||||
}
|
||||
|
||||
// 获取ip与归属地信息
|
||||
func getIpAndRegion(rc *req.Ctx) string {
|
||||
clientIp := rc.GinCtx.ClientIP()
|
||||
@@ -184,7 +193,7 @@ func (a *Account) OtpVerify(rc *req.Ctx) {
|
||||
|
||||
la := &entity.Account{Username: otpInfo.Username}
|
||||
la.Id = accountId
|
||||
go a.saveLogin(la, rc.GinCtx.ClientIP())
|
||||
go saveLogin(a.AccountApp, a.MsgApp, la, getIpAndRegion(rc))
|
||||
|
||||
cache.Del(tokenKey)
|
||||
rc.ResData = accessToken
|
||||
@@ -261,13 +270,13 @@ func CheckPasswordLever(ps string) bool {
|
||||
}
|
||||
|
||||
// 保存更新账号登录信息
|
||||
func (a *Account) saveLogin(account *entity.Account, ip string) {
|
||||
func saveLogin(accountApp application.Account, msgApp msgapp.Msg, account *entity.Account, ip string) {
|
||||
// 更新账号最后登录时间
|
||||
now := time.Now()
|
||||
updateAccount := &entity.Account{LastLoginTime: &now}
|
||||
updateAccount.Id = account.Id
|
||||
updateAccount.LastLoginIp = ip
|
||||
a.AccountApp.Update(updateAccount)
|
||||
accountApp.Update(updateAccount)
|
||||
|
||||
// 创建登录消息
|
||||
loginMsg := &msgentity.Msg{
|
||||
@@ -278,7 +287,7 @@ func (a *Account) saveLogin(account *entity.Account, ip string) {
|
||||
loginMsg.CreateTime = &now
|
||||
loginMsg.Creator = account.Username
|
||||
loginMsg.CreatorId = account.Id
|
||||
a.MsgApp.Create(loginMsg)
|
||||
msgApp.Create(loginMsg)
|
||||
}
|
||||
|
||||
// 获取个人账号信息
|
||||
|
||||
339
server/internal/sys/api/auth.go
Normal file
339
server/internal/sys/api/auth.go
Normal file
@@ -0,0 +1,339 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
"io"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
form2 "mayfly-go/internal/sys/api/form"
|
||||
"mayfly-go/internal/sys/api/vo"
|
||||
"mayfly-go/internal/sys/application"
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/cache"
|
||||
"mayfly-go/pkg/ginx"
|
||||
"mayfly-go/pkg/global"
|
||||
"mayfly-go/pkg/model"
|
||||
"mayfly-go/pkg/req"
|
||||
"mayfly-go/pkg/utils/stringx"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
AuthOAuth2Name string = "OAuth2.0客户端配置"
|
||||
AuthOAuth2Key string = "AuthOAuth2"
|
||||
AuthOAuth2Param string = "[{\"name\":\"Client ID\",\"model\":\"clientID\",\"placeholder\":\"客户端id\"}," +
|
||||
"{\"name\":\"Client Secret\",\"model\":\"clientSecret\",\"placeholder\":\"客户端密钥\"}," +
|
||||
"{\"name\":\"Authorization URL\",\"model\":\"authorizationURL\",\"placeholder\":\"https://example.com/oauth/authorize\"}," +
|
||||
"{\"name\":\"Access Token URL\",\"model\":\"accessTokenURL\",\"placeholder\":\"https://example.com/oauth/token\"}," +
|
||||
"{\"name\":\"Resource URL\",\"model\":\"resourceURL\",\"placeholder\":\"https://example.com/oauth/token\"}," +
|
||||
"{\"name\":\"Redirect URL\",\"model\":\"redirectURL\",\"placeholder\":\"http://mayfly地址/\"}," +
|
||||
"{\"name\":\"User identifier\",\"model\":\"userIdentifier\",\"placeholder\":\"\"}," +
|
||||
"{\"name\":\"Scopes\",\"model\":\"scopes\",\"placeholder\":\"read_user\"}," +
|
||||
"{\"name\":\"自动注册\",\"model\":\"autoRegister\",\"placeholder\":\"开启自动注册将会自动注册账号, 否则需要手动创建账号后再进行绑定\",\"type\":\"checkbox\"}]"
|
||||
AuthOAuth2Remark string = "自定义oauth2.0 server登录"
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
ConfigApp application.Config
|
||||
AuthApp application.Auth
|
||||
AccountApp application.Account
|
||||
MsgApp msgapp.Msg
|
||||
}
|
||||
|
||||
func (a *Auth) OAuth2Login(rc *req.Ctx) {
|
||||
client, _, err := a.getOAuthClient()
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取oauth2 client失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
state := stringx.Rand(32)
|
||||
cache.SetStr("oauth2:state:"+state, "login", 5*time.Minute)
|
||||
rc.GinCtx.Redirect(http.StatusFound, client.AuthCodeURL(state))
|
||||
}
|
||||
|
||||
func (a *Auth) OAuth2Callback(rc *req.Ctx) {
|
||||
client, oauth, err := a.getOAuthClient()
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取oauth2 client失败: "+err.Error())
|
||||
}
|
||||
code := rc.GinCtx.Query("code")
|
||||
if code == "" {
|
||||
biz.ErrIsNil(errors.New("code不能为空"), "code不能为空")
|
||||
}
|
||||
state := rc.GinCtx.Query("state")
|
||||
if state == "" {
|
||||
biz.ErrIsNil(errors.New("state不能为空"), "state不能为空")
|
||||
}
|
||||
stateAction := cache.GetStr("oauth2:state:" + state)
|
||||
if stateAction == "" {
|
||||
biz.ErrIsNil(errors.New("state已过期,请重新登录"), "state已过期,请重新登录")
|
||||
}
|
||||
token, err := client.Exchange(rc.GinCtx, code)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取token失败: "+err.Error())
|
||||
}
|
||||
// 获取用户信息
|
||||
httpCli := client.Client(rc.GinCtx.Request.Context(), token)
|
||||
resp, err := httpCli.Get(oauth.ResourceURL)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取用户信息失败: "+err.Error())
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取用户信息失败: "+err.Error())
|
||||
}
|
||||
userInfo := make(map[string]interface{})
|
||||
err = json.Unmarshal(b, &userInfo)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "解析用户信息失败: "+err.Error())
|
||||
}
|
||||
|
||||
// 获取用户唯一标识
|
||||
keys := strings.Split(oauth.UserIdentifier, ".")
|
||||
var identifier interface{} = userInfo
|
||||
endKey := keys[len(keys)-1]
|
||||
keys = keys[:len(keys)-1]
|
||||
for _, key := range keys {
|
||||
identifier = identifier.(map[string]interface{})[key]
|
||||
}
|
||||
identifier = identifier.(map[string]interface{})[endKey]
|
||||
userId := ""
|
||||
switch identifier.(type) {
|
||||
case string:
|
||||
userId = identifier.(string)
|
||||
case int, int32, int64:
|
||||
userId = fmt.Sprintf("%d", identifier)
|
||||
case float32, float64:
|
||||
userId = fmt.Sprintf("%.0f", identifier.(float64))
|
||||
}
|
||||
// 查询用户是否存在
|
||||
oauthAccount := &entity.OAuthAccount{Identity: userId}
|
||||
err = a.AuthApp.GetOAuthAccount(oauthAccount, "account_id", "identity")
|
||||
// 判断是登录还是绑定
|
||||
if stateAction == "login" {
|
||||
var accountId uint64
|
||||
if err != nil {
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
biz.ErrIsNil(err, "查询用户失败: "+err.Error())
|
||||
}
|
||||
// 不存在,进行注册
|
||||
if !oauth.AutoRegister {
|
||||
biz.ErrIsNil(errors.New("未绑定账号, 请先注册"), "未绑定账号, 请先注册")
|
||||
}
|
||||
now := time.Now()
|
||||
account := &entity.Account{
|
||||
Model: model.Model{
|
||||
CreateTime: &now,
|
||||
CreatorId: 0,
|
||||
Creator: "oauth2",
|
||||
UpdateTime: &now,
|
||||
},
|
||||
Name: userId,
|
||||
Username: userId,
|
||||
}
|
||||
a.AccountApp.Create(account)
|
||||
// 绑定
|
||||
if err := a.AuthApp.BindOAuthAccount(&entity.OAuthAccount{
|
||||
AccountId: account.Id,
|
||||
Identity: oauthAccount.Identity,
|
||||
CreateTime: &now,
|
||||
UpdateTime: &now,
|
||||
}); err != nil {
|
||||
biz.ErrIsNil(err, "绑定用户失败: "+err.Error())
|
||||
}
|
||||
accountId = account.Id
|
||||
} else {
|
||||
accountId = oauthAccount.AccountId
|
||||
}
|
||||
// 进行登录
|
||||
account := &entity.Account{
|
||||
Model: model.Model{DeletedModel: model.DeletedModel{Id: accountId}},
|
||||
}
|
||||
if err := a.AccountApp.GetAccount(account, "Id", "Name", "Username", "Password", "Status", "LastLoginTime", "LastLoginIp", "OtpSecret"); err != nil {
|
||||
biz.ErrIsNil(err, "获取用户信息失败: "+err.Error())
|
||||
}
|
||||
biz.IsTrue(account.IsEnable(), "该账号不可用")
|
||||
// 访问系统使用的token
|
||||
accessToken := req.CreateToken(accountId, account.Username)
|
||||
// 默认为不校验otp
|
||||
otpStatus := OtpStatusNone
|
||||
clientIp := rc.GinCtx.ClientIP()
|
||||
rc.ReqParam = fmt.Sprintf("oauth2 login username: %s | ip: %s", account.Username, clientIp)
|
||||
|
||||
res := map[string]any{
|
||||
"name": account.Name,
|
||||
"username": account.Username,
|
||||
"lastLoginTime": account.LastLoginTime,
|
||||
"lastLoginIp": account.LastLoginIp,
|
||||
}
|
||||
|
||||
accountLoginSecurity := a.ConfigApp.GetConfig(entity.ConfigKeyAccountLoginSecurity).ToAccountLoginSecurity()
|
||||
// 判断otp
|
||||
if accountLoginSecurity.UseOtp {
|
||||
otpInfo, otpurl, otpToken := useOtp(account, accountLoginSecurity.OtpIssuer, accessToken)
|
||||
otpStatus = otpInfo.OptStatus
|
||||
if otpurl != "" {
|
||||
res["otpUrl"] = otpurl
|
||||
}
|
||||
accessToken = otpToken
|
||||
} else {
|
||||
// 保存登录消息
|
||||
go saveLogin(a.AccountApp, a.MsgApp, account, getIpAndRegion(rc))
|
||||
}
|
||||
// 赋值otp状态
|
||||
res["action"] = "oauthLogin"
|
||||
res["otp"] = otpStatus
|
||||
res["token"] = accessToken
|
||||
b, err = json.Marshal(res)
|
||||
biz.ErrIsNil(err, "数据序列化失败")
|
||||
rc.GinCtx.Header("Content-Type", "text/html; charset=utf-8")
|
||||
rc.GinCtx.Writer.WriteHeader(http.StatusOK)
|
||||
_, _ = rc.GinCtx.Writer.WriteString("<html>" +
|
||||
"<script>top.opener.postMessage(" + string(b) + ")</script>" +
|
||||
"</html>")
|
||||
} else if sAccountId, ok := strings.CutPrefix(stateAction, "bind:"); ok {
|
||||
// 绑定
|
||||
accountId, err := strconv.ParseUint(sAccountId, 10, 64)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "绑定用户失败: "+err.Error())
|
||||
}
|
||||
now := time.Now()
|
||||
if err := a.AuthApp.BindOAuthAccount(&entity.OAuthAccount{
|
||||
AccountId: accountId,
|
||||
Identity: oauthAccount.Identity,
|
||||
CreateTime: &now,
|
||||
UpdateTime: &now,
|
||||
}); err != nil {
|
||||
biz.ErrIsNil(err, "绑定用户失败: "+err.Error())
|
||||
}
|
||||
res := map[string]any{
|
||||
"action": "oauthBind",
|
||||
"bind": true,
|
||||
}
|
||||
b, err = json.Marshal(res)
|
||||
biz.ErrIsNil(err, "数据序列化失败")
|
||||
rc.GinCtx.Header("Content-Type", "text/html; charset=utf-8")
|
||||
rc.GinCtx.Writer.WriteHeader(http.StatusOK)
|
||||
_, _ = rc.GinCtx.Writer.WriteString("<html>" +
|
||||
"<script>top.opener.postMessage(" + string(b) + ")</script>" +
|
||||
"</html>")
|
||||
} else {
|
||||
biz.ErrIsNil(errors.New("state不合法"), "state不合法")
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Auth) getOAuthClient() (*oauth2.Config, *vo.OAuth2VO, error) {
|
||||
config := a.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
oauth2Vo := &vo.OAuth2VO{}
|
||||
if config.Value != "" {
|
||||
if err := json.Unmarshal([]byte(config.Value), oauth2Vo); err != nil {
|
||||
global.Log.Warnf("解析自定义oauth2配置失败,err:%s", err.Error())
|
||||
return nil, nil, errors.New("解析自定义oauth2配置失败")
|
||||
}
|
||||
}
|
||||
if oauth2Vo.ClientID == "" {
|
||||
biz.ErrIsNil(nil, "请先配置oauth2")
|
||||
return nil, nil, errors.New("请先配置oauth2")
|
||||
}
|
||||
client := &oauth2.Config{
|
||||
ClientID: oauth2Vo.ClientID,
|
||||
ClientSecret: oauth2Vo.ClientSecret,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: oauth2Vo.AuthorizationURL,
|
||||
TokenURL: oauth2Vo.AccessTokenURL,
|
||||
},
|
||||
RedirectURL: oauth2Vo.RedirectURL + "api/sys/auth/oauth2/callback",
|
||||
Scopes: strings.Split(oauth2Vo.Scopes, ","),
|
||||
}
|
||||
return client, oauth2Vo, nil
|
||||
}
|
||||
|
||||
// GetInfo 获取认证平台信息
|
||||
func (a *Auth) GetInfo(rc *req.Ctx) {
|
||||
config := a.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
oauth2 := &vo.OAuth2VO{}
|
||||
if config.Value != "" {
|
||||
if err := json.Unmarshal([]byte(config.Value), oauth2); err != nil {
|
||||
global.Log.Warnf("解析自定义oauth2配置失败,err:%s", err.Error())
|
||||
biz.ErrIsNil(err, "解析自定义oauth2配置失败")
|
||||
}
|
||||
}
|
||||
rc.ResData = &vo.AuthVO{
|
||||
OAuth2VO: oauth2,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Auth) SaveOAuth2(rc *req.Ctx) {
|
||||
form := &form2.OAuth2Form{}
|
||||
form = ginx.BindJsonAndValid(rc.GinCtx, form)
|
||||
rc.ReqParam = form
|
||||
// 先获取看看有没有
|
||||
config := a.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
now := time.Now()
|
||||
if config.Id == 0 {
|
||||
config.CreatorId = rc.LoginAccount.Id
|
||||
config.Creator = rc.LoginAccount.Username
|
||||
config.CreateTime = &now
|
||||
}
|
||||
config.ModifierId = rc.LoginAccount.Id
|
||||
config.Modifier = rc.LoginAccount.Username
|
||||
config.UpdateTime = &now
|
||||
config.Name = AuthOAuth2Name
|
||||
config.Key = AuthOAuth2Key
|
||||
config.Params = AuthOAuth2Param
|
||||
b, err := json.Marshal(form)
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "json marshal error")
|
||||
return
|
||||
}
|
||||
config.Value = string(b)
|
||||
config.Remark = AuthOAuth2Remark
|
||||
a.ConfigApp.Save(config)
|
||||
}
|
||||
|
||||
func (a *Auth) OAuth2Bind(rc *req.Ctx) {
|
||||
client, _, err := a.getOAuthClient()
|
||||
if err != nil {
|
||||
biz.ErrIsNil(err, "获取oauth2 client失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
state := stringx.Rand(32)
|
||||
cache.SetStr("oauth2:state:"+state, "bind:"+strconv.FormatUint(rc.LoginAccount.Id, 10),
|
||||
5*time.Minute)
|
||||
rc.GinCtx.Redirect(http.StatusFound, client.AuthCodeURL(state))
|
||||
}
|
||||
|
||||
func (a *Auth) Auth2Status(ctx *req.Ctx) {
|
||||
res := &vo.AuthStatusVO{}
|
||||
config := a.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
if config.Value != "" {
|
||||
oauth2 := &vo.OAuth2VO{}
|
||||
if err := json.Unmarshal([]byte(config.Value), oauth2); err != nil {
|
||||
global.Log.Warnf("解析自定义oauth2配置失败,err:%s", err.Error())
|
||||
biz.ErrIsNil(err, "解析自定义oauth2配置失败")
|
||||
} else if oauth2.ClientID != "" {
|
||||
res.Enable.OAuth2 = true
|
||||
}
|
||||
}
|
||||
if res.Enable.OAuth2 {
|
||||
err := a.AuthApp.GetOAuthAccount(&entity.OAuthAccount{
|
||||
AccountId: ctx.LoginAccount.Id,
|
||||
}, "account_id", "identity")
|
||||
if err != nil {
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
biz.ErrIsNil(err, "查询用户失败: "+err.Error())
|
||||
}
|
||||
} else {
|
||||
res.Bind.OAuth2 = true
|
||||
}
|
||||
}
|
||||
ctx.ResData = res
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"mayfly-go/internal/sys/api/form"
|
||||
"mayfly-go/internal/sys/api/vo"
|
||||
"mayfly-go/internal/sys/application"
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/biz"
|
||||
"mayfly-go/pkg/ginx"
|
||||
"mayfly-go/pkg/global"
|
||||
"mayfly-go/pkg/req"
|
||||
)
|
||||
|
||||
@@ -25,6 +28,21 @@ func (c *Config) GetConfigValueByKey(rc *req.Ctx) {
|
||||
rc.ResData = c.ConfigApp.GetConfig(key).Value
|
||||
}
|
||||
|
||||
func (c *Config) GetConfigValueByKeyWithNoToken(keys []string) func(rc *req.Ctx) {
|
||||
keyMap := make(map[string]struct{})
|
||||
for _, key := range keys {
|
||||
keyMap[key] = struct{}{}
|
||||
}
|
||||
return func(rc *req.Ctx) {
|
||||
key := rc.GinCtx.Query("key")
|
||||
biz.NotEmpty(key, "key不能为空")
|
||||
if _, ok := keyMap[key]; !ok {
|
||||
biz.ErrIsNil(nil, "无权限获取该配置信息")
|
||||
}
|
||||
rc.ResData = c.ConfigApp.GetConfig(key).Value
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) SaveConfig(rc *req.Ctx) {
|
||||
form := &form.ConfigForm{}
|
||||
config := ginx.BindJsonAndCopyTo(rc.GinCtx, form, new(entity.Config))
|
||||
@@ -32,3 +50,19 @@ func (c *Config) SaveConfig(rc *req.Ctx) {
|
||||
config.SetBaseInfo(rc.LoginAccount)
|
||||
c.ConfigApp.Save(config)
|
||||
}
|
||||
|
||||
// AuthConfig auth相关配置
|
||||
func (c *Config) AuthConfig(rc *req.Ctx) {
|
||||
resp := &vo.Auth2EnableVO{}
|
||||
config := c.ConfigApp.GetConfig(AuthOAuth2Key)
|
||||
oauth2 := &vo.OAuth2VO{}
|
||||
if config.Value != "" {
|
||||
if err := json.Unmarshal([]byte(config.Value), oauth2); err != nil {
|
||||
global.Log.Warnf("解析自定义oauth2配置失败,err:%s", err.Error())
|
||||
biz.ErrIsNil(err, "解析自定义oauth2配置失败")
|
||||
} else if oauth2.ClientID != "" {
|
||||
resp.OAuth2 = true
|
||||
}
|
||||
}
|
||||
rc.ResData = resp
|
||||
}
|
||||
|
||||
13
server/internal/sys/api/form/auth.go
Normal file
13
server/internal/sys/api/form/auth.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package form
|
||||
|
||||
type OAuth2Form struct {
|
||||
ClientID string `json:"clientID" binding:"required"`
|
||||
ClientSecret string `json:"clientSecret" binding:"required"`
|
||||
AuthorizationURL string `json:"authorizationURL" binding:"required,url"`
|
||||
AccessTokenURL string `json:"accessTokenURL" binding:"required,url"`
|
||||
ResourceURL string `json:"resourceURL" binding:"required,url"`
|
||||
RedirectURL string `json:"redirectURL" binding:"required,url"`
|
||||
UserIdentifier string `json:"userIdentifier" binding:"required"`
|
||||
Scopes string `json:"scopes"`
|
||||
AutoRegister bool `json:"autoRegister"`
|
||||
}
|
||||
26
server/internal/sys/api/vo/auth.go
Normal file
26
server/internal/sys/api/vo/auth.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package vo
|
||||
|
||||
type OAuth2VO struct {
|
||||
ClientID string `json:"clientID"`
|
||||
ClientSecret string `json:"clientSecret"`
|
||||
AuthorizationURL string `json:"authorizationURL"`
|
||||
AccessTokenURL string `json:"accessTokenURL"`
|
||||
ResourceURL string `json:"resourceURL"`
|
||||
RedirectURL string `json:"redirectURL"`
|
||||
UserIdentifier string `json:"userIdentifier"`
|
||||
Scopes string `json:"scopes"`
|
||||
AutoRegister bool `json:"autoRegister"`
|
||||
}
|
||||
|
||||
type AuthVO struct {
|
||||
*OAuth2VO `json:"oauth2"`
|
||||
}
|
||||
|
||||
type Auth2EnableVO struct {
|
||||
OAuth2 bool `json:"oauth2"`
|
||||
}
|
||||
|
||||
type AuthStatusVO struct {
|
||||
Enable Auth2EnableVO `json:"enable"`
|
||||
Bind Auth2EnableVO `json:"bind"`
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
var (
|
||||
accountApp = newAccountApp(persistence.GetAccountRepo())
|
||||
authApp = newAuthApp(persistence.GetOAuthAccountRepo())
|
||||
configApp = newConfigApp(persistence.GetConfigRepo())
|
||||
resourceApp = newResourceApp(persistence.GetResourceRepo())
|
||||
roleApp = newRoleApp(persistence.GetRoleRepo())
|
||||
@@ -16,6 +17,10 @@ func GetAccountApp() Account {
|
||||
return accountApp
|
||||
}
|
||||
|
||||
func GetAuthApp() Auth {
|
||||
return authApp
|
||||
}
|
||||
|
||||
func GetConfigApp() Config {
|
||||
return configApp
|
||||
}
|
||||
|
||||
29
server/internal/sys/application/auth.go
Normal file
29
server/internal/sys/application/auth.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/internal/sys/domain/repository"
|
||||
)
|
||||
|
||||
type Auth interface {
|
||||
GetOAuthAccount(condition *entity.OAuthAccount, cols ...string) error
|
||||
BindOAuthAccount(e *entity.OAuthAccount) error
|
||||
}
|
||||
|
||||
func newAuthApp(oauthAccountRepo repository.OAuthAccount) Auth {
|
||||
return &authAppImpl{
|
||||
oauthAccountRepo: oauthAccountRepo,
|
||||
}
|
||||
}
|
||||
|
||||
type authAppImpl struct {
|
||||
oauthAccountRepo repository.OAuthAccount
|
||||
}
|
||||
|
||||
func (a *authAppImpl) GetOAuthAccount(condition *entity.OAuthAccount, cols ...string) error {
|
||||
return a.oauthAccountRepo.GetOAuthAccount(condition, cols...)
|
||||
}
|
||||
|
||||
func (a *authAppImpl) BindOAuthAccount(e *entity.OAuthAccount) error {
|
||||
return a.oauthAccountRepo.SaveOAuthAccount(e)
|
||||
}
|
||||
@@ -17,7 +17,7 @@ type Config interface {
|
||||
|
||||
Save(config *entity.Config)
|
||||
|
||||
// 获取指定key的配置信息, 不会返回nil, 若不存在则值都默认值即空字符串
|
||||
// GetConfig 获取指定key的配置信息, 不会返回nil, 若不存在则值都默认值即空字符串
|
||||
GetConfig(key string) *entity.Config
|
||||
}
|
||||
|
||||
|
||||
20
server/internal/sys/domain/entity/auth.go
Normal file
20
server/internal/sys/domain/entity/auth.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"mayfly-go/pkg/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
type OAuthAccount struct {
|
||||
model.DeletedModel
|
||||
|
||||
AccountId uint64 `json:"accountId" gorm:"column:account_id;index:account_id,unique"`
|
||||
Identity string `json:"identity" gorm:"column:identity;index:identity,unique"`
|
||||
|
||||
CreateTime *time.Time `json:"createTime"`
|
||||
UpdateTime *time.Time `json:"updateTime"`
|
||||
}
|
||||
|
||||
func (OAuthAccount) TableName() string {
|
||||
return "t_oauth_account"
|
||||
}
|
||||
@@ -12,14 +12,15 @@ const (
|
||||
ConfigKeyUseLoginOtp string = "UseLoginOtp" // 是否开启otp双因素校验
|
||||
ConfigKeyDbQueryMaxCount string = "DbQueryMaxCount" // 数据库查询的最大数量
|
||||
ConfigKeyDbSaveQuerySQL string = "DbSaveQuerySQL" // 数据库是否记录查询相关sql
|
||||
ConfigUseWartermark string = "UseWartermark" // 是否使用水印
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
model.Model
|
||||
Name string `json:"name"` // 配置名
|
||||
Key string `json:"key"` // 配置key
|
||||
Params string `json:"params"`
|
||||
Value string `json:"value"`
|
||||
Params string `json:"params" gorm:"column:params;type:varchar(1000)"`
|
||||
Value string `json:"value" gorm:"column:value;type:varchar(1000)"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ import "mayfly-go/pkg/model"
|
||||
type Resource struct {
|
||||
model.Model
|
||||
Pid int `json:"pid"`
|
||||
UiPath string // 唯一标识路径
|
||||
Type int8 `json:"type"` // 1:菜单路由;2:资源(按钮等)
|
||||
Status int8 `json:"status"` // 1:可用;-1:不可用
|
||||
UiPath string `json:"ui_path"` // 唯一标识路径
|
||||
Type int8 `json:"type"` // 1:菜单路由;2:资源(按钮等)
|
||||
Status int8 `json:"status"` // 1:可用;-1:不可用
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Weight int `json:"weight"`
|
||||
|
||||
@@ -15,8 +15,8 @@ type SysLog struct {
|
||||
|
||||
Type int8 `json:"type"`
|
||||
Description string `json:"description"`
|
||||
ReqParam string `json:"reqParam"` // 请求参数
|
||||
Resp string `json:"resp"` // 响应结构
|
||||
ReqParam string `json:"reqParam" gorm:"column:req_param;type:varchar(1000)"` // 请求参数
|
||||
Resp string `json:"resp" gorm:"column:resp;type:varchar(1000)"` // 响应结构
|
||||
}
|
||||
|
||||
func (a *SysLog) TableName() string {
|
||||
|
||||
10
server/internal/sys/domain/repository/auth.go
Normal file
10
server/internal/sys/domain/repository/auth.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package repository
|
||||
|
||||
import "mayfly-go/internal/sys/domain/entity"
|
||||
|
||||
type OAuthAccount interface {
|
||||
// GetOAuthAccount 根据identity获取第三方账号信息
|
||||
GetOAuthAccount(condition *entity.OAuthAccount, cols ...string) error
|
||||
|
||||
SaveOAuthAccount(e *entity.OAuthAccount) error
|
||||
}
|
||||
24
server/internal/sys/infrastructure/persistence/auth.go
Normal file
24
server/internal/sys/infrastructure/persistence/auth.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/internal/sys/domain/repository"
|
||||
"mayfly-go/pkg/gormx"
|
||||
)
|
||||
|
||||
type authAccountRepoImpl struct{}
|
||||
|
||||
func newAuthAccountRepo() repository.OAuthAccount {
|
||||
return new(authAccountRepoImpl)
|
||||
}
|
||||
|
||||
func (a *authAccountRepoImpl) GetOAuthAccount(condition *entity.OAuthAccount, cols ...string) error {
|
||||
return gormx.GetBy(condition, cols...)
|
||||
}
|
||||
|
||||
func (a *authAccountRepoImpl) SaveOAuthAccount(e *entity.OAuthAccount) error {
|
||||
if e.Id == 0 {
|
||||
return gormx.Insert(e)
|
||||
}
|
||||
return gormx.UpdateById(e)
|
||||
}
|
||||
@@ -3,17 +3,22 @@ package persistence
|
||||
import "mayfly-go/internal/sys/domain/repository"
|
||||
|
||||
var (
|
||||
accountRepo = newAccountRepo()
|
||||
configRepo = newConfigRepo()
|
||||
resourceRepo = newResourceRepo()
|
||||
roleRepo = newRoleRepo()
|
||||
syslogRepo = newSyslogRepo()
|
||||
accountRepo = newAccountRepo()
|
||||
authAccountRepo = newAuthAccountRepo()
|
||||
configRepo = newConfigRepo()
|
||||
resourceRepo = newResourceRepo()
|
||||
roleRepo = newRoleRepo()
|
||||
syslogRepo = newSyslogRepo()
|
||||
)
|
||||
|
||||
func GetAccountRepo() repository.Account {
|
||||
return accountRepo
|
||||
}
|
||||
|
||||
func GetOAuthAccountRepo() repository.OAuthAccount {
|
||||
return authAccountRepo
|
||||
}
|
||||
|
||||
func GetConfigRepo() repository.Config {
|
||||
return configRepo
|
||||
}
|
||||
|
||||
35
server/internal/sys/router/auth.go
Normal file
35
server/internal/sys/router/auth.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
msgapp "mayfly-go/internal/msg/application"
|
||||
"mayfly-go/internal/sys/api"
|
||||
"mayfly-go/internal/sys/application"
|
||||
"mayfly-go/pkg/req"
|
||||
)
|
||||
|
||||
func InitSysAuthRouter(router *gin.RouterGroup) {
|
||||
r := &api.Auth{
|
||||
ConfigApp: application.GetConfigApp(),
|
||||
AuthApp: application.GetAuthApp(),
|
||||
AccountApp: application.GetAccountApp(),
|
||||
MsgApp: msgapp.GetMsgApp(),
|
||||
}
|
||||
rg := router.Group("sys/auth")
|
||||
|
||||
baseP := req.NewPermission("system:auth:base")
|
||||
|
||||
reqs := [...]*req.Conf{
|
||||
req.NewGet("", r.GetInfo).RequiredPermission(baseP),
|
||||
|
||||
req.NewPut("/oauth2", r.SaveOAuth2).RequiredPermission(baseP),
|
||||
|
||||
req.NewGet("/status", r.Auth2Status),
|
||||
req.NewGet("/oauth2/bind", r.OAuth2Bind),
|
||||
|
||||
req.NewGet("/oauth2/login", r.OAuth2Login).DontNeedToken(),
|
||||
req.NewGet("/oauth2/callback", r.OAuth2Callback).NoRes().DontNeedToken(),
|
||||
}
|
||||
|
||||
req.BatchSetGroup(rg, reqs[:])
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package router
|
||||
import (
|
||||
"mayfly-go/internal/sys/api"
|
||||
"mayfly-go/internal/sys/application"
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/req"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -18,9 +19,17 @@ func InitSysConfigRouter(router *gin.RouterGroup) {
|
||||
req.NewGet("", r.Configs).RequiredPermission(baseP),
|
||||
|
||||
// 获取指定配置key对应的值
|
||||
req.NewGet("/value", r.GetConfigValueByKey).DontNeedToken(),
|
||||
req.NewGet("/value", r.GetConfigValueByKeyWithNoToken([]string{
|
||||
entity.ConfigKeyAccountLoginSecurity,
|
||||
entity.ConfigKeyDbQueryMaxCount,
|
||||
entity.ConfigKeyDbSaveQuerySQL,
|
||||
entity.ConfigUseWartermark,
|
||||
})).DontNeedToken(),
|
||||
|
||||
req.NewPost("", r.SaveConfig).Log(req.NewLogSave("保存系统配置信息")).RequiredPermissionCode("config:save"),
|
||||
req.NewGet("/auth", r.AuthConfig).DontNeedToken(),
|
||||
|
||||
req.NewPost("", r.SaveConfig).Log(req.NewLogSave("保存系统配置信息")).
|
||||
RequiredPermissionCode("config:save"),
|
||||
}
|
||||
|
||||
req.BatchSetGroup(configG, reqs[:])
|
||||
|
||||
@@ -10,4 +10,5 @@ func Init(router *gin.RouterGroup) {
|
||||
InitSystemRouter(router)
|
||||
InitSyslogRouter(router)
|
||||
InitSysConfigRouter(router)
|
||||
InitSysAuthRouter(router)
|
||||
}
|
||||
|
||||
107
server/migrations/2022.go
Normal file
107
server/migrations/2022.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
entity2 "mayfly-go/internal/db/domain/entity"
|
||||
"mayfly-go/internal/machine/domain/entity"
|
||||
entity3 "mayfly-go/internal/mongo/domain/entity"
|
||||
entity6 "mayfly-go/internal/msg/domain/entity"
|
||||
entity4 "mayfly-go/internal/redis/domain/entity"
|
||||
entity5 "mayfly-go/internal/sys/domain/entity"
|
||||
entity7 "mayfly-go/internal/tag/domain/entity"
|
||||
)
|
||||
|
||||
// T2022 TODO 在此之前的数据库表结构初始化, 目前先使用mayfly-go.sql文件初始化数据库结构
|
||||
func T2022() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "2022",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
if err := tx.AutoMigrate(&entity.AuthCert{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity.Machine{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity.MachineFile{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity.MachineMonitor{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity.MachineScript{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity.MachineCronJob{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity.MachineCronJobExec{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity.MachineCronJobRelate{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.AutoMigrate(&entity2.Db{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity2.DbSql{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity2.DbSqlExec{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.AutoMigrate(&entity3.Mongo{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.AutoMigrate(&entity4.Redis{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.AutoMigrate(&entity5.Account{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity5.AccountRole{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity5.Config{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity5.SysLog{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity5.Resource{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity5.Role{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity5.RoleResource{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.AutoMigrate(&entity6.Msg{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity7.TagTree{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity7.TagTreeTeam{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity7.Team{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.AutoMigrate(&entity7.TeamMember{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
80
server/migrations/20230720.go
Normal file
80
server/migrations/20230720.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
"mayfly-go/internal/sys/api"
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/model"
|
||||
"time"
|
||||
)
|
||||
|
||||
// T20230720 三方登录表
|
||||
func T20230720() *gormigrate.Migration {
|
||||
return &gormigrate.Migration{
|
||||
ID: "20230319",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
// 添加路由权限
|
||||
res := &entity.Resource{
|
||||
Model: model.Model{
|
||||
DeletedModel: model.DeletedModel{Id: 133},
|
||||
},
|
||||
Pid: 4,
|
||||
UiPath: "sys/auth",
|
||||
Type: 1,
|
||||
Status: 1,
|
||||
Code: "system:auth",
|
||||
Name: "登录认证",
|
||||
Weight: 10000001,
|
||||
Meta: "{\"component\":\"system/auth/AuthInfo\"," +
|
||||
"\"icon\":\"User\",\"isKeepAlive\":true," +
|
||||
"\"routeName\":\"AuthInfo\"}",
|
||||
}
|
||||
if err := insertResource(tx, res); err != nil {
|
||||
return err
|
||||
}
|
||||
res = &entity.Resource{
|
||||
Model: model.Model{
|
||||
DeletedModel: model.DeletedModel{Id: 134},
|
||||
},
|
||||
Pid: 133,
|
||||
UiPath: "sys/auth/base",
|
||||
Type: 2,
|
||||
Status: 1,
|
||||
Code: "system:auth:base",
|
||||
Name: "基本权限",
|
||||
Weight: 10000000,
|
||||
Meta: "null",
|
||||
}
|
||||
if err := insertResource(tx, res); err != nil {
|
||||
return err
|
||||
}
|
||||
// 加大params字段长度
|
||||
now := time.Now()
|
||||
if err := tx.AutoMigrate(&entity.Config{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Save(&entity.Config{
|
||||
Model: model.Model{
|
||||
CreateTime: &now,
|
||||
CreatorId: 1,
|
||||
Creator: "admin",
|
||||
UpdateTime: &now,
|
||||
ModifierId: 1,
|
||||
Modifier: "admin",
|
||||
},
|
||||
Name: api.AuthOAuth2Name,
|
||||
Key: api.AuthOAuth2Key,
|
||||
Params: api.AuthOAuth2Param,
|
||||
Value: "{}",
|
||||
Remark: api.AuthOAuth2Remark,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.AutoMigrate(&entity.OAuthAccount{})
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
68
server/migrations/init.go
Normal file
68
server/migrations/init.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
"mayfly-go/internal/sys/domain/entity"
|
||||
"mayfly-go/pkg/model"
|
||||
"mayfly-go/pkg/rediscli"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RunMigrations 数据库迁移操作
|
||||
func RunMigrations(db *gorm.DB) error {
|
||||
// 添加分布式锁, 防止多个服务同时执行迁移
|
||||
if rediscli.GetCli() != nil {
|
||||
if ok, err := rediscli.GetCli().
|
||||
SetNX(context.Background(), "migrations", "lock", time.Minute).Result(); err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
return nil
|
||||
}
|
||||
defer rediscli.Del("migrations")
|
||||
}
|
||||
return run(db,
|
||||
T2022,
|
||||
T20230720,
|
||||
)
|
||||
}
|
||||
|
||||
func run(db *gorm.DB, fs ...func() *gormigrate.Migration) error {
|
||||
var ms []*gormigrate.Migration
|
||||
for _, f := range fs {
|
||||
ms = append(ms, f())
|
||||
}
|
||||
m := gormigrate.New(db, &gormigrate.Options{
|
||||
TableName: "migrations",
|
||||
IDColumnName: "id",
|
||||
IDColumnSize: 200,
|
||||
UseTransaction: true,
|
||||
ValidateUnknownMigrations: true,
|
||||
}, ms)
|
||||
if err := m.Migrate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insertResource(tx *gorm.DB, res *entity.Resource) error {
|
||||
now := time.Now()
|
||||
res.CreateTime = &now
|
||||
res.CreatorId = 1
|
||||
res.Creator = "admin"
|
||||
res.UpdateTime = &now
|
||||
res.ModifierId = 1
|
||||
res.Modifier = "admin"
|
||||
if err := tx.Save(res).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Save(&entity.RoleResource{
|
||||
DeletedModel: model.DeletedModel{},
|
||||
RoleId: 1,
|
||||
ResourceId: res.Id,
|
||||
CreateTime: &now,
|
||||
CreatorId: 1,
|
||||
Creator: "admin",
|
||||
}).Error
|
||||
}
|
||||
@@ -35,7 +35,7 @@ func GetByIdIn(model any, list any, ids []uint64, orderBy ...string) {
|
||||
// 若 error不为nil,则为不存在该记录
|
||||
// @param model 数据库映射实体模型
|
||||
func GetBy(model any, cols ...string) error {
|
||||
return global.Db.Select(cols).Where(model).Scopes(UndeleteScope).First(model).Error
|
||||
return global.Db.Debug().Select(cols).Where(model).Scopes(UndeleteScope).First(model).Error
|
||||
}
|
||||
|
||||
// 根据model指定条件统计数量
|
||||
|
||||
@@ -15,7 +15,7 @@ const (
|
||||
// 含有删除字段模型
|
||||
type DeletedModel struct {
|
||||
Id uint64 `json:"id"`
|
||||
IsDeleted int8 `json:"-"`
|
||||
IsDeleted int8 `json:"-" gorm:"column:is_deleted;default:0"`
|
||||
DeleteTime *time.Time `json:"-"`
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package starter
|
||||
|
||||
import (
|
||||
"mayfly-go/migrations"
|
||||
"mayfly-go/initialize"
|
||||
"mayfly-go/pkg/config"
|
||||
"mayfly-go/pkg/global"
|
||||
"mayfly-go/pkg/logger"
|
||||
"mayfly-go/pkg/req"
|
||||
)
|
||||
@@ -25,6 +27,10 @@ func RunWebServer() {
|
||||
|
||||
// 有配置redis信息,则初始化redis。多台机器部署需要使用redis存储验证码、权限、公私钥等
|
||||
initRedis()
|
||||
// 数据库升级操作
|
||||
if err := migrations.RunMigrations(global.Db); err != nil {
|
||||
logger.Log.Fatalf("数据库升级失败: %v", err)
|
||||
}
|
||||
|
||||
// 初始化其他需要启动时运行的方法
|
||||
initialize.InitOther()
|
||||
|
||||
Reference in New Issue
Block a user