wip: oauth2登录和oauth2 otp登录验证

This commit is contained in:
王一之
2023-07-21 21:18:31 +08:00
parent 179b58e557
commit 513f8ea012
21 changed files with 507 additions and 123 deletions

View File

@@ -6,6 +6,7 @@ export default {
changePwd: (param: any) => request.post('/sys/accounts/change-pwd', param), changePwd: (param: any) => request.post('/sys/accounts/change-pwd', param),
getPublicKey: () => request.get('/common/public-key'), getPublicKey: () => request.get('/common/public-key'),
getConfigValue: (params: any) => request.get('/sys/configs/value', params), getConfigValue: (params: any) => request.get('/sys/configs/value', params),
oauthConfig: () => request.get('/sys/configs/auth'),
captcha: () => request.get('/sys/captcha'), captcha: () => request.get('/sys/captcha'),
logout: () => request.post('/sys/accounts/logout/{token}'), logout: () => request.post('/sys/accounts/logout/{token}'),
getPermissions: () => request.get('/sys/accounts/permissions'), getPermissions: () => request.get('/sys/accounts/permissions'),

View File

@@ -2,37 +2,24 @@
<div> <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> <el-input type="text" placeholder="请输入用户名" prefix-icon="user" v-model="loginForm.username" clearable
autocomplete="off"> </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"
type="password" autocomplete="off" @keyup.enter="login" show-password>
placeholder="请输入密码"
prefix-icon="lock"
v-model="loginForm.password"
autocomplete="off"
@keyup.enter="login"
show-password
>
</el-input> </el-input>
</el-form-item> </el-form-item>
<el-form-item v-if="accountLoginSecurity.useCaptcha" prop="captcha"> <el-form-item v-if="accountLoginSecurity.useCaptcha" prop="captcha">
<el-row :gutter="15"> <el-row :gutter="15">
<el-col :span="16"> <el-col :span="16">
<el-input <el-input type="text" maxlength="6" placeholder="请输入验证码" prefix-icon="position"
type="text" v-model="loginForm.captcha" clearable autocomplete="off" @keyup.enter="login"></el-input>
maxlength="6"
placeholder="请输入验证码"
prefix-icon="position"
v-model="loginForm.captcha"
clearable
autocomplete="off"
@keyup.enter="login"
></el-input>
</el-col> </el-col>
<el-col :span="8"> <el-col :span="8">
<div class="login-content-code"> <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> </div>
</el-col> </el-col>
</el-row> </el-row>
@@ -47,21 +34,19 @@
</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-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 :model="changePwdDialog.form" :rules="changePwdDialog.rules" ref="changePwdFormRef" label-width="auto">
<el-form-item prop="username" label="用户名" required> <el-form-item prop="username" label="用户名" required>
<el-input v-model.trim="changePwdDialog.form.username" disabled></el-input> <el-input v-model.trim="changePwdDialog.form.username" disabled></el-input>
</el-form-item> </el-form-item>
<el-form-item prop="oldPassword" label="旧密码" required> <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>
<el-form-item prop="newPassword" label="新密码" required> <el-form-item prop="newPassword" label="新密码" required>
<el-input <el-input v-model.trim="changePwdDialog.form.newPassword" placeholder="须为8位以上且包含字⺟⼤⼩写+数字+特殊符号"
v-model.trim="changePwdDialog.form.newPassword" type="password" autocomplete="new-password"></el-input>
placeholder="须为8位以上且包含字⺟⼤⼩写+数字+特殊符号"
type="password"
autocomplete="new-password"
></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
@@ -73,28 +58,17 @@
</template> </template>
</el-dialog> </el-dialog>
<el-dialog <el-dialog title="OTP校验" v-model="otpDialog.visible" @close="loading.signIn = false" :close-on-click-modal="false"
title="OTP校验" width="350px" :destroy-on-close="true">
v-model="otpDialog.visible" <el-form ref="otpFormRef" :model="otpDialog.form" :rules="otpDialog.rules" @submit.native.prevent
@close="loading.signIn = false" label-width="auto">
: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="二维码"> <el-form-item v-if="otpDialog.otpUrl" label="二维码">
<qrcode-vue :value="otpDialog.otpUrl" :size="200" level="H" /> <qrcode-vue :value="otpDialog.otpUrl" :size="200" level="H" />
</el-form-item> </el-form-item>
<el-form-item prop="code" label="OTP" required> <el-form-item prop="code" label="OTP" required>
<el-input <el-input style="width: 220px" ref="otpCodeInputRef" v-model.trim="otpDialog.form.code" clearable
style="width: 220px" @keyup.enter="otpVerify" placeholder="请输入令牌APP中显示的授权码"></el-input>
ref="otpCodeInputRef"
v-model.trim="otpDialog.form.code"
clearable
@keyup.enter="otpVerify"
placeholder="请输入令牌APP中显示的授权码"
></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
@@ -265,10 +239,14 @@ const onSignIn = async () => {
return; return;
} }
state.showLoginFailTips = false; state.showLoginFailTips = false;
loginResDeal(loginRes);
}
const loginResDeal = (loginRes: any) => {
// 用户信息 // 用户信息
const userInfos = { const userInfos = {
name: loginRes.name, name: loginRes.name,
username: state.loginForm.username, username: loginRes.username,
// 头像 // 头像
photo: letterAvatar(state.loginForm.username), photo: letterAvatar(state.loginForm.username),
time: new Date().getTime(), time: new Date().getTime(),
@@ -297,6 +275,10 @@ const onSignIn = async () => {
}, 400); }, 400);
}; };
defineExpose({
loginResDeal
});
// 登录成功后的跳转 // 登录成功后的跳转
const signInSuccess = async (accessToken: string = '') => { const signInSuccess = async (accessToken: string = '') => {
// 存储 token 到浏览器缓存 // 存储 token 到浏览器缓存

View File

@@ -9,7 +9,7 @@
<el-tabs v-model="tabsActiveName" @tab-click="onTabsClick"> <el-tabs v-model="tabsActiveName" @tab-click="onTabsClick">
<el-tab-pane label="账号密码登录" name="account" :disabled="tabsActiveName === 'account'"> <el-tab-pane label="账号密码登录" name="account" :disabled="tabsActiveName === 'account'">
<transition name="el-zoom-in-center"> <transition name="el-zoom-in-center">
<Account v-show="isTabPaneShow" /> <Account v-show="isTabPaneShow" ref="loginForm" />
</transition> </transition>
</el-tab-pane> </el-tab-pane>
<!-- <el-tab-pane label="手机号登录" name="mobile" :disabled="tabsActiveName === 'mobile'"> <!-- <el-tab-pane label="手机号登录" name="mobile" :disabled="tabsActiveName === 'mobile'">
@@ -18,10 +18,19 @@
</transition> </transition>
</el-tab-pane> --> </el-tab-pane> -->
</el-tabs> </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>
<el-button type="text" size="small">友情链接</el-button> <!-- <el-button type="text" size="small">友情链接</el-button> -->
</div> --> </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> </div>
<!-- <div class="login-copyright"> <!-- <div class="login-copyright">
@@ -32,23 +41,58 @@
</template> </template>
<script lang="ts" setup> <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 Account from '@/views/login/component/AccountLogin.vue';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { useThemeConfig } from '@/store/themeConfig'; import { useThemeConfig } from '@/store/themeConfig';
import openApi from '@/common/openApi';
import config from '@/common/config';
const { themeConfig } = storeToRefs(useThemeConfig()); const { themeConfig } = storeToRefs(useThemeConfig());
const state = reactive({ const state = reactive({
tabsActiveName: 'account', tabsActiveName: 'account',
isTabPaneShow: true, 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 = () => { const onTabsClick = () => {
state.isTabPaneShow = !state.isTabPaneShow; 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> </script>
<style scoped lang="scss"> <style scoped lang="scss">

View File

@@ -12,8 +12,8 @@
</div> </div>
<div class="personal-user-right"> <div class="personal-user-right">
<el-row> <el-row>
<el-col :span="24" class="personal-title mb18" <el-col :span="24" class="personal-title mb18">{{ currentTime }}{{ userInfo.name
>{{ currentTime }}{{ userInfo.name }}生活变的再糟糕也不妨碍我变得更好 }}生活变的再糟糕也不妨碍我变得更好
</el-col> </el-col>
<el-col :span="24"> <el-col :span="24">
<el-row> <el-row>
@@ -77,16 +77,9 @@
</el-table-column> </el-table-column>
</el-table> </el-table>
<el-row type="flex" class="mt5" justify="center"> <el-row type="flex" class="mt5" justify="center">
<el-pagination <el-pagination small @current-change="getMsgs" style="text-align: center" background
small layout="prev, pager, next, total, jumper" :total="msgDialog.msgs.total"
@current-change="getMsgs" v-model:current-page="msgDialog.query.pageNum" :page-size="msgDialog.query.pageSize" />
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-row>
</el-dialog> </el-dialog>
@@ -115,7 +108,8 @@
<el-row :gutter="35"> <el-row :gutter="35">
<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20"> <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20">
<el-form-item label="密码"> <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-form-item>
</el-col> </el-col>
<!-- --> <!-- -->
@@ -160,18 +154,18 @@
<el-button type="text">立即设置</el-button> <el-button type="text">立即设置</el-button>
</div> </div>
</div> </div>
</div> </div> -->
<div class="personal-edit-safe-box"> <div class="personal-edit-safe-box">
<div class="personal-edit-safe-item"> <div class="personal-edit-safe-item">
<div class="personal-edit-safe-item-left"> <div class="personal-edit-safe-item-left">
<div class="personal-edit-safe-item-left-label">绑定QQ</div> <div class="personal-edit-safe-item-left-label">绑定OAuth2</div>
<div class="personal-edit-safe-item-left-value">已绑定QQ110****566</div> <div class="personal-edit-safe-item-left-value">已绑定OAuth2</div>
</div> </div>
<div class="personal-edit-safe-item-right"> <div class="personal-edit-safe-item-right">
<el-button type="text">立即设置</el-button> <el-button type="text">立即绑定</el-button>
</div> </div>
</div> </div>
</div> --> </div>
</el-card> </el-card>
</el-col> </el-col>
</el-row> </el-row>

View File

@@ -22,22 +22,28 @@
</el-form-item> </el-form-item>
<el-form-item prop="authorizationURL" label="Authorization URL" required> <el-form-item prop="authorizationURL" label="Authorization URL" required>
<el-input v-model="oauth2.authorizationURL" <el-input v-model="oauth2.authorizationURL"
placeholder="https://example.com/oauth/authorize"></el-input> placeholder="授权码获取地址 例如: https://example.com/oauth/authorize"></el-input>
</el-form-item> </el-form-item>
<el-form-item prop="accessTokenURL" label="Access token URL" required> <el-form-item prop="accessTokenURL" label="Access token URL" required>
<el-input v-model="oauth2.accessTokenURL" placeholder="https://example.com/oauth/token"></el-input> <el-input v-model="oauth2.accessTokenURL"
placeholder="访问token获取地址 例如: https://example.com/oauth/token"></el-input>
</el-form-item> </el-form-item>
<el-form-item prop="resourceURL" label="Resource URL" required> <el-form-item prop="resourceURL" label="Resource URL" required>
<el-input v-model="oauth2.resourceURL" placeholder="https://example.com/user"></el-input> <el-input v-model="oauth2.resourceURL"
placeholder="获取用户信息地址 例如: https://example.com/api/v4/user"></el-input>
</el-form-item> </el-form-item>
<el-form-item prop="redirectURL" label="Redirect URL" required> <el-form-item prop="redirectURL" label="Redirect URL" required>
<el-input v-model="oauth2.redirectURL" placeholder="http://mayfly地址/"></el-input> <el-input v-model="oauth2.redirectURL" placeholder="mayfly地址 例如: http://localhost:8889/"></el-input>
</el-form-item> </el-form-item>
<el-form-item prop="userIdentifier" label="User identifier" required> <el-form-item prop="userIdentifier" label="User identifier" required>
<el-input v-model="oauth2.userIdentifier" placeholder=""></el-input> <el-input v-model="oauth2.userIdentifier"
placeholder="用户唯一标识key 例如:username,如果有多层可以写为: data.username"></el-input>
</el-form-item> </el-form-item>
<el-form-item prop="scopes" label="Scopes" required> <el-form-item prop="scopes" label="Scopes" required>
<el-input v-model="oauth2.scopes" placeholder=""></el-input> <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-form-item> <el-form-item>
<el-button type="primary" @click="onSubmit" :loading="btnLoading">保存</el-button> <el-button type="primary" @click="onSubmit" :loading="btnLoading">保存</el-button>
@@ -50,7 +56,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, reactive, ref, toRefs } from 'vue'; import { onMounted, reactive, ref, toRefs } from 'vue';
import { authApi } from '../api'; import { authApi } from '../api';
import { FormInstance } from 'element-plus'; import { ElMessage, FormInstance } from 'element-plus';
const oauth2Form = ref<FormInstance>(); const oauth2Form = ref<FormInstance>();
@@ -65,6 +71,7 @@ const state = reactive({
redirectURL: '', redirectURL: '',
userIdentifier: '', userIdentifier: '',
scopes: '', scopes: '',
autoRegister: false,
}, },
btnLoading: false, btnLoading: false,
}); });
@@ -89,6 +96,7 @@ const onSubmit = () => {
} catch (e) { } catch (e) {
} }
state.btnLoading = false; state.btnLoading = false;
ElMessage.success('保存成功');
} }
}) })
} }

