Merge pull request #833 from Windfarer/oidc
feat: Authentication with OIDC
This commit is contained in:
+97
-1
@@ -1,7 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, nextTick, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import ManualKnowledgeEditor from '@/components/manual-knowledge-editor.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
// TDesign locale configs
|
||||
import enUSConfig from 'tdesign-vue-next/esm/locale/en_US'
|
||||
@@ -10,6 +13,8 @@ import koKRConfig from 'tdesign-vue-next/esm/locale/ko_KR'
|
||||
import ruRUConfig from 'tdesign-vue-next/esm/locale/ru_RU'
|
||||
|
||||
const { locale } = useI18n()
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const tdLocaleMap: Record<string, object> = {
|
||||
'en-US': enUSConfig,
|
||||
@@ -19,6 +24,97 @@ const tdLocaleMap: Record<string, object> = {
|
||||
}
|
||||
|
||||
const tdGlobalConfig = computed(() => tdLocaleMap[locale.value] || enUSConfig)
|
||||
|
||||
const decodeOIDCResult = (encoded: string) => {
|
||||
const normalized = encoded.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padded = normalized + '='.repeat((4 - normalized.length % 4) % 4)
|
||||
const binary = window.atob(padded)
|
||||
const bytes = Uint8Array.from(binary, char => char.charCodeAt(0))
|
||||
return JSON.parse(new TextDecoder().decode(bytes))
|
||||
}
|
||||
|
||||
const clearOIDCCallbackState = (path = '/') => {
|
||||
window.history.replaceState({}, document.title, path)
|
||||
}
|
||||
|
||||
const persistOIDCLoginResponse = async (response: any) => {
|
||||
if (response.user && response.tenant && response.token) {
|
||||
authStore.setUser({
|
||||
id: response.user.id || '',
|
||||
username: response.user.username || '',
|
||||
email: response.user.email || '',
|
||||
avatar: response.user.avatar,
|
||||
tenant_id: String(response.tenant.id) || '',
|
||||
can_access_all_tenants: response.user.can_access_all_tenants || false,
|
||||
created_at: response.user.created_at || new Date().toISOString(),
|
||||
updated_at: response.user.updated_at || new Date().toISOString()
|
||||
})
|
||||
authStore.setToken(response.token)
|
||||
if (response.refresh_token) {
|
||||
authStore.setRefreshToken(response.refresh_token)
|
||||
}
|
||||
authStore.setTenant({
|
||||
id: String(response.tenant.id) || '',
|
||||
name: response.tenant.name || '',
|
||||
api_key: response.tenant.api_key || '',
|
||||
owner_id: response.user.id || '',
|
||||
created_at: response.tenant.created_at || new Date().toISOString(),
|
||||
updated_at: response.tenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
}
|
||||
|
||||
const handleGlobalOIDCCallback = async () => {
|
||||
const hash = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : ''
|
||||
if (!hash) return
|
||||
|
||||
const params = new URLSearchParams(hash)
|
||||
const oidcError = params.get('oidc_error')
|
||||
const oidcErrorDescription = params.get('oidc_error_description')
|
||||
const oidcResult = params.get('oidc_result')
|
||||
|
||||
if (!oidcError && !oidcResult) return
|
||||
|
||||
if (oidcError) {
|
||||
clearOIDCCallbackState('/login')
|
||||
await router.replace('/login')
|
||||
MessagePlugin.error(oidcErrorDescription || 'OIDC login failed')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
if (!oidcResult) {
|
||||
clearOIDCCallbackState('/login')
|
||||
await router.replace('/login')
|
||||
MessagePlugin.error('OIDC login failed')
|
||||
return
|
||||
}
|
||||
|
||||
const response = decodeOIDCResult(oidcResult)
|
||||
if (response.success) {
|
||||
clearOIDCCallbackState('/')
|
||||
MessagePlugin.success('Login successful')
|
||||
await persistOIDCLoginResponse(response)
|
||||
return
|
||||
}
|
||||
|
||||
clearOIDCCallbackState('/login')
|
||||
await router.replace('/login')
|
||||
MessagePlugin.error(response.message || 'OIDC login failed')
|
||||
} catch (error: any) {
|
||||
console.error('Global OIDC callback handling failed:', error)
|
||||
clearOIDCCallbackState('/login')
|
||||
await router.replace('/login')
|
||||
MessagePlugin.error(error.message || 'OIDC login failed')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
handleGlobalOIDCCallback()
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<t-config-provider :globalConfig="tdGlobalConfig">
|
||||
|
||||
@@ -39,6 +39,20 @@ export interface LoginResponse {
|
||||
refresh_token?: string
|
||||
}
|
||||
|
||||
export interface OIDCAuthURLResponse {
|
||||
success: boolean
|
||||
authorization_url?: string
|
||||
state?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface OIDCConfigResponse {
|
||||
success: boolean
|
||||
enabled: boolean
|
||||
provider_display_name?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
// 用户注册接口
|
||||
export interface RegisterRequest {
|
||||
username: string
|
||||
@@ -130,6 +144,37 @@ export async function login(data: LoginRequest): Promise<LoginResponse> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 OIDC 登录跳转地址
|
||||
*/
|
||||
export async function getOIDCAuthorizationURL(redirectURI: string): Promise<OIDCAuthURLResponse> {
|
||||
try {
|
||||
const response = await get(`/api/v1/auth/oidc/url?redirect_uri=${encodeURIComponent(redirectURI)}`)
|
||||
return response as unknown as OIDCAuthURLResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: error.message || t('error.auth.loginFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 OIDC 登录配置
|
||||
*/
|
||||
export async function getOIDCConfig(): Promise<OIDCConfigResponse> {
|
||||
try {
|
||||
const response = await get('/api/v1/auth/oidc/config')
|
||||
return response as unknown as OIDCConfigResponse
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
enabled: false,
|
||||
message: error.message || t('error.auth.loginFailed')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户注册
|
||||
*/
|
||||
|
||||
@@ -1027,6 +1027,12 @@ export default {
|
||||
auth: {
|
||||
login: 'Login',
|
||||
logout: 'Logout',
|
||||
oidcLogin: 'Sign in with OIDC',
|
||||
oidcLoginWithProvider: 'Sign in with {provider}',
|
||||
redirectingToOIDC: 'Redirecting to identity provider...',
|
||||
orContinueWith: 'Or continue with',
|
||||
oidcLoginFailed: 'OIDC login failed',
|
||||
oidcStateMismatch: 'OIDC state verification failed, please try again',
|
||||
username: 'Username',
|
||||
email: 'Email',
|
||||
password: 'Password',
|
||||
|
||||
@@ -989,6 +989,12 @@ export default {
|
||||
auth: {
|
||||
login: 'Вход',
|
||||
logout: 'Выход',
|
||||
oidcLogin: 'Войти через OIDC',
|
||||
oidcLoginWithProvider: 'Войти через {provider}',
|
||||
redirectingToOIDC: 'Перенаправление к поставщику удостоверений...',
|
||||
orContinueWith: 'Или продолжить с помощью',
|
||||
oidcLoginFailed: 'Ошибка входа через OIDC',
|
||||
oidcStateMismatch: 'Не удалось проверить состояние OIDC, попробуйте снова',
|
||||
username: 'Имя пользователя',
|
||||
email: 'Почта Email',
|
||||
password: 'Пароль',
|
||||
|
||||
@@ -887,6 +887,12 @@ export default {
|
||||
loginSuccess: "登录成功!",
|
||||
loginFailed: "登录失败",
|
||||
loggingIn: "登录中...",
|
||||
oidcLogin: "使用 OIDC 登录",
|
||||
oidcLoginWithProvider: "使用 {provider} 登录",
|
||||
redirectingToOIDC: "正在跳转到身份提供商...",
|
||||
orContinueWith: "或使用以下方式继续",
|
||||
oidcLoginFailed: "OIDC 登录失败",
|
||||
oidcStateMismatch: "OIDC 状态校验失败,请重试",
|
||||
register: "注册",
|
||||
registering: "注册中...",
|
||||
createAccount: "创建账户",
|
||||
|
||||
@@ -228,14 +228,31 @@
|
||||
>
|
||||
{{ loading ? $t('auth.loggingIn') : $t('auth.login') }}
|
||||
</t-button>
|
||||
</t-form>
|
||||
|
||||
<div class="form-footer">
|
||||
<span>{{ $t('auth.noAccount') }}</span>
|
||||
<a href="#" @click.prevent="toggleMode" class="link-button">
|
||||
{{ $t('auth.registerNow') }}
|
||||
</a>
|
||||
</div>
|
||||
<div class="form-footer login-form-footer">
|
||||
<span>{{ $t('auth.noAccount') }}</span>
|
||||
<a href="#" @click.prevent="toggleMode" class="link-button">
|
||||
{{ $t('auth.registerNow') }}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div v-if="oidcEnabled" class="oidc-divider">
|
||||
<span>{{ $t('auth.orContinueWith') }}</span>
|
||||
</div>
|
||||
|
||||
<t-button
|
||||
v-if="oidcEnabled"
|
||||
theme="default"
|
||||
size="large"
|
||||
block
|
||||
:loading="oidcLoading"
|
||||
:disabled="loading"
|
||||
class="oidc-button"
|
||||
@click="handleOIDCLogin"
|
||||
>
|
||||
{{ oidcLoading ? $t('auth.redirectingToOIDC') : oidcLoginText }}
|
||||
</t-button>
|
||||
</t-form>
|
||||
|
||||
<!-- Features list -->
|
||||
<div class="login-features">
|
||||
@@ -360,7 +377,7 @@ import { Autoplay, EffectFade, Pagination } from 'swiper/modules'
|
||||
import 'swiper/css'
|
||||
import 'swiper/css/effect-fade'
|
||||
import 'swiper/css/pagination'
|
||||
import { login, register } from '@/api/auth'
|
||||
import { login, register, getOIDCAuthorizationURL, getOIDCConfig } from '@/api/auth'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -401,8 +418,11 @@ const registerFormRef = ref()
|
||||
|
||||
// State management
|
||||
const loading = ref(false)
|
||||
const oidcLoading = ref(false)
|
||||
const isRegisterMode = ref(false)
|
||||
const showLanguageMenu = ref(false)
|
||||
const oidcEnabled = ref(false)
|
||||
const oidcProviderName = ref('')
|
||||
|
||||
// Language options
|
||||
const languageOptions = [
|
||||
@@ -413,6 +433,12 @@ const languageOptions = [
|
||||
]
|
||||
|
||||
const currentLanguage = computed(() => locale.value)
|
||||
const oidcLoginText = computed(() => {
|
||||
if (oidcProviderName.value) {
|
||||
return t('auth.oidcLoginWithProvider', { provider: oidcProviderName.value })
|
||||
}
|
||||
return t('auth.oidcLogin')
|
||||
})
|
||||
const currentLangOption = computed(() => languageOptions.find(l => l.value === currentLanguage.value))
|
||||
|
||||
// Login form data
|
||||
@@ -516,6 +542,69 @@ onBeforeUnmount(() => {
|
||||
document.removeEventListener('click', handleClickOutside)
|
||||
})
|
||||
|
||||
const persistLoginResponse = async (response: any) => {
|
||||
if (response.user && response.tenant && response.token) {
|
||||
authStore.setUser({
|
||||
id: response.user.id || '',
|
||||
username: response.user.username || '',
|
||||
email: response.user.email || '',
|
||||
avatar: response.user.avatar,
|
||||
tenant_id: String(response.tenant.id) || '',
|
||||
can_access_all_tenants: response.user.can_access_all_tenants || false,
|
||||
created_at: response.user.created_at || new Date().toISOString(),
|
||||
updated_at: response.user.updated_at || new Date().toISOString()
|
||||
})
|
||||
authStore.setToken(response.token)
|
||||
if (response.refresh_token) {
|
||||
authStore.setRefreshToken(response.refresh_token)
|
||||
}
|
||||
authStore.setTenant({
|
||||
id: String(response.tenant.id) || '',
|
||||
name: response.tenant.name || '',
|
||||
api_key: response.tenant.api_key || '',
|
||||
owner_id: response.user.id || '',
|
||||
created_at: response.tenant.created_at || new Date().toISOString(),
|
||||
updated_at: response.tenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
}
|
||||
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
}
|
||||
|
||||
const getBackendOIDCRedirectURI = () => `${window.location.origin}/api/v1/auth/oidc/callback`
|
||||
|
||||
const loadOIDCConfig = async () => {
|
||||
try {
|
||||
const response = await getOIDCConfig()
|
||||
oidcEnabled.value = !!response.success && !!response.enabled
|
||||
oidcProviderName.value = response.provider_display_name || ''
|
||||
} catch {
|
||||
oidcEnabled.value = false
|
||||
oidcProviderName.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleOIDCLogin = async () => {
|
||||
try {
|
||||
oidcLoading.value = true
|
||||
const response = await getOIDCAuthorizationURL(getBackendOIDCRedirectURI())
|
||||
const authorizationURL = response.authorization_url
|
||||
|
||||
if (!response.success || !authorizationURL) {
|
||||
MessagePlugin.error(response.message || t('auth.oidcLoginFailed'))
|
||||
return
|
||||
}
|
||||
|
||||
window.location.href = authorizationURL
|
||||
} catch (error: any) {
|
||||
console.error('OIDC 登录跳转失败:', error)
|
||||
MessagePlugin.error(error.message || t('auth.oidcLoginFailed'))
|
||||
} finally {
|
||||
oidcLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Handle login
|
||||
const handleLogin = async () => {
|
||||
try {
|
||||
@@ -530,37 +619,8 @@ const handleLogin = async () => {
|
||||
})
|
||||
|
||||
if (response.success) {
|
||||
// Save user info and token
|
||||
if (response.user && response.tenant && response.token) {
|
||||
authStore.setUser({
|
||||
id: response.user.id || '',
|
||||
username: response.user.username || '',
|
||||
email: response.user.email || '',
|
||||
avatar: response.user.avatar,
|
||||
tenant_id: String(response.tenant.id) || '',
|
||||
can_access_all_tenants: response.user.can_access_all_tenants || false,
|
||||
created_at: response.user.created_at || new Date().toISOString(),
|
||||
updated_at: response.user.updated_at || new Date().toISOString()
|
||||
})
|
||||
authStore.setToken(response.token)
|
||||
if (response.refresh_token) {
|
||||
authStore.setRefreshToken(response.refresh_token)
|
||||
}
|
||||
authStore.setTenant({
|
||||
id: String(response.tenant.id) || '',
|
||||
name: response.tenant.name || '',
|
||||
api_key: response.tenant.api_key || '',
|
||||
owner_id: response.user.id || '',
|
||||
created_at: response.tenant.created_at || new Date().toISOString(),
|
||||
updated_at: response.tenant.updated_at || new Date().toISOString()
|
||||
})
|
||||
}
|
||||
|
||||
MessagePlugin.success(t('auth.loginSuccess'))
|
||||
|
||||
// Wait for state update before redirect
|
||||
await nextTick()
|
||||
router.replace('/platform/knowledge-bases')
|
||||
await persistLoginResponse(response)
|
||||
} else {
|
||||
MessagePlugin.error(response.message || t('auth.loginError'))
|
||||
}
|
||||
@@ -611,8 +671,11 @@ const handleRegister = async () => {
|
||||
// Check if already logged in
|
||||
onMounted(() => {
|
||||
if (authStore.isLoggedIn) {
|
||||
router.replace('/platform/tenant/knowledge-bases')
|
||||
router.replace('/platform/knowledge-bases')
|
||||
return
|
||||
}
|
||||
|
||||
loadOIDCConfig()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -1083,6 +1146,37 @@ onMounted(() => {
|
||||
margin: 20px 0 16px 0;
|
||||
}
|
||||
|
||||
.oidc-divider {
|
||||
position: relative;
|
||||
margin: 4px 0 6px;
|
||||
text-align: center;
|
||||
color: var(--td-text-color-placeholder);
|
||||
font-size: 12px;
|
||||
|
||||
span {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
padding: 0 12px;
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
}
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 50%;
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
}
|
||||
|
||||
.oidc-button {
|
||||
height: 46px;
|
||||
border-radius: 8px;
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-footer {
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
@@ -1106,6 +1200,12 @@ onMounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
.login-form-footer {
|
||||
border-bottom: none;
|
||||
padding-bottom: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.login-features {
|
||||
margin-top: 20px;
|
||||
padding: 0;
|
||||
@@ -1145,6 +1245,14 @@ onMounted(() => {
|
||||
|
||||
/* Responsive Design */
|
||||
@media (max-width: 1024px) {
|
||||
.knowledge-node:nth-of-type(n + 13) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.connection-line:nth-of-type(n + 13) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.showcase-subtitle {
|
||||
font-size: 18px;
|
||||
}
|
||||
@@ -1179,6 +1287,14 @@ onMounted(() => {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.knowledge-node:nth-of-type(n + 9) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.connection-line:nth-of-type(n + 9) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.showcase-section {
|
||||
flex: 0 0 auto;
|
||||
min-height: 50vh;
|
||||
@@ -1241,6 +1357,10 @@ onMounted(() => {
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.animated-bg {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.showcase-section {
|
||||
padding: 32px 20px;
|
||||
}
|
||||
@@ -1287,6 +1407,18 @@ onMounted(() => {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.knowledge-node,
|
||||
.connection-line {
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
.animated-bg {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
|
||||
Reference in New Issue
Block a user