feat: chat auth (#3285)

This commit is contained in:
shaohuzhang1 2025-06-17 20:26:20 +08:00 committed by GitHub
parent fbc37edf3c
commit 35433b4752
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 132 additions and 198 deletions

View File

@ -1,4 +1,4 @@
import {Result} from '@/request/Result'
import { Result } from '@/request/Result'
import {
get,
post,
@ -9,16 +9,16 @@ import {
download,
exportFile,
} from '@/request/chat/index'
import {type ChatProfile} from '@/api/type/chat'
import {type Ref} from 'vue'
import { type ChatProfile } from '@/api/type/chat'
import { type Ref } from 'vue'
import useStore from '@/stores'
import type {LoginRequest} from "@/api/type/user.ts";
import type { LoginRequest } from '@/api/type/user'
const prefix: any = {_value: '/workspace/'}
const prefix: any = { _value: '/workspace/' }
Object.defineProperty(prefix, 'value', {
get: function () {
const {user} = useStore()
const { user } = useStore()
return this._value + user.getWorkspaceId() + '/application'
},
})
@ -31,7 +31,6 @@ Object.defineProperty(prefix, 'value', {
*/
const open: (loading?: Ref<boolean>) => Promise<Result<string>> = (loading) => {
return get('/open', {}, loading)
}
/**
*
@ -46,7 +45,7 @@ const chatProfile: (assessToken: string, loading?: Ref<boolean>) => Promise<Resu
assessToken,
loading,
) => {
return get('/profile', {access_token: assessToken}, loading)
return get('/profile', { access_token: assessToken }, loading)
}
/**
*
@ -58,7 +57,7 @@ const anonymousAuthentication: (
assessToken: string,
loading?: Ref<boolean>,
) => Promise<Result<any>> = (assessToken, loading) => {
return post('/auth/anonymous', {access_token: assessToken}, {}, loading)
return post('/auth/anonymous', { access_token: assessToken }, {}, loading)
}
/**
*
@ -69,30 +68,28 @@ const applicationProfile: (loading?: Ref<boolean>) => Promise<Result<any>> = (lo
return get('/application/profile', {}, loading)
}
/**
*
* @param request
* @param loading
* @returns
*/
const login: (accessToken: string, request: LoginRequest, loading?: Ref<boolean>) => Promise<Result<any>> = (
const login: (
accessToken: string,
request,
loading,
) => {
request: LoginRequest,
loading?: Ref<boolean>,
) => Promise<Result<any>> = (accessToken: string, request, loading) => {
return post('/auth/login/' + accessToken, request, undefined, loading)
}
const ldapLogin: (accessToken: string, request: LoginRequest, loading?: Ref<boolean>) => Promise<Result<any>> = (
const ldapLogin: (
accessToken: string,
request,
loading,
) => {
request: LoginRequest,
loading?: Ref<boolean>,
) => Promise<Result<any>> = (accessToken: string, request, loading) => {
return post('/auth/ldap/login/' + accessToken, request, undefined, loading)
}
/**
*
* @param loading
@ -114,35 +111,38 @@ const getQrSource: (loading?: Ref<boolean>) => Promise<Result<any>> = (loading)
const getDingCallback: (code: string, loading?: Ref<boolean>) => Promise<Result<any>> = (
code,
loading
loading,
) => {
return get('dingtalk', {code}, loading)
return get('dingtalk', { code }, loading)
}
const getDingOauth2Callback: (code: string, loading?: Ref<boolean>) => Promise<Result<any>> = (
code,
loading
loading,
) => {
return get('dingtalk/oauth2', {code}, loading)
return get('dingtalk/oauth2', { code }, loading)
}
const getWecomCallback: (code: string, loading?: Ref<boolean>) => Promise<Result<any>> = (
code,
loading
loading,
) => {
return get('wecom', {code}, loading)
return get('wecom', { code }, loading)
}
const getLarkCallback: (code: string, loading?: Ref<boolean>) => Promise<Result<any>> = (
code,
loading
loading,
) => {
return get('lark/oauth2', {code}, loading)
return get('lark/oauth2', { code }, loading)
}
/**
*
*/
const getAuthSetting: (auth_type: string, loading?: Ref<boolean>) => Promise<Result<any>> = (auth_type, loading) => {
const getAuthSetting: (auth_type: string, loading?: Ref<boolean>) => Promise<Result<any>> = (
auth_type,
loading,
) => {
return get(`/chat_user/${auth_type}/detail`, undefined, loading)
}
export default {
@ -160,5 +160,5 @@ export default {
getLarkCallback,
getQrSource,
ldapLogin,
getAuthSetting
getAuthSetting,
}

View File

@ -53,19 +53,6 @@ instance.interceptors.response.use(
MsgError(err.message)
console.error(err)
}
if (err.response?.status === 401) {
const { chatUser } = useStore()
if (chatUser.accessToken) {
router.push({ name: 'login', params: { accessToken: chatUser.accessToken } })
} else {
router.push('/404 ')
}
}
if (err.response?.status === 403 && !err.response.config.url.includes('chat/open')) {
MsgError(
err.response.data && err.response.data.message ? err.response.data.message : '没有权限访问',
)
}
return Promise.reject(err)
},
)

View File

@ -33,7 +33,15 @@ router.beforeEach(
})
return
}
const authentication = await chatUser.isAuthentication()
let authentication = false
try {
authentication = await chatUser.isAuthentication()
} catch (e: any) {
next({
path: '/404',
})
return
}
const token = chatUser.getToken()
if (authentication) {
if (!token && to.name != 'login') {
@ -45,22 +53,46 @@ router.beforeEach(
})
return
} else {
next()
return
if (to.name == 'login') {
next()
return
} else {
try {
await chatUser.applicationProfile()
} catch (e: any) {
if (e.response?.status === 401) {
next({
name: 'login',
params: {
accessToken: to.params.accessToken,
},
})
}
return
}
next()
return
}
}
} else {
await chatUser.anonymousAuthentication()
}
if (!chatUser.application) {
await chatUser.applicationProfile()
}
// 判断是否有菜单权限
if (to.meta.permission ? hasPermission(to.meta.permission as any, 'OR') : true) {
next()
} else {
// 如果没有权限则直接取404页面
next('404')
try {
await chatUser.applicationProfile()
} catch (e: any) {
if (e.response?.status === 401) {
next({
name: 'login',
params: {
accessToken: to.params.accessToken,
},
})
}
return
}
}
next()
},
)
router.afterEach(() => {

View File

@ -1,7 +1,8 @@
import { defineStore } from 'pinia'
import ChatAPI from '@/api/chat/chat'
import { type ChatProfile } from '@/api/type/chat'
import type { LoginRequest } from '@/api/type/user'
import type { Ref } from 'vue'
interface ChatUser {
// 用户id
id: string
@ -59,12 +60,29 @@ const useChatUserStore = defineStore('chat-user', {
}
return localStorage.getItem(`accessToken`)
},
setToken(token: string) {
this.token = token
sessionStorage.setItem(`${this.accessToken}-accessToken`, token)
localStorage.setItem(`${this.accessToken}-accessToken`, token)
},
/**
*
*/
anonymousAuthentication() {
return ChatAPI.anonymousAuthentication(this.accessToken as string).then((ok) => {
this.token = ok.data
this.setToken(ok.data)
return this.token
})
},
login(request: LoginRequest, loading?: Ref<boolean>) {
return ChatAPI.login(this.accessToken as string, request, loading).then((ok) => {
this.setToken(ok.data.token)
return this.token
})
},
ldapLogin(request: LoginRequest, loading?: Ref<boolean>) {
return ChatAPI.ldapLogin(this.accessToken as string, request, loading).then((ok) => {
this.setToken(ok.data.token)
return this.token
})
},

View File

@ -2,7 +2,8 @@
<UserLoginLayout v-if="!loading" v-loading="loading">
<LoginContainer :subTitle="theme.themeInfo?.slogan || $t('theme.defaultSlogan')">
<h2 class="mb-24" v-if="!showQrCodeTab">
{{ loginMode == 'LOCAL' ? $t('views.login.title') : loginMode }}</h2>
{{ loginMode == 'LOCAL' ? $t('views.login.title') : loginMode }}
</h2>
<div v-if="!showQrCodeTab">
<el-form
class="login-form"
@ -80,7 +81,7 @@
</div>
</div>
<div v-if="showQrCodeTab">
<QrCodeTab :tabs="orgOptions"/>
<QrCodeTab :tabs="orgOptions" />
</div>
<div class="login-gradient-divider lighter mt-24" v-if="modeList.length > 1">
<span>{{ $t('views.login.moreMethod') }}</span>
@ -99,7 +100,7 @@
'font-size': item === 'OAUTH2' ? '8px' : '10px',
color: user.themeInfo?.theme,
}"
>{{ item }}</span
>{{ item }}</span
>
</el-button>
<el-button
@ -109,7 +110,7 @@
class="login-button-circle color-secondary"
@click="changeMode('QR_CODE')"
>
<img src="@/assets/scan/icon_qr_outlined.svg" width="25px"/>
<img src="@/assets/scan/icon_qr_outlined.svg" width="25px" />
</el-button>
<el-button
v-if="item === 'LOCAL' && loginMode != 'LOCAL'"
@ -126,30 +127,28 @@
</UserLoginLayout>
</template>
<script setup lang="ts">
import {onMounted, ref, onBeforeMount} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import type {FormInstance, FormRules} from 'element-plus'
import type {LoginRequest} from '@/api/type/login'
import { onMounted, ref, onBeforeMount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import type { LoginRequest } from '@/api/type/login'
import LoginContainer from '@/layout/login-layout/LoginContainer.vue'
import UserLoginLayout from '@/layout/login-layout/UserLoginLayout.vue'
import loginApi from '@/api/chat/chat.ts'
import {t, getBrowserLang} from '@/locales'
import { t, getBrowserLang } from '@/locales'
import useStore from '@/stores'
import {useI18n} from 'vue-i18n'
import { useI18n } from 'vue-i18n'
import QrCodeTab from '@/views/login/scanCompinents/QrCodeTab.vue'
import {MsgConfirm, MsgError} from '@/utils/message.ts'
import useUserStore from "@/stores/modules/user.ts";
// import * as dd from 'dingtalk-jsapi'
// import {loadScript} from '@/utils/utils'
import { MsgConfirm, MsgError } from '@/utils/message.ts'
import useUserStore from '@/stores/modules/user.ts'
const router = useRouter()
const {login, user, theme, chatUser} = useStore()
const {locale} = useI18n({useScope: 'global'})
const { login, user, theme, chatUser } = useStore()
const { locale } = useI18n({ useScope: 'global' })
const loading = ref<boolean>(false)
const route = useRoute()
const identifyCode = ref<string>('')
const {
params: {accessToken}
params: { accessToken },
} = route as any
const loginFormRef = ref<FormInstance>()
const loginForm = ref<LoginRequest>({
@ -185,16 +184,12 @@ const rules = ref<FormRules<LoginRequest>>({
const loginHandle = () => {
loginFormRef.value?.validate().then(() => {
if (loginMode.value === 'LDAP') {
loginApi.ldapLogin(accessToken, loginForm.value,).then((ok) => {
localStorage.setItem('token', ok?.data?.token)
const user = useUserStore()
return user.profile(loading)
chatUser.ldapLogin(loginForm.value).then((ok) => {
router.push({ name: 'chat', params: { accessToken: chatUser.accessToken } })
})
} else {
loginApi.login(accessToken, loginForm.value,).then((ok) => {
localStorage.setItem('token', ok?.data?.token)
const user = useUserStore()
return user.profile(loading)
chatUser.login(loginForm.value).then((ok) => {
router.push({ name: 'chat', params: { accessToken: chatUser.accessToken } })
})
}
})
@ -236,31 +231,32 @@ function redirectAuth(authType: string, needMessage: boolean = false) {
}
loginApi.getAuthSetting(authType, loading).then((res: any) => {
if (!res.data || !res.data.config) {
return;
return
}
const config = res.data.config;
const redirectUrl = eval(`\`${config.redirectUrl}/${accessToken}\``);
let url;
const config = res.data.config
const redirectUrl = eval(`\`${config.redirectUrl}/${accessToken}\``)
let url
if (authType === 'CAS') {
url = config.ldpUri;
url += url.indexOf('?') !== -1
? `&service=${encodeURIComponent(redirectUrl)}`
: `?service=${encodeURIComponent(redirectUrl)}`;
url = config.ldpUri
url +=
url.indexOf('?') !== -1
? `&service=${encodeURIComponent(redirectUrl)}`
: `?service=${encodeURIComponent(redirectUrl)}`
} else if (authType === 'OIDC') {
const scope = config.scope || 'openid+profile+email';
url = `${config.authEndpoint}?client_id=${config.clientId}&redirect_uri=${redirectUrl}&response_type=code&scope=${scope}`;
const scope = config.scope || 'openid+profile+email'
url = `${config.authEndpoint}?client_id=${config.clientId}&redirect_uri=${redirectUrl}&response_type=code&scope=${scope}`
if (config.state) {
url += `&state=${config.state}`;
url += `&state=${config.state}`
}
} else if (authType === 'OAuth2') {
url = `${config.authEndpoint}?client_id=${config.clientId}&response_type=code&redirect_uri=${redirectUrl}&state=${uuidv4()}`;
url = `${config.authEndpoint}?client_id=${config.clientId}&response_type=code&redirect_uri=${redirectUrl}&state=${uuidv4()}`
if (config.scope) {
url += `&scope=${config.scope}`;
url += `&scope=${config.scope}`
}
}
if (!url) {
return;
return
}
if (needMessage) {
MsgConfirm(t('views.login.jump_tip'), '', {
@ -269,15 +265,14 @@ function redirectAuth(authType: string, needMessage: boolean = false) {
confirmButtonClass: '',
})
.then(() => {
window.location.href = url;
window.location.href = url
})
.catch(() => {
});
.catch(() => {})
} else {
console.log('url', url);
window.location.href = url;
console.log('url', url)
window.location.href = url
}
});
})
}
function changeMode(val: string) {
@ -305,105 +300,7 @@ onBeforeMount(() => {
redirectAuth(modeList.value[0])
}
}
// user
// .getQrType()
// .then((res) => {
// if (res.length > 0) {
// modeList.value = ['QR_CODE', ...modeList.value]
// QrList.value = res
// QrList.value.forEach((item) => {
// orgOptions.value.push({
// key: item,
// value:
// item === 'wecom'
// ? t('views.system.authentication.scanTheQRCode.wecom')
// : item === 'dingtalk'
// ? t('views.system.authentication.scanTheQRCode.dingtalk')
// : t('views.system.authentication.scanTheQRCode.lark'),
// })
// })
// }
// })
// .finally(() => (loading.value = false))
})
//declare const window: any
// onMounted(() => {
// makeCode()
// const route = useRoute()
// const currentUrl = ref(route.fullPath)
// const params = new URLSearchParams(currentUrl.value.split('?')[1])
// const client = params.get('client')
//
// const handleDingTalk = () => {
// const code = params.get('corpId')
// if (code) {
// dd.runtime.permission.requestAuthCode({corpId: code}).then((res) => {
// console.log('DingTalk client request success:', res)
// user.dingOauth2Callback(res.code).then(() => {
// router.push({name: 'home'})
// })
// })
// }
// }
//
// const handleLark = () => {
// const appId = params.get('appId')
// const callRequestAuthCode = () => {
// window.tt?.requestAuthCode({
// appId: appId,
// success: (res: any) => {
// user.larkCallback(res.code).then(() => {
// router.push({name: 'home'})
// })
// },
// fail: (error: any) => {
// MsgError(error)
// },
// })
// }
//
// loadScript('https://lf-scm-cn.feishucdn.com/lark/op/h5-js-sdk-1.5.35.js', {
// jsId: 'lark-sdk',
// forceReload: true,
// })
// .then(() => {
// if (window.tt) {
// window.tt.requestAccess({
// appID: appId,
// scopeList: [],
// success: (res: any) => {
// user.larkCallback(res.code).then(() => {
// router.push({name: 'home'})
// })
// },
// fail: (error: any) => {
// const {errno} = error
// if (errno === 103) {
// callRequestAuthCode()
// }
// },
// })
// } else {
// callRequestAuthCode()
// }
// })
// .catch((error) => {
// console.error('SDK :', error)
// })
// }
//
// switch (client) {
// case 'dingtalk':
// handleDingTalk()
// break
// case 'lark':
// handleLark()
// break
// default:
// break
// }
// })
</script>
<style lang="scss" scoped>
.login-gradient-divider {