View File

@@ -29,12 +29,17 @@
<el-form v-if="paramsDialog.paramsFormItem.length > 0" ref="paramsFormRef" :model="paramsDialog.params" label-width="auto"> <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-form-item v-for="item in paramsDialog.paramsFormItem" :key="item.name" :prop="item.model" :label="item.name" required>
<el-input <el-input
v-if="!item.options" v-if="!item.options && !item.type"
v-model="paramsDialog.params[item.model]" v-model="paramsDialog.params[item.model]"
:placeholder="item.placeholder" :placeholder="item.placeholder"
autocomplete="off" autocomplete="off"
clearable clearable
></el-input> ></el-input>
<el-checkbox v-else-if="item.type == 'checkbox'"
v-model="paramsDialog.params[item.model]"
autocomplete="off"
:label="item.placeholder"
clearable/>
<el-select <el-select
v-else v-else
v-model="paramsDialog.params[item.model]" v-model="paramsDialog.params[item.model]"

View File

@@ -91,50 +91,59 @@ func (a *Account) Login(rc *req.Ctx) {
// 默认为不校验otp // 默认为不校验otp
otpStatus := OtpStatusNone otpStatus := OtpStatusNone
var token string
// 访问系统使用的token // 访问系统使用的token
accessToken := req.CreateToken(account.Id, username) accessToken := req.CreateToken(account.Id, username)
// 若系统配置中设置开启otp双因素校验则进行otp校验 // 若系统配置中设置开启otp双因素校验则进行otp校验
if accountLoginSecurity.UseOtp { if accountLoginSecurity.UseOtp {
account.OtpSecretDecrypt() otpInfo, otpurl, otpToken := useOtp(account, accountLoginSecurity.OtpIssuer, accessToken)
otpSecret := account.OtpSecret otpStatus = otpInfo.OptStatus
// 修改状态为已注册 if otpurl != "" {
otpStatus = OtpStatusReg res["otpUrl"] = otpurl
// 该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, 只有双因素校验通过才可返回真正的accessToken accessToken = otpToken
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))
} else { } else {
// 不进行otp二次校验则直接返回accessToken // 不进行otp二次校验则直接返回accessToken
token = accessToken
// 保存登录消息 // 保存登录消息
go a.saveLogin(account, getIpAndRegion(rc)) go saveLogin(a.AccountApp, a.MsgApp, account, clientIp)
} }
// 赋值otp状态 // 赋值otp状态
res["otp"] = otpStatus res["otp"] = otpStatus
res["token"] = token res["token"] = accessToken
rc.ResData = res 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 := utils.RandString(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), utils.ToJsonStr(otpInfo), time.Minute*time.Duration(3))
return otpInfo, otpUrl, token
}
// 获取ip与归属地信息 // 获取ip与归属地信息
func getIpAndRegion(rc *req.Ctx) string { func getIpAndRegion(rc *req.Ctx) string {
clientIp := rc.GinCtx.ClientIP() clientIp := rc.GinCtx.ClientIP()
@@ -184,7 +193,7 @@ func (a *Account) OtpVerify(rc *req.Ctx) {
la := &entity.Account{Username: otpInfo.Username} la := &entity.Account{Username: otpInfo.Username}
la.Id = accountId la.Id = accountId
go a.saveLogin(la, rc.GinCtx.ClientIP()) go saveLogin(a.AccountApp, a.MsgApp, la, rc.GinCtx.ClientIP())
cache.Del(tokenKey) cache.Del(tokenKey)
rc.ResData = accessToken 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() now := time.Now()
updateAccount := &entity.Account{LastLoginTime: &now} updateAccount := &entity.Account{LastLoginTime: &now}
updateAccount.Id = account.Id updateAccount.Id = account.Id
updateAccount.LastLoginIp = ip updateAccount.LastLoginIp = ip
a.AccountApp.Update(updateAccount) accountApp.Update(updateAccount)
// 创建登录消息 // 创建登录消息
loginMsg := &msgentity.Msg{ loginMsg := &msgentity.Msg{
@@ -278,7 +287,7 @@ func (a *Account) saveLogin(account *entity.Account, ip string) {
loginMsg.CreateTime = &now loginMsg.CreateTime = &now
loginMsg.Creator = account.Username loginMsg.Creator = account.Username
loginMsg.CreatorId = account.Id loginMsg.CreatorId = account.Id
a.MsgApp.Create(loginMsg) msgApp.Create(loginMsg)
} }
// 获取个人账号信息 // 获取个人账号信息

View File

@@ -2,13 +2,25 @@ package api
import ( import (
"encoding/json" "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" form2 "mayfly-go/internal/sys/api/form"
"mayfly-go/internal/sys/api/vo" "mayfly-go/internal/sys/api/vo"
"mayfly-go/internal/sys/application" "mayfly-go/internal/sys/application"
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/pkg/biz" "mayfly-go/pkg/biz"
"mayfly-go/pkg/cache"
"mayfly-go/pkg/ginx" "mayfly-go/pkg/ginx"
"mayfly-go/pkg/global" "mayfly-go/pkg/global"
"mayfly-go/pkg/model"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"mayfly-go/pkg/utils"
"net/http"
"strings"
"time" "time"
) )
@@ -22,12 +34,193 @@ const (
"{\"name\":\"Resource URL\",\"model\":\"resourceURL\",\"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\":\"Redirect URL\",\"model\":\"redirectURL\",\"placeholder\":\"http://mayfly地址/\"}," +
"{\"name\":\"User identifier\",\"model\":\"userIdentifier\",\"placeholder\":\"\"}," + "{\"name\":\"User identifier\",\"model\":\"userIdentifier\",\"placeholder\":\"\"}," +
"{\"name\":\"Scopes\",\"model\":\"scopes\",\"placeholder\":\"read_user\"}]" "{\"name\":\"Scopes\",\"model\":\"scopes\",\"placeholder\":\"read_user\"}," +
"{\"name\":\"自动注册\",\"model\":\"autoRegister\",\"placeholder\":\"开启自动注册将会自动注册账号, 否则需要手动创建账号后再进行绑定\",\"type\":\"checkbox\"}]"
AuthOAuth2Remark string = "自定义oauth2.0 server登录" AuthOAuth2Remark string = "自定义oauth2.0 server登录"
) )
type Auth struct { type Auth struct {
ConfigApp application.Config 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 := utils.RandString(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不能为空")
}
if cache.GetStr("oauth2:state:"+state) == "" {
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")
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{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, rc.GinCtx.ClientIP())
}
// 赋值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>")
}
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 获取认证平台信息 // GetInfo 获取认证平台信息

View File

@@ -1,11 +1,14 @@
package api package api
import ( import (
"encoding/json"
"mayfly-go/internal/sys/api/form" "mayfly-go/internal/sys/api/form"
"mayfly-go/internal/sys/api/vo"
"mayfly-go/internal/sys/application" "mayfly-go/internal/sys/application"
"mayfly-go/internal/sys/domain/entity" "mayfly-go/internal/sys/domain/entity"
"mayfly-go/pkg/biz" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ginx" "mayfly-go/pkg/ginx"
"mayfly-go/pkg/global"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
) )
@@ -25,6 +28,21 @@ func (c *Config) GetConfigValueByKey(rc *req.Ctx) {
rc.ResData = c.ConfigApp.GetConfig(key).Value 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) { func (c *Config) SaveConfig(rc *req.Ctx) {
form := &form.ConfigForm{} form := &form.ConfigForm{}
config := ginx.BindJsonAndCopyTo(rc.GinCtx, form, new(entity.Config)) config := ginx.BindJsonAndCopyTo(rc.GinCtx, form, new(entity.Config))
@@ -32,3 +50,19 @@ func (c *Config) SaveConfig(rc *req.Ctx) {
config.SetBaseInfo(rc.LoginAccount) config.SetBaseInfo(rc.LoginAccount)
c.ConfigApp.Save(config) c.ConfigApp.Save(config)
} }
// AuthConfig auth相关配置
func (c *Config) AuthConfig(rc *req.Ctx) {
resp := &vo.OAuth2EnableVO{}
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
}

View File

@@ -9,4 +9,5 @@ type OAuth2Form struct {
RedirectURL string `json:"redirectURL" binding:"required,url"` RedirectURL string `json:"redirectURL" binding:"required,url"`
UserIdentifier string `json:"userIdentifier" binding:"required"` UserIdentifier string `json:"userIdentifier" binding:"required"`
Scopes string `json:"scopes"` Scopes string `json:"scopes"`
AutoRegister bool `json:"autoRegister"`
} }

View File

@@ -9,8 +9,13 @@ type OAuth2VO struct {
RedirectURL string `json:"redirectURL"` RedirectURL string `json:"redirectURL"`
UserIdentifier string `json:"userIdentifier"` UserIdentifier string `json:"userIdentifier"`
Scopes string `json:"scopes"` Scopes string `json:"scopes"`
AutoRegister bool `json:"autoRegister"`
} }
type AuthVO struct { type AuthVO struct {
*OAuth2VO `json:"oauth2"` *OAuth2VO `json:"oauth2"`
} }
type OAuth2EnableVO struct {
OAuth2 bool `json:"oauth2"`
}

View File

@@ -6,6 +6,7 @@ import (
var ( var (
accountApp = newAccountApp(persistence.GetAccountRepo()) accountApp = newAccountApp(persistence.GetAccountRepo())
authApp = newAuthApp(persistence.GetOAuthAccountRepo())
configApp = newConfigApp(persistence.GetConfigRepo()) configApp = newConfigApp(persistence.GetConfigRepo())
resourceApp = newResourceApp(persistence.GetResourceRepo()) resourceApp = newResourceApp(persistence.GetResourceRepo())
roleApp = newRoleApp(persistence.GetRoleRepo()) roleApp = newRoleApp(persistence.GetRoleRepo())
@@ -16,6 +17,10 @@ func GetAccountApp() Account {
return accountApp return accountApp
} }
func GetAuthApp() Auth {
return authApp
}
func GetConfigApp() Config { func GetConfigApp() Config {
return configApp return configApp
} }

View 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)
}

View File

@@ -0,0 +1,17 @@
package entity
import "time"
type OAuthAccount struct {
Id uint64 `json:"id"`
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"
}

View File

@@ -12,6 +12,7 @@ const (
ConfigKeyUseLoginOtp string = "UseLoginOtp" // 是否开启otp双因素校验 ConfigKeyUseLoginOtp string = "UseLoginOtp" // 是否开启otp双因素校验
ConfigKeyDbQueryMaxCount string = "DbQueryMaxCount" // 数据库查询的最大数量 ConfigKeyDbQueryMaxCount string = "DbQueryMaxCount" // 数据库查询的最大数量
ConfigKeyDbSaveQuerySQL string = "DbSaveQuerySQL" // 数据库是否记录查询相关sql ConfigKeyDbSaveQuerySQL string = "DbSaveQuerySQL" // 数据库是否记录查询相关sql
ConfigUseWartermark string = "UseWartermark" // 是否使用水印
) )
type Config struct { type Config struct {

View 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
}

View 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)
}

View File

@@ -3,17 +3,22 @@ package persistence
import "mayfly-go/internal/sys/domain/repository" import "mayfly-go/internal/sys/domain/repository"
var ( var (
accountRepo = newAccountRepo() accountRepo = newAccountRepo()
configRepo = newConfigRepo() authAccountRepo = newAuthAccountRepo()
resourceRepo = newResourceRepo() configRepo = newConfigRepo()
roleRepo = newRoleRepo() resourceRepo = newResourceRepo()
syslogRepo = newSyslogRepo() roleRepo = newRoleRepo()
syslogRepo = newSyslogRepo()
) )
func GetAccountRepo() repository.Account { func GetAccountRepo() repository.Account {
return accountRepo return accountRepo
} }
func GetOAuthAccountRepo() repository.OAuthAccount {
return authAccountRepo
}
func GetConfigRepo() repository.Config { func GetConfigRepo() repository.Config {
return configRepo return configRepo
} }

View File

@@ -2,6 +2,7 @@ package router
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
msgapp "mayfly-go/internal/msg/application"
"mayfly-go/internal/sys/api" "mayfly-go/internal/sys/api"
"mayfly-go/internal/sys/application" "mayfly-go/internal/sys/application"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
@@ -9,7 +10,10 @@ import (
func InitSysAuthRouter(router *gin.RouterGroup) { func InitSysAuthRouter(router *gin.RouterGroup) {
r := &api.Auth{ r := &api.Auth{
ConfigApp: application.GetConfigApp(), ConfigApp: application.GetConfigApp(),
AuthApp: application.GetAuthApp(),
AccountApp: application.GetAccountApp(),
MsgApp: msgapp.GetMsgApp(),
} }
rg := router.Group("sys/auth") rg := router.Group("sys/auth")
@@ -17,7 +21,11 @@ func InitSysAuthRouter(router *gin.RouterGroup) {
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
req.NewGet("", r.GetInfo).RequiredPermission(baseP), req.NewGet("", r.GetInfo).RequiredPermission(baseP),
req.NewPut("/oauth2", r.SaveOAuth2).RequiredPermission(baseP), req.NewPut("/oauth2", r.SaveOAuth2).RequiredPermission(baseP),
req.NewGet("/oauth2/login", r.OAuth2Login).DontNeedToken(),
req.NewGet("/oauth2/callback", r.OAuth2Callback).NoRes().DontNeedToken(),
} }
req.BatchSetGroup(rg, reqs[:]) req.BatchSetGroup(rg, reqs[:])

View File

@@ -3,6 +3,7 @@ package router
import ( import (
"mayfly-go/internal/sys/api" "mayfly-go/internal/sys/api"
"mayfly-go/internal/sys/application" "mayfly-go/internal/sys/application"
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -18,9 +19,17 @@ func InitSysConfigRouter(router *gin.RouterGroup) {
req.NewGet("", r.Configs).RequiredPermission(baseP), req.NewGet("", r.Configs).RequiredPermission(baseP),
// 获取指定配置key对应的值 // 获取指定配置key对应的值
req.NewGet("/value", r.GetConfigValueByKey).RequiredPermission(baseP), 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[:]) req.BatchSetGroup(configG, reqs[:])

View File

@@ -84,7 +84,7 @@ func T20230720() *gormigrate.Migration {
}).Error; err != nil { }).Error; err != nil {
return err return err
} }
return nil return tx.AutoMigrate(&entity.OAuthAccount{})
}, },
Rollback: func(tx *gorm.DB) error { Rollback: func(tx *gorm.DB) error {
return nil return nil