mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 09:20:22 +08:00
feat: 添加 OAuth 认证支持及相关改进
- 新增 OAuth 模块,支持 LinuxDo/GitHub/Google 等第三方登录 - 用户邮箱改为可选字段,支持无邮箱注册 - 新增模块配置验证状态 (config_validated/config_error) - 系统设置界面改为分块独立保存 - 用户设置新增 OAuth 绑定管理和首次密码设置 - 登录界面支持 OAuth 按钮展示 - 邮箱验证设置移至邮件设置页面
This commit is contained in:
@@ -99,40 +99,13 @@
|
||||
>
|
||||
SMTP 密码
|
||||
</Label>
|
||||
<div class="relative mt-1">
|
||||
<div class="mt-1">
|
||||
<Input
|
||||
id="smtp-password"
|
||||
v-model="emailConfig.smtp_password"
|
||||
type="text"
|
||||
masked
|
||||
:placeholder="smtpPasswordIsSet ? '已设置(留空保持不变)' : '请输入密码'"
|
||||
class="-webkit-text-security-disc"
|
||||
:class="(smtpPasswordIsSet || emailConfig.smtp_password) ? 'pr-10' : ''"
|
||||
autocomplete="one-time-code"
|
||||
data-lpignore="true"
|
||||
data-1p-ignore="true"
|
||||
data-form-type="other"
|
||||
/>
|
||||
<button
|
||||
v-if="smtpPasswordIsSet || emailConfig.smtp_password"
|
||||
type="button"
|
||||
class="absolute right-3 top-1/2 -translate-y-1/2 p-1 rounded-full text-muted-foreground/60 hover:text-muted-foreground hover:bg-muted/50 transition-colors"
|
||||
title="清除密码"
|
||||
@click="handleClearSmtpPassword"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M18 6 6 18" /><path d="m6 6 12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
邮箱密码或应用专用密码
|
||||
@@ -213,6 +186,116 @@
|
||||
</div>
|
||||
</CardSection>
|
||||
|
||||
<!-- 注册邮箱验证 -->
|
||||
<CardSection
|
||||
title="注册邮箱验证"
|
||||
description="控制用户注册时的邮箱验证要求和后缀限制"
|
||||
>
|
||||
<template #actions>
|
||||
<Button
|
||||
size="sm"
|
||||
:disabled="emailVerificationSaveLoading"
|
||||
@click="saveEmailVerificationConfig"
|
||||
>
|
||||
{{ emailVerificationSaveLoading ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</template>
|
||||
<div class="space-y-6">
|
||||
<!-- 第一行:需要邮箱验证 + 后缀限制模式 -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<!-- 需要邮箱验证 -->
|
||||
<div class="flex items-center justify-between h-full">
|
||||
<div>
|
||||
<Label
|
||||
for="require-email-verification"
|
||||
class="block text-sm font-medium cursor-pointer"
|
||||
:class="{ 'text-muted-foreground': !smtpConfigured }"
|
||||
>
|
||||
需要邮箱验证
|
||||
</Label>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
<template v-if="!smtpConfigured">
|
||||
需先配置 SMTP 服务
|
||||
</template>
|
||||
<template v-else>
|
||||
开启后,用户注册时必须验证邮箱
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="require-email-verification"
|
||||
v-model="requireEmailVerification"
|
||||
:disabled="!smtpConfigured"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 后缀限制模式 -->
|
||||
<div>
|
||||
<Label
|
||||
for="email-suffix-mode"
|
||||
class="block text-sm font-medium mb-2"
|
||||
>
|
||||
后缀限制模式
|
||||
</Label>
|
||||
<Select
|
||||
v-model="emailConfig.email_suffix_mode"
|
||||
v-model:open="emailSuffixModeSelectOpen"
|
||||
:disabled="!requireEmailVerification"
|
||||
>
|
||||
<SelectTrigger
|
||||
id="email-suffix-mode"
|
||||
class="mt-1"
|
||||
:disabled="!requireEmailVerification"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
不限制 - 允许所有邮箱
|
||||
</SelectItem>
|
||||
<SelectItem value="whitelist">
|
||||
白名单 - 仅允许列出的后缀
|
||||
</SelectItem>
|
||||
<SelectItem value="blacklist">
|
||||
黑名单 - 拒绝列出的后缀
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
<template v-if="emailConfig.email_suffix_mode === 'none'">
|
||||
不限制邮箱后缀,所有邮箱均可注册
|
||||
</template>
|
||||
<template v-else-if="emailConfig.email_suffix_mode === 'whitelist'">
|
||||
仅允许列出后缀的邮箱注册
|
||||
</template>
|
||||
<template v-else>
|
||||
拒绝列出后缀的邮箱注册
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 第二行:邮箱后缀列表 -->
|
||||
<div v-if="emailConfig.email_suffix_mode !== 'none'">
|
||||
<Label
|
||||
for="email-suffix-list"
|
||||
class="block text-sm font-medium mb-2"
|
||||
>
|
||||
邮箱后缀列表
|
||||
</Label>
|
||||
<Input
|
||||
id="email-suffix-list"
|
||||
v-model="emailSuffixListStr"
|
||||
placeholder="gmail.com, outlook.com, qq.com"
|
||||
class="mt-1"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
逗号分隔,例如: gmail.com, outlook.com, qq.com
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardSection>
|
||||
|
||||
<!-- 邮件模板配置 -->
|
||||
<CardSection
|
||||
title="邮件模板"
|
||||
@@ -227,38 +310,43 @@
|
||||
{{ templateSaveLoading ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</template>
|
||||
<!-- 模板类型选择 -->
|
||||
<div class="flex items-center gap-2 mb-4">
|
||||
<button
|
||||
v-for="tpl in templateTypes"
|
||||
:key="tpl.type"
|
||||
class="px-3 py-1.5 text-sm font-medium rounded-md transition-colors"
|
||||
:class="activeTemplateType === tpl.type
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted text-muted-foreground hover:text-foreground'"
|
||||
@click="handleTemplateTypeChange(tpl.type)"
|
||||
>
|
||||
{{ tpl.name }}
|
||||
<span
|
||||
v-if="tpl.is_custom"
|
||||
class="ml-1 text-xs opacity-70"
|
||||
>(已自定义)</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 当前模板编辑区 -->
|
||||
<div
|
||||
v-if="currentTemplate"
|
||||
class="space-y-4"
|
||||
>
|
||||
<!-- 可用变量提示 -->
|
||||
<div class="text-xs text-muted-foreground bg-muted/50 rounded-md px-3 py-2">
|
||||
可用变量:
|
||||
<code
|
||||
v-for="(v, i) in currentTemplate.variables"
|
||||
:key="v"
|
||||
class="mx-1 px-1.5 py-0.5 bg-background rounded text-foreground"
|
||||
>{{ formatVariable(v) }}<span v-if="i < currentTemplate.variables.length - 1">,</span></code>
|
||||
<!-- 模板类型选择 + 可用变量 -->
|
||||
<div class="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div class="flex items-center border-b border-border">
|
||||
<button
|
||||
v-for="tpl in templateTypes"
|
||||
:key="tpl.type"
|
||||
class="px-4 py-2 text-sm font-medium transition-colors relative"
|
||||
:class="activeTemplateType === tpl.type
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground'"
|
||||
@click="handleTemplateTypeChange(tpl.type)"
|
||||
>
|
||||
{{ tpl.name }}
|
||||
<span
|
||||
v-if="tpl.is_custom"
|
||||
class="ml-1 text-xs opacity-70"
|
||||
>(已自定义)</span>
|
||||
<span
|
||||
v-if="activeTemplateType === tpl.type"
|
||||
class="absolute bottom-0 left-0 right-0 h-0.5 bg-primary"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<div class="text-xs text-muted-foreground">
|
||||
可用变量:
|
||||
<code
|
||||
v-for="(v, i) in currentTemplate.variables"
|
||||
:key="v"
|
||||
class="mx-0.5 px-1.5 py-0.5 bg-muted rounded text-foreground"
|
||||
>{{ formatVariable(v) }}<span v-if="i < currentTemplate.variables.length - 1">,</span></code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 邮件主题 -->
|
||||
@@ -289,7 +377,7 @@
|
||||
<textarea
|
||||
id="template-html"
|
||||
v-model="templateHtml"
|
||||
rows="16"
|
||||
rows="12"
|
||||
class="mt-1 w-full font-mono text-sm bg-muted/30 border border-border rounded-md p-3 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-y"
|
||||
:placeholder="currentTemplate.default_html || '<!DOCTYPE html>...'"
|
||||
spellcheck="false"
|
||||
@@ -300,6 +388,7 @@
|
||||
<div class="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="previewLoading"
|
||||
@click="handlePreviewTemplate"
|
||||
>
|
||||
@@ -307,6 +396,7 @@
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="!currentTemplate.is_custom"
|
||||
@click="handleResetTemplate"
|
||||
>
|
||||
@@ -378,83 +468,6 @@
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
<!-- 注册邮箱限制 -->
|
||||
<CardSection
|
||||
title="注册邮箱限制"
|
||||
description="控制允许注册的邮箱后缀,支持白名单或黑名单模式"
|
||||
>
|
||||
<template #actions>
|
||||
<Button
|
||||
size="sm"
|
||||
:disabled="emailSuffixSaveLoading"
|
||||
@click="saveEmailSuffixConfig"
|
||||
>
|
||||
{{ emailSuffixSaveLoading ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</template>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<Label
|
||||
for="email-suffix-mode"
|
||||
class="block text-sm font-medium mb-2"
|
||||
>
|
||||
限制模式
|
||||
</Label>
|
||||
<Select
|
||||
v-model="emailConfig.email_suffix_mode"
|
||||
v-model:open="emailSuffixModeSelectOpen"
|
||||
>
|
||||
<SelectTrigger
|
||||
id="email-suffix-mode"
|
||||
class="mt-1"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">
|
||||
不限制 - 允许所有邮箱
|
||||
</SelectItem>
|
||||
<SelectItem value="whitelist">
|
||||
白名单 - 仅允许列出的后缀
|
||||
</SelectItem>
|
||||
<SelectItem value="blacklist">
|
||||
黑名单 - 拒绝列出的后缀
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
<template v-if="emailConfig.email_suffix_mode === 'none'">
|
||||
不限制邮箱后缀,所有邮箱均可注册
|
||||
</template>
|
||||
<template v-else-if="emailConfig.email_suffix_mode === 'whitelist'">
|
||||
仅允许下方列出后缀的邮箱注册
|
||||
</template>
|
||||
<template v-else>
|
||||
拒绝下方列出后缀的邮箱注册
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-if="emailConfig.email_suffix_mode !== 'none'">
|
||||
<Label
|
||||
for="email-suffix-list"
|
||||
class="block text-sm font-medium"
|
||||
>
|
||||
邮箱后缀列表
|
||||
</Label>
|
||||
<Input
|
||||
id="email-suffix-list"
|
||||
v-model="emailSuffixListStr"
|
||||
placeholder="gmail.com, outlook.com, qq.com"
|
||||
class="mt-1"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
逗号分隔,例如: gmail.com, outlook.com, qq.com
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardSection>
|
||||
</div>
|
||||
</PageContainer>
|
||||
</template>
|
||||
@@ -464,6 +477,7 @@ import { ref, computed, onMounted } from 'vue'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import Input from '@/components/ui/input.vue'
|
||||
import Label from '@/components/ui/label.vue'
|
||||
import Switch from '@/components/ui/switch.vue'
|
||||
import Select from '@/components/ui/select.vue'
|
||||
import SelectTrigger from '@/components/ui/select-trigger.vue'
|
||||
import SelectValue from '@/components/ui/select-value.vue'
|
||||
@@ -473,6 +487,7 @@ import Dialog from '@/components/ui/dialog/Dialog.vue'
|
||||
import { PageHeader, PageContainer, CardSection } from '@/components/layout'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { adminApi, type EmailTemplateInfo } from '@/api/admin'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { log } from '@/utils/logger'
|
||||
|
||||
const { success, error } = useToast()
|
||||
@@ -493,12 +508,13 @@ interface EmailConfig {
|
||||
}
|
||||
|
||||
const smtpSaveLoading = ref(false)
|
||||
const emailSuffixSaveLoading = ref(false)
|
||||
const emailVerificationSaveLoading = ref(false)
|
||||
const smtpEncryptionSelectOpen = ref(false)
|
||||
const emailSuffixModeSelectOpen = ref(false)
|
||||
const testSmtpLoading = ref(false)
|
||||
const smtpPasswordIsSet = ref(false)
|
||||
const clearSmtpPassword = ref(false) // 标记是否要清除密码
|
||||
const requireEmailVerification = ref(false) // 是否开启了邮箱验证
|
||||
const smtpConfigured = ref(false) // SMTP 是否已配置
|
||||
|
||||
// 邮件模板相关状态
|
||||
const templateLoading = ref(false)
|
||||
@@ -583,10 +599,57 @@ const smtpEncryption = computed({
|
||||
onMounted(async () => {
|
||||
await Promise.all([
|
||||
loadEmailConfig(),
|
||||
loadEmailTemplates()
|
||||
loadEmailTemplates(),
|
||||
loadRequireEmailVerification(),
|
||||
])
|
||||
})
|
||||
|
||||
async function loadRequireEmailVerification() {
|
||||
try {
|
||||
const settings = await authApi.getRegistrationSettings()
|
||||
requireEmailVerification.value = !!settings.require_email_verification
|
||||
smtpConfigured.value = !!settings.email_configured
|
||||
} catch {
|
||||
requireEmailVerification.value = false
|
||||
smtpConfigured.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveEmailVerificationConfig() {
|
||||
emailVerificationSaveLoading.value = true
|
||||
try {
|
||||
const configItems = [
|
||||
{
|
||||
key: 'require_email_verification',
|
||||
value: requireEmailVerification.value,
|
||||
description: '是否需要邮箱验证'
|
||||
},
|
||||
{
|
||||
key: 'email_suffix_mode',
|
||||
value: emailConfig.value.email_suffix_mode,
|
||||
description: '邮箱后缀限制模式'
|
||||
},
|
||||
{
|
||||
key: 'email_suffix_list',
|
||||
value: emailConfig.value.email_suffix_list,
|
||||
description: '邮箱后缀列表'
|
||||
},
|
||||
]
|
||||
|
||||
await Promise.all(
|
||||
configItems.map(item =>
|
||||
adminApi.updateSystemConfig(item.key, item.value, item.description)
|
||||
)
|
||||
)
|
||||
success('配置已保存')
|
||||
} catch (err) {
|
||||
error('保存配置失败')
|
||||
log.error('保存邮箱验证配置失败:', err)
|
||||
} finally {
|
||||
emailVerificationSaveLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEmailTemplates() {
|
||||
templateLoading.value = true
|
||||
try {
|
||||
@@ -711,7 +774,6 @@ async function loadEmailConfig() {
|
||||
// 配置不存在时使用默认值,无需处理
|
||||
}
|
||||
}
|
||||
clearSmtpPassword.value = false
|
||||
} catch (err) {
|
||||
error('加载邮件配置失败')
|
||||
log.error('加载邮件配置失败:', err)
|
||||
@@ -722,12 +784,6 @@ async function loadEmailConfig() {
|
||||
async function saveSmtpConfig() {
|
||||
smtpSaveLoading.value = true
|
||||
try {
|
||||
const passwordAction: 'unchanged' | 'updated' | 'cleared' = emailConfig.value.smtp_password
|
||||
? 'updated'
|
||||
: clearSmtpPassword.value
|
||||
? 'cleared'
|
||||
: 'unchanged'
|
||||
|
||||
const configItems = [
|
||||
{
|
||||
key: 'smtp_host',
|
||||
@@ -745,7 +801,7 @@ async function saveSmtpConfig() {
|
||||
description: 'SMTP 用户名'
|
||||
},
|
||||
// 只有输入了新密码才提交(空值表示保持原密码)
|
||||
...(passwordAction === 'updated'
|
||||
...(emailConfig.value.smtp_password
|
||||
? [{
|
||||
key: 'smtp_password',
|
||||
value: emailConfig.value.smtp_password,
|
||||
@@ -774,24 +830,15 @@ async function saveSmtpConfig() {
|
||||
},
|
||||
]
|
||||
|
||||
const promises = configItems.map(item =>
|
||||
adminApi.updateSystemConfig(item.key, item.value, item.description)
|
||||
await Promise.all(
|
||||
configItems.map(item =>
|
||||
adminApi.updateSystemConfig(item.key, item.value, item.description)
|
||||
)
|
||||
)
|
||||
|
||||
// 如果标记了清除密码,删除密码配置
|
||||
if (passwordAction === 'cleared') {
|
||||
promises.push(adminApi.deleteSystemConfig('smtp_password'))
|
||||
}
|
||||
|
||||
await Promise.all(promises)
|
||||
success('SMTP 配置已保存')
|
||||
|
||||
// 更新状态
|
||||
if (passwordAction === 'cleared') {
|
||||
clearSmtpPassword.value = false
|
||||
smtpPasswordIsSet.value = false
|
||||
} else if (passwordAction === 'updated') {
|
||||
clearSmtpPassword.value = false
|
||||
if (emailConfig.value.smtp_password) {
|
||||
smtpPasswordIsSet.value = true
|
||||
}
|
||||
emailConfig.value.smtp_password = null
|
||||
@@ -803,51 +850,6 @@ async function saveSmtpConfig() {
|
||||
}
|
||||
}
|
||||
|
||||
// 保存邮箱后缀限制配置
|
||||
async function saveEmailSuffixConfig() {
|
||||
emailSuffixSaveLoading.value = true
|
||||
try {
|
||||
const configItems = [
|
||||
{
|
||||
key: 'email_suffix_mode',
|
||||
value: emailConfig.value.email_suffix_mode,
|
||||
description: '邮箱后缀限制模式(none/whitelist/blacklist)'
|
||||
},
|
||||
{
|
||||
key: 'email_suffix_list',
|
||||
value: emailConfig.value.email_suffix_list,
|
||||
description: '邮箱后缀列表'
|
||||
},
|
||||
]
|
||||
|
||||
const promises = configItems.map(item =>
|
||||
adminApi.updateSystemConfig(item.key, item.value, item.description)
|
||||
)
|
||||
|
||||
await Promise.all(promises)
|
||||
success('邮箱限制配置已保存')
|
||||
} catch (err) {
|
||||
error('保存配置失败')
|
||||
log.error('保存邮箱限制配置失败:', err)
|
||||
} finally {
|
||||
emailSuffixSaveLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 清除 SMTP 密码
|
||||
function handleClearSmtpPassword() {
|
||||
// 如果有输入内容,先清空输入框
|
||||
if (emailConfig.value.smtp_password) {
|
||||
emailConfig.value.smtp_password = null
|
||||
return
|
||||
}
|
||||
// 标记要清除服务端密码(保存时生效)
|
||||
if (smtpPasswordIsSet.value) {
|
||||
clearSmtpPassword.value = true
|
||||
smtpPasswordIsSet.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 测试 SMTP 连接
|
||||
async function handleTestSmtp() {
|
||||
testSmtpLoading.value = true
|
||||
|
||||
@@ -76,44 +76,14 @@
|
||||
>
|
||||
绑定密码
|
||||
</Label>
|
||||
<div class="relative mt-1">
|
||||
<div class="mt-1">
|
||||
<Input
|
||||
id="bind-password"
|
||||
v-model="ldapConfig.bind_password"
|
||||
type="password"
|
||||
masked
|
||||
:placeholder="hasPassword ? '已设置(留空保持不变)' : '请输入密码'"
|
||||
:class="(hasPassword || ldapConfig.bind_password) ? 'pr-10' : ''"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
<button
|
||||
v-if="hasPassword || ldapConfig.bind_password"
|
||||
type="button"
|
||||
class="absolute right-3 top-1/2 -translate-y-1/2 p-1 rounded-full text-muted-foreground/60 hover:text-muted-foreground hover:bg-muted/50 transition-colors"
|
||||
title="清除密码"
|
||||
@click="handleClearPassword"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
><line
|
||||
x1="18"
|
||||
y1="6"
|
||||
x2="6"
|
||||
y2="18"
|
||||
/><line
|
||||
x1="6"
|
||||
y1="6"
|
||||
x2="18"
|
||||
y2="18"
|
||||
/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
绑定账号的密码
|
||||
@@ -280,7 +250,6 @@ const loading = ref(false)
|
||||
const saveLoading = ref(false)
|
||||
const testLoading = ref(false)
|
||||
const hasPassword = ref(false)
|
||||
const clearPassword = ref(false) // 标记是否要清除密码
|
||||
|
||||
const ldapConfig = ref({
|
||||
server_url: '',
|
||||
@@ -320,7 +289,6 @@ async function loadConfig() {
|
||||
connect_timeout: response.connect_timeout || 10,
|
||||
}
|
||||
hasPassword.value = !!response.has_bind_password
|
||||
clearPassword.value = false
|
||||
} catch (err) {
|
||||
error('加载 LDAP 配置失败')
|
||||
console.error('加载 LDAP 配置失败:', err)
|
||||
@@ -346,25 +314,16 @@ async function handleSave() {
|
||||
connect_timeout: ldapConfig.value.connect_timeout,
|
||||
}
|
||||
|
||||
// 优先使用输入的新密码;否则如果标记清除则发送空字符串
|
||||
let passwordAction: 'unchanged' | 'updated' | 'cleared' = 'unchanged'
|
||||
// 只有输入了新密码才更新密码
|
||||
if (ldapConfig.value.bind_password) {
|
||||
payload.bind_password = ldapConfig.value.bind_password
|
||||
passwordAction = 'updated'
|
||||
} else if (clearPassword.value) {
|
||||
payload.bind_password = ''
|
||||
passwordAction = 'cleared'
|
||||
}
|
||||
|
||||
await adminApi.updateLdapConfig(payload)
|
||||
success('LDAP 配置保存成功')
|
||||
|
||||
if (passwordAction === 'cleared') {
|
||||
hasPassword.value = false
|
||||
clearPassword.value = false
|
||||
} else if (passwordAction === 'updated') {
|
||||
if (ldapConfig.value.bind_password) {
|
||||
hasPassword.value = true
|
||||
clearPassword.value = false
|
||||
}
|
||||
ldapConfig.value.bind_password = ''
|
||||
} catch (err) {
|
||||
@@ -376,11 +335,6 @@ async function handleSave() {
|
||||
}
|
||||
|
||||
async function handleTestConnection() {
|
||||
if (clearPassword.value && !ldapConfig.value.bind_password) {
|
||||
error('已标记清除绑定密码,请先保存或输入新的绑定密码再测试')
|
||||
return
|
||||
}
|
||||
|
||||
testLoading.value = true
|
||||
try {
|
||||
const payload: LdapConfigUpdateRequest = {
|
||||
@@ -410,17 +364,4 @@ async function handleTestConnection() {
|
||||
testLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleClearPassword() {
|
||||
// 如果有输入内容,先清空输入框
|
||||
if (ldapConfig.value.bind_password) {
|
||||
ldapConfig.value.bind_password = ''
|
||||
return
|
||||
}
|
||||
// 标记要清除服务端密码(保存时生效)
|
||||
if (hasPassword.value) {
|
||||
clearPassword.value = true
|
||||
hasPassword.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -55,25 +55,17 @@
|
||||
</div>
|
||||
|
||||
<!-- 模块图标和名称 -->
|
||||
<div class="flex items-start gap-4 mb-4">
|
||||
<div class="flex items-start gap-4 mb-3">
|
||||
<div
|
||||
class="w-12 h-12 rounded-xl flex items-center justify-center shrink-0 transition-colors"
|
||||
class="w-11 h-11 rounded-xl flex items-center justify-center shrink-0 transition-colors"
|
||||
:class="module.active
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'bg-muted text-muted-foreground group-hover:bg-muted/80'"
|
||||
>
|
||||
<component :is="getCategoryIcon(module.category)" class="w-6 h-6" />
|
||||
<component :is="getCategoryIcon(module.category)" class="w-5 h-5" />
|
||||
</div>
|
||||
<div class="flex-1 min-w-0 pt-0.5">
|
||||
<div class="flex-1 min-w-0 pt-1">
|
||||
<h4 class="font-semibold text-base truncate">{{ module.display_name }}</h4>
|
||||
<div class="mt-1.5">
|
||||
<Badge
|
||||
:variant="getStatusBadgeVariant(module)"
|
||||
class="text-xs"
|
||||
>
|
||||
{{ getStatusText(module) }}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -82,21 +74,6 @@
|
||||
{{ module.description }}
|
||||
</p>
|
||||
|
||||
<!-- 模块信息 -->
|
||||
<div class="mt-4 pt-4 border-t border-border/50 space-y-2">
|
||||
<div class="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span class="font-mono bg-muted/50 px-1.5 py-0.5 rounded">{{ module.name }}</span>
|
||||
<span class="text-border">|</span>
|
||||
<span :class="{
|
||||
'text-green-600': module.health === 'healthy',
|
||||
'text-amber-600': module.health === 'degraded',
|
||||
'text-red-600': module.health === 'unhealthy',
|
||||
}">
|
||||
{{ getHealthText(module.health) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 不可用提示 -->
|
||||
<div
|
||||
v-if="!module.available"
|
||||
@@ -110,15 +87,24 @@
|
||||
<div class="flex items-center gap-3">
|
||||
<Switch
|
||||
:model-value="module.enabled"
|
||||
:disabled="!module.available || toggling[module.name]"
|
||||
:disabled="!module.available || !module.config_validated || toggling[module.name]"
|
||||
@update:model-value="(val: boolean) => toggleModule(module.name, val)"
|
||||
/>
|
||||
<span class="text-sm" :class="module.enabled ? 'text-foreground' : 'text-muted-foreground'">
|
||||
{{ module.enabled ? '已启用' : '已禁用' }}
|
||||
</span>
|
||||
<div class="flex flex-col">
|
||||
<span class="text-sm" :class="module.enabled ? 'text-foreground' : 'text-muted-foreground'">
|
||||
{{ module.enabled ? '已启用' : '已禁用' }}
|
||||
</span>
|
||||
<!-- 配置未验证提示(小字) -->
|
||||
<span
|
||||
v-if="module.available && !module.config_validated"
|
||||
class="text-xs text-muted-foreground"
|
||||
>
|
||||
{{ module.config_error || '请先完成配置' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
v-if="module.admin_route && module.active"
|
||||
v-if="module.admin_route"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="gap-1.5"
|
||||
@@ -157,14 +143,13 @@ import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { RefreshCw, Puzzle, Users, Shield, Gauge, Link, Search, Settings } from 'lucide-vue-next'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
import Switch from '@/components/ui/switch.vue'
|
||||
import Input from '@/components/ui/input.vue'
|
||||
import { PageHeader, PageContainer } from '@/components/layout'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { useModuleStore } from '@/stores/modules'
|
||||
import type { ModuleStatus } from '@/api/modules'
|
||||
import { log } from '@/utils/logger'
|
||||
import { getErrorMessage } from '@/types/api-error'
|
||||
|
||||
const router = useRouter()
|
||||
const { success, error } = useToast()
|
||||
@@ -185,33 +170,6 @@ function getCategoryIcon(category: string) {
|
||||
return icons[category] || Puzzle
|
||||
}
|
||||
|
||||
// 获取状态文本
|
||||
function getStatusText(module: ModuleStatus): string {
|
||||
if (!module.available) return '不可用'
|
||||
if (module.active) return '已激活'
|
||||
if (module.enabled) return '已启用'
|
||||
return '已禁用'
|
||||
}
|
||||
|
||||
// 获取状态徽章样式
|
||||
function getStatusBadgeVariant(module: ModuleStatus): 'default' | 'secondary' | 'outline' | 'destructive' {
|
||||
if (!module.available) return 'destructive'
|
||||
if (module.active) return 'default'
|
||||
if (module.enabled) return 'secondary'
|
||||
return 'outline'
|
||||
}
|
||||
|
||||
// 获取健康状态文本
|
||||
function getHealthText(health: string): string {
|
||||
const texts: Record<string, string> = {
|
||||
healthy: '健康',
|
||||
degraded: '降级',
|
||||
unhealthy: '异常',
|
||||
unknown: '未知',
|
||||
}
|
||||
return texts[health] || health
|
||||
}
|
||||
|
||||
// 所有模块列表(按 admin_menu_order 排序)
|
||||
const allModules = computed(() => {
|
||||
return Object.values(moduleStore.modules)
|
||||
@@ -249,14 +207,10 @@ async function fetchModules() {
|
||||
async function toggleModule(moduleName: string, enabled: boolean) {
|
||||
toggling.value[moduleName] = true
|
||||
try {
|
||||
const result = await moduleStore.setEnabled(moduleName, enabled)
|
||||
if (result) {
|
||||
success(enabled ? '模块已启用' : '模块已禁用')
|
||||
} else {
|
||||
error('操作失败')
|
||||
}
|
||||
await moduleStore.setEnabled(moduleName, enabled)
|
||||
success(enabled ? '模块已启用' : '模块已禁用')
|
||||
} catch (err) {
|
||||
error('操作失败')
|
||||
error(getErrorMessage(err, '操作失败'))
|
||||
log.error('切换模块状态失败:', err)
|
||||
} finally {
|
||||
toggling.value[moduleName] = false
|
||||
|
||||
454
frontend/src/views/admin/OAuthSettings.vue
Normal file
454
frontend/src/views/admin/OAuthSettings.vue
Normal file
@@ -0,0 +1,454 @@
|
||||
<template>
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title="OAuth 配置"
|
||||
description="配置 OAuth Providers(登录/绑定)"
|
||||
>
|
||||
<template #actions>
|
||||
<Button
|
||||
variant="outline"
|
||||
:disabled="loading"
|
||||
@click="loadAll"
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="mt-6">
|
||||
<!-- Provider 选择 Tab -->
|
||||
<div class="flex flex-wrap gap-2 mb-6">
|
||||
<button
|
||||
v-for="t in supportedTypes"
|
||||
:key="t.provider_type"
|
||||
class="flex items-center gap-3 px-4 py-2 rounded-lg text-sm font-medium transition-colors border"
|
||||
:class="selectedType === t.provider_type
|
||||
? 'border-primary text-primary'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50 hover:text-foreground'"
|
||||
@click="handleTabClick(t.provider_type)"
|
||||
>
|
||||
<div class="flex flex-col items-center leading-none">
|
||||
<span>{{ t.display_name }}</span>
|
||||
<span class="text-[10px] text-muted-foreground">
|
||||
{{ configs[t.provider_type]
|
||||
? (configs[t.provider_type]?.is_enabled ? '点击禁用' : '点击启用')
|
||||
: '未配置' }}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
class="w-2 h-2 rounded-full"
|
||||
:class="configs[t.provider_type]?.is_enabled ? 'bg-green-500' : 'bg-gray-300'"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 无 Provider 提示 -->
|
||||
<div
|
||||
v-if="supportedTypes.length === 0 && !loading"
|
||||
class="text-center py-12 text-muted-foreground"
|
||||
>
|
||||
未发现可用的 OAuth Provider
|
||||
</div>
|
||||
|
||||
<!-- 配置表单 -->
|
||||
<CardSection
|
||||
v-if="selectedType"
|
||||
:title="selectedTypeMeta?.display_name || selectedType"
|
||||
:description="configs[selectedType]?.is_enabled ? '已启用' : '未配置'"
|
||||
>
|
||||
<template #actions>
|
||||
<div class="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
:disabled="saving || testing"
|
||||
@click="handleTest"
|
||||
>
|
||||
{{ testing ? '测试中...' : '测试' }}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
:disabled="saving"
|
||||
@click="handleSave"
|
||||
>
|
||||
{{ saving ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="space-y-6">
|
||||
<!-- 凭证配置 -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Client ID</Label>
|
||||
<Input
|
||||
v-model="form.client_id"
|
||||
class="mt-1"
|
||||
placeholder="client_id"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Client Secret</Label>
|
||||
<Input
|
||||
v-model="form.client_secret"
|
||||
masked
|
||||
class="mt-1"
|
||||
:placeholder="hasSecret ? '已设置(留空保持不变)' : '请输入 secret'"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 回调地址 -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Redirect URI(后端回调)</Label>
|
||||
<Input
|
||||
v-model="form.redirect_uri"
|
||||
class="mt-1"
|
||||
placeholder="http://localhost:8084/api/oauth/xxx/callback"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">前端回调页</Label>
|
||||
<Input
|
||||
v-model="form.frontend_callback_url"
|
||||
class="mt-1"
|
||||
placeholder="http://localhost:5173/auth/callback"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 高级选项(折叠) -->
|
||||
<details class="group">
|
||||
<summary class="cursor-pointer text-sm font-medium text-muted-foreground hover:text-foreground transition-colors">
|
||||
高级选项
|
||||
</summary>
|
||||
<div class="mt-4 space-y-4 pl-4 border-l-2 border-border">
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Scopes</Label>
|
||||
<Input
|
||||
v-model="form.scopes_input"
|
||||
class="mt-1"
|
||||
:placeholder="selectedTypeMeta?.default_scopes?.join(' ') || '留空使用默认值'"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
空格/逗号分隔;留空使用默认值
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Authorization URL</Label>
|
||||
<Input
|
||||
v-model="form.authorization_url_override"
|
||||
class="mt-1"
|
||||
:placeholder="selectedTypeMeta?.default_authorization_url || '默认'"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Token URL</Label>
|
||||
<Input
|
||||
v-model="form.token_url_override"
|
||||
class="mt-1"
|
||||
:placeholder="selectedTypeMeta?.default_token_url || '默认'"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Userinfo URL</Label>
|
||||
<Input
|
||||
v-model="form.userinfo_url_override"
|
||||
class="mt-1"
|
||||
:placeholder="selectedTypeMeta?.default_userinfo_url || '默认'"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Attribute Mapping</Label>
|
||||
<Textarea
|
||||
v-model="form.attribute_mapping_json"
|
||||
class="mt-1 font-mono text-xs"
|
||||
rows="3"
|
||||
placeholder='{"id": "user_id", "username": "login"}'
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label class="block text-sm font-medium">Extra Config</Label>
|
||||
<Textarea
|
||||
v-model="form.extra_config_json"
|
||||
class="mt-1 font-mono text-xs"
|
||||
rows="3"
|
||||
placeholder='{"min_trust_level": 1}'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<!-- 测试结果 -->
|
||||
<div
|
||||
v-if="lastTestResult"
|
||||
class="mt-6 rounded-lg border border-border p-4 text-sm"
|
||||
>
|
||||
<div class="font-medium mb-2">
|
||||
测试结果
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-4 text-xs">
|
||||
<div class="flex items-center gap-2">
|
||||
<span
|
||||
class="w-2 h-2 rounded-full"
|
||||
:class="lastTestResult.authorization_url_reachable ? 'bg-green-500' : 'bg-red-500'"
|
||||
/>
|
||||
<span class="text-muted-foreground">Authorization URL</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span
|
||||
class="w-2 h-2 rounded-full"
|
||||
:class="lastTestResult.token_url_reachable ? 'bg-green-500' : 'bg-red-500'"
|
||||
/>
|
||||
<span class="text-muted-foreground">Token URL</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span
|
||||
class="w-2 h-2 rounded-full"
|
||||
:class="lastTestResult.secret_status === 'likely_valid' ? 'bg-green-500' : lastTestResult.secret_status === 'invalid' ? 'bg-red-500' : 'bg-yellow-500'"
|
||||
/>
|
||||
<span class="text-muted-foreground">Secret: {{ lastTestResult.secret_status }}</span>
|
||||
</div>
|
||||
<span
|
||||
v-if="lastTestResult.details"
|
||||
class="text-muted-foreground"
|
||||
>
|
||||
{{ lastTestResult.details }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardSection>
|
||||
</div>
|
||||
</PageContainer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { oauthApi, type OAuthProviderAdminConfig, type OAuthProviderTestResponse, type SupportedOAuthType } from '@/api/oauth'
|
||||
import { PageContainer, PageHeader, CardSection } from '@/components/layout'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import Input from '@/components/ui/input.vue'
|
||||
import Label from '@/components/ui/label.vue'
|
||||
import Textarea from '@/components/ui/textarea.vue'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { useConfirm } from '@/composables/useConfirm'
|
||||
import { log } from '@/utils/logger'
|
||||
import { getErrorMessage, getErrorStatus, isApiError } from '@/types/api-error'
|
||||
|
||||
const { success, error: showError } = useToast()
|
||||
const { confirmWarning } = useConfirm()
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const testing = ref(false)
|
||||
|
||||
const supportedTypes = ref<SupportedOAuthType[]>([])
|
||||
const configs = ref<Record<string, OAuthProviderAdminConfig>>({})
|
||||
const selectedType = ref<string>('')
|
||||
const lastTestResult = ref<OAuthProviderTestResponse | null>(null)
|
||||
|
||||
const form = ref({
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
authorization_url_override: '',
|
||||
token_url_override: '',
|
||||
userinfo_url_override: '',
|
||||
scopes_input: '',
|
||||
redirect_uri: '',
|
||||
frontend_callback_url: '',
|
||||
attribute_mapping_json: '',
|
||||
extra_config_json: '',
|
||||
})
|
||||
|
||||
const hasSecret = computed(() => !!configs.value[selectedType.value]?.has_secret)
|
||||
const selectedTypeMeta = computed(() => supportedTypes.value.find((t) => t.provider_type === selectedType.value))
|
||||
|
||||
function defaultRedirectUri(providerType: string): string {
|
||||
return new URL(`/api/oauth/${providerType}/callback`, window.location.origin).toString()
|
||||
}
|
||||
|
||||
function defaultFrontendCallbackUrl(): string {
|
||||
return new URL('/auth/callback', window.location.origin).toString()
|
||||
}
|
||||
|
||||
function parseScopes(input: string): string[] | null {
|
||||
const raw = input.trim()
|
||||
if (!raw) return null
|
||||
const parts = raw.split(/[,\s]+/).map((s) => s.trim()).filter(Boolean)
|
||||
return parts.length ? parts : null
|
||||
}
|
||||
|
||||
function parseJsonOrNull(input: string): Record<string, any> | null {
|
||||
const raw = input.trim()
|
||||
if (!raw) return null
|
||||
return JSON.parse(raw)
|
||||
}
|
||||
|
||||
function handleTabClick(providerType: string) {
|
||||
// 如果点击的是当前选中的 Provider,且已配置,则切换启用状态
|
||||
if (selectedType.value === providerType && configs.value[providerType]) {
|
||||
toggleProviderEnabled(providerType, !configs.value[providerType].is_enabled)
|
||||
return
|
||||
}
|
||||
// 否则切换到该 Provider
|
||||
selectedType.value = providerType
|
||||
syncFormFromSelected()
|
||||
}
|
||||
|
||||
function syncFormFromSelected() {
|
||||
lastTestResult.value = null
|
||||
const cfg = configs.value[selectedType.value]
|
||||
|
||||
form.value = {
|
||||
client_id: cfg?.client_id || '',
|
||||
client_secret: '',
|
||||
authorization_url_override: cfg?.authorization_url_override || '',
|
||||
token_url_override: cfg?.token_url_override || '',
|
||||
userinfo_url_override: cfg?.userinfo_url_override || '',
|
||||
scopes_input: (cfg?.scopes || []).join(' '),
|
||||
redirect_uri: cfg?.redirect_uri || defaultRedirectUri(selectedType.value),
|
||||
frontend_callback_url: cfg?.frontend_callback_url || defaultFrontendCallbackUrl(),
|
||||
attribute_mapping_json: cfg?.attribute_mapping ? JSON.stringify(cfg.attribute_mapping, null, 2) : '',
|
||||
extra_config_json: cfg?.extra_config ? JSON.stringify(cfg.extra_config, null, 2) : '',
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleProviderEnabled(providerType: string, enabled: boolean, force = false) {
|
||||
const cfg = configs.value[providerType]
|
||||
if (!cfg) {
|
||||
showError('请先保存配置后再启用')
|
||||
return
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
const payload = {
|
||||
display_name: cfg.display_name,
|
||||
client_id: cfg.client_id,
|
||||
redirect_uri: cfg.redirect_uri,
|
||||
frontend_callback_url: cfg.frontend_callback_url,
|
||||
is_enabled: enabled,
|
||||
force,
|
||||
}
|
||||
await oauthApi.admin.upsertProviderConfig(providerType, payload)
|
||||
success(enabled ? '已启用' : '已禁用')
|
||||
await loadAll()
|
||||
} catch (err: unknown) {
|
||||
// 检查是否是需要确认的冲突错误
|
||||
if (isApiError(err) && getErrorStatus(err) === 409) {
|
||||
const errorData = err.response?.data?.error
|
||||
if (errorData?.type === 'confirmation_required') {
|
||||
const affectedCount = errorData.details?.affected_count ?? 0
|
||||
const confirmed = await confirmWarning(
|
||||
`禁用该 Provider 会导致 ${affectedCount} 个用户无法登录,是否继续?`,
|
||||
'确认禁用'
|
||||
)
|
||||
if (confirmed) {
|
||||
await toggleProviderEnabled(providerType, enabled, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
showError(getErrorMessage(err, '操作失败'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAll() {
|
||||
loading.value = true
|
||||
try {
|
||||
const [types, list] = await Promise.all([
|
||||
oauthApi.admin.getSupportedTypes(),
|
||||
oauthApi.admin.listProviderConfigs(),
|
||||
])
|
||||
supportedTypes.value = types
|
||||
configs.value = Object.fromEntries(list.map((c) => [c.provider_type, c]))
|
||||
|
||||
if (!selectedType.value && supportedTypes.value.length > 0) {
|
||||
selectedType.value = supportedTypes.value[0].provider_type
|
||||
}
|
||||
|
||||
if (selectedType.value) {
|
||||
syncFormFromSelected()
|
||||
}
|
||||
} catch (err: any) {
|
||||
log.error('加载 OAuth 配置失败:', err)
|
||||
showError(getErrorMessage(err, '加载失败'))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (!selectedType.value) return
|
||||
saving.value = true
|
||||
lastTestResult.value = null
|
||||
try {
|
||||
const typeMeta = supportedTypes.value.find((t) => t.provider_type === selectedType.value)
|
||||
const existingConfig = configs.value[selectedType.value]
|
||||
const payload = {
|
||||
display_name: typeMeta?.display_name || selectedType.value,
|
||||
client_id: form.value.client_id.trim(),
|
||||
client_secret: form.value.client_secret.trim() || undefined,
|
||||
authorization_url_override: form.value.authorization_url_override.trim() || null,
|
||||
token_url_override: form.value.token_url_override.trim() || null,
|
||||
userinfo_url_override: form.value.userinfo_url_override.trim() || null,
|
||||
scopes: parseScopes(form.value.scopes_input),
|
||||
redirect_uri: form.value.redirect_uri.trim(),
|
||||
frontend_callback_url: form.value.frontend_callback_url.trim(),
|
||||
attribute_mapping: parseJsonOrNull(form.value.attribute_mapping_json),
|
||||
extra_config: parseJsonOrNull(form.value.extra_config_json),
|
||||
is_enabled: existingConfig?.is_enabled || false,
|
||||
}
|
||||
|
||||
await oauthApi.admin.upsertProviderConfig(selectedType.value, payload)
|
||||
success('保存成功')
|
||||
await loadAll()
|
||||
} catch (err: any) {
|
||||
showError(getErrorMessage(err, '保存失败'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
form.value.client_secret = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTest() {
|
||||
if (!selectedType.value) return
|
||||
testing.value = true
|
||||
try {
|
||||
const testPayload = {
|
||||
client_id: form.value.client_id.trim(),
|
||||
client_secret: form.value.client_secret.trim() || undefined,
|
||||
authorization_url_override: form.value.authorization_url_override.trim() || null,
|
||||
token_url_override: form.value.token_url_override.trim() || null,
|
||||
redirect_uri: form.value.redirect_uri.trim(),
|
||||
}
|
||||
lastTestResult.value = await oauthApi.admin.testProviderConfig(selectedType.value, testPayload)
|
||||
success('测试完成')
|
||||
} catch (err: any) {
|
||||
showError(getErrorMessage(err, '测试失败'))
|
||||
} finally {
|
||||
testing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadAll()
|
||||
})
|
||||
</script>
|
||||
@@ -3,17 +3,7 @@
|
||||
<PageHeader
|
||||
title="系统设置"
|
||||
description="管理系统级别的配置和参数"
|
||||
>
|
||||
<template #actions>
|
||||
<Button
|
||||
:disabled="loading"
|
||||
class="shadow-none hover:shadow-none"
|
||||
@click="saveSystemConfig"
|
||||
>
|
||||
{{ loading ? '保存中...' : '保存所有配置' }}
|
||||
</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
/>
|
||||
|
||||
<div class="mt-6 space-y-6">
|
||||
<!-- 配置导出/导入 -->
|
||||
@@ -109,6 +99,15 @@
|
||||
title="基础配置"
|
||||
description="配置系统默认参数"
|
||||
>
|
||||
<template #actions>
|
||||
<Button
|
||||
size="sm"
|
||||
:disabled="basicConfigLoading || !hasBasicConfigChanges"
|
||||
@click="saveBasicConfig"
|
||||
>
|
||||
{{ basicConfigLoading ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</template>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<Label
|
||||
@@ -148,49 +147,27 @@
|
||||
0 表示不限制
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardSection>
|
||||
|
||||
<!-- 用户注册配置 -->
|
||||
<CardSection
|
||||
title="用户注册"
|
||||
description="控制用户注册和验证"
|
||||
>
|
||||
<div class="space-y-4">
|
||||
<div class="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="enable-registration"
|
||||
v-model:checked="systemConfig.enable_registration"
|
||||
/>
|
||||
<Label
|
||||
for="enable-registration"
|
||||
class="cursor-pointer"
|
||||
>
|
||||
开放用户注册
|
||||
</Label>
|
||||
<div class="flex items-center h-full">
|
||||
<div class="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="enable-registration"
|
||||
v-model:checked="systemConfig.enable_registration"
|
||||
/>
|
||||
<div>
|
||||
<Label
|
||||
for="enable-registration"
|
||||
class="cursor-pointer"
|
||||
>
|
||||
开放用户注册
|
||||
</Label>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
允许新用户自助注册账户
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="require-email-verification"
|
||||
v-model:checked="systemConfig.require_email_verification"
|
||||
/>
|
||||
<Label
|
||||
for="require-email-verification"
|
||||
class="cursor-pointer"
|
||||
>
|
||||
需要邮箱验证
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</CardSection>
|
||||
|
||||
<!-- 独立余额 Key 过期管理 -->
|
||||
<CardSection
|
||||
title="独立余额 Key 过期管理"
|
||||
description="独立余额 Key 的过期处理策略(普通用户 Key 不会过期)"
|
||||
>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div class="flex items-center h-full">
|
||||
<div class="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
@@ -205,7 +182,7 @@
|
||||
自动删除过期 Key
|
||||
</Label>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
关闭时仅禁用过期 Key,不会物理删除
|
||||
关闭时仅禁用过期的独立余额 Key
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -218,6 +195,15 @@
|
||||
title="日志记录"
|
||||
description="控制请求日志的记录方式和内容"
|
||||
>
|
||||
<template #actions>
|
||||
<Button
|
||||
size="sm"
|
||||
:disabled="logConfigLoading || !hasLogConfigChanges"
|
||||
@click="saveLogConfig"
|
||||
>
|
||||
{{ logConfigLoading ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</template>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<Label
|
||||
@@ -316,25 +302,36 @@
|
||||
title="日志清理策略"
|
||||
description="配置日志的分级保留和自动清理"
|
||||
>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div class="md:col-span-2">
|
||||
<div class="flex items-center space-x-2 mb-4">
|
||||
<Checkbox
|
||||
<template #actions>
|
||||
<div class="flex items-center gap-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<Switch
|
||||
id="enable-auto-cleanup"
|
||||
v-model:checked="systemConfig.enable_auto_cleanup"
|
||||
:model-value="systemConfig.enable_auto_cleanup"
|
||||
@update:model-value="handleAutoCleanupToggle"
|
||||
/>
|
||||
<Label
|
||||
for="enable-auto-cleanup"
|
||||
class="cursor-pointer"
|
||||
>
|
||||
启用自动清理任务
|
||||
</Label>
|
||||
<span class="text-xs text-muted-foreground ml-2">
|
||||
(每天凌晨执行)
|
||||
</span>
|
||||
<div>
|
||||
<Label
|
||||
for="enable-auto-cleanup"
|
||||
class="text-sm cursor-pointer"
|
||||
>
|
||||
启用自动清理
|
||||
</Label>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
每天凌晨执行
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
:disabled="cleanupConfigLoading || !hasCleanupConfigChanges"
|
||||
@click="saveCleanupConfig"
|
||||
>
|
||||
{{ cleanupConfigLoading ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
</template>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<Label
|
||||
for="detail-log-retention-days"
|
||||
@@ -814,6 +811,7 @@ import Button from '@/components/ui/button.vue'
|
||||
import Input from '@/components/ui/input.vue'
|
||||
import Label from '@/components/ui/label.vue'
|
||||
import Checkbox from '@/components/ui/checkbox.vue'
|
||||
import Switch from '@/components/ui/switch.vue'
|
||||
import Select from '@/components/ui/select.vue'
|
||||
import SelectTrigger from '@/components/ui/select-trigger.vue'
|
||||
import SelectValue from '@/components/ui/select-value.vue'
|
||||
@@ -833,9 +831,7 @@ interface SystemConfig {
|
||||
// 基础配置
|
||||
default_user_quota_usd: number
|
||||
rate_limit_per_minute: number
|
||||
// 用户注册
|
||||
enable_registration: boolean
|
||||
require_email_verification: boolean
|
||||
// 独立余额 Key 过期管理
|
||||
auto_delete_expired_keys: boolean
|
||||
// 日志记录
|
||||
@@ -853,7 +849,9 @@ interface SystemConfig {
|
||||
audit_log_retention_days: number
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const basicConfigLoading = ref(false)
|
||||
const logConfigLoading = ref(false)
|
||||
const cleanupConfigLoading = ref(false)
|
||||
const logLevelSelectOpen = ref(false)
|
||||
|
||||
// 导出/导入相关
|
||||
@@ -885,9 +883,7 @@ const systemConfig = ref<SystemConfig>({
|
||||
// 基础配置
|
||||
default_user_quota_usd: 10.0,
|
||||
rate_limit_per_minute: 0,
|
||||
// 用户注册
|
||||
enable_registration: false,
|
||||
require_email_verification: false,
|
||||
// 独立余额 Key 过期管理
|
||||
auto_delete_expired_keys: false,
|
||||
// 日志记录
|
||||
@@ -905,6 +901,42 @@ const systemConfig = ref<SystemConfig>({
|
||||
audit_log_retention_days: 30,
|
||||
})
|
||||
|
||||
// 原始配置值(用于检测变动)
|
||||
const originalConfig = ref<SystemConfig | null>(null)
|
||||
|
||||
// 检测各模块是否有变动
|
||||
const hasBasicConfigChanges = computed(() => {
|
||||
if (!originalConfig.value) return false
|
||||
return (
|
||||
systemConfig.value.default_user_quota_usd !== originalConfig.value.default_user_quota_usd ||
|
||||
systemConfig.value.rate_limit_per_minute !== originalConfig.value.rate_limit_per_minute ||
|
||||
systemConfig.value.enable_registration !== originalConfig.value.enable_registration ||
|
||||
systemConfig.value.auto_delete_expired_keys !== originalConfig.value.auto_delete_expired_keys
|
||||
)
|
||||
})
|
||||
|
||||
const hasLogConfigChanges = computed(() => {
|
||||
if (!originalConfig.value) return false
|
||||
return (
|
||||
systemConfig.value.request_log_level !== originalConfig.value.request_log_level ||
|
||||
systemConfig.value.max_request_body_size !== originalConfig.value.max_request_body_size ||
|
||||
systemConfig.value.max_response_body_size !== originalConfig.value.max_response_body_size ||
|
||||
JSON.stringify(systemConfig.value.sensitive_headers) !== JSON.stringify(originalConfig.value.sensitive_headers)
|
||||
)
|
||||
})
|
||||
|
||||
const hasCleanupConfigChanges = computed(() => {
|
||||
if (!originalConfig.value) return false
|
||||
return (
|
||||
systemConfig.value.detail_log_retention_days !== originalConfig.value.detail_log_retention_days ||
|
||||
systemConfig.value.compressed_log_retention_days !== originalConfig.value.compressed_log_retention_days ||
|
||||
systemConfig.value.header_retention_days !== originalConfig.value.header_retention_days ||
|
||||
systemConfig.value.log_retention_days !== originalConfig.value.log_retention_days ||
|
||||
systemConfig.value.cleanup_batch_size !== originalConfig.value.cleanup_batch_size ||
|
||||
systemConfig.value.audit_log_retention_days !== originalConfig.value.audit_log_retention_days
|
||||
)
|
||||
})
|
||||
|
||||
// 计算属性:KB 和 字节 之间的转换
|
||||
const maxRequestBodySizeKB = computed({
|
||||
get: () => Math.round(systemConfig.value.max_request_body_size / 1024),
|
||||
@@ -934,7 +966,7 @@ const sensitiveHeadersStr = computed({
|
||||
onMounted(async () => {
|
||||
await Promise.all([
|
||||
loadSystemConfig(),
|
||||
loadSystemVersion()
|
||||
loadSystemVersion(),
|
||||
])
|
||||
})
|
||||
|
||||
@@ -953,9 +985,7 @@ async function loadSystemConfig() {
|
||||
// 基础配置
|
||||
'default_user_quota_usd',
|
||||
'rate_limit_per_minute',
|
||||
// 用户注册
|
||||
'enable_registration',
|
||||
'require_email_verification',
|
||||
// 独立余额 Key 过期管理
|
||||
'auto_delete_expired_keys',
|
||||
// 日志记录
|
||||
@@ -983,17 +1013,18 @@ async function loadSystemConfig() {
|
||||
// 配置不存在时使用默认值,无需处理
|
||||
}
|
||||
}
|
||||
// 保存原始值用于变动检测
|
||||
originalConfig.value = JSON.parse(JSON.stringify(systemConfig.value))
|
||||
} catch (err) {
|
||||
error('加载系统配置失败')
|
||||
log.error('加载系统配置失败:', err)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSystemConfig() {
|
||||
loading.value = true
|
||||
async function saveBasicConfig() {
|
||||
basicConfigLoading.value = true
|
||||
try {
|
||||
const configItems = [
|
||||
// 基础配置
|
||||
{
|
||||
key: 'default_user_quota_usd',
|
||||
value: systemConfig.value.default_user_quota_usd,
|
||||
@@ -1004,24 +1035,43 @@ async function saveSystemConfig() {
|
||||
value: systemConfig.value.rate_limit_per_minute,
|
||||
description: '每分钟请求限制'
|
||||
},
|
||||
// 用户注册
|
||||
{
|
||||
key: 'enable_registration',
|
||||
value: systemConfig.value.enable_registration,
|
||||
description: '是否开放用户注册'
|
||||
},
|
||||
{
|
||||
key: 'require_email_verification',
|
||||
value: systemConfig.value.require_email_verification,
|
||||
description: '是否需要邮箱验证'
|
||||
},
|
||||
// 独立余额 Key 过期管理
|
||||
{
|
||||
key: 'auto_delete_expired_keys',
|
||||
value: systemConfig.value.auto_delete_expired_keys,
|
||||
description: '是否自动删除过期的API Key'
|
||||
},
|
||||
// 日志记录
|
||||
]
|
||||
|
||||
await Promise.all(
|
||||
configItems.map(item =>
|
||||
adminApi.updateSystemConfig(item.key, item.value, item.description)
|
||||
)
|
||||
)
|
||||
// 更新原始值
|
||||
if (originalConfig.value) {
|
||||
originalConfig.value.default_user_quota_usd = systemConfig.value.default_user_quota_usd
|
||||
originalConfig.value.rate_limit_per_minute = systemConfig.value.rate_limit_per_minute
|
||||
originalConfig.value.enable_registration = systemConfig.value.enable_registration
|
||||
originalConfig.value.auto_delete_expired_keys = systemConfig.value.auto_delete_expired_keys
|
||||
}
|
||||
success('基础配置已保存')
|
||||
} catch (err) {
|
||||
error('保存配置失败')
|
||||
log.error('保存基础配置失败:', err)
|
||||
} finally {
|
||||
basicConfigLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveLogConfig() {
|
||||
logConfigLoading.value = true
|
||||
try {
|
||||
const configItems = [
|
||||
{
|
||||
key: 'request_log_level',
|
||||
value: systemConfig.value.request_log_level,
|
||||
@@ -1042,12 +1092,51 @@ async function saveSystemConfig() {
|
||||
value: systemConfig.value.sensitive_headers,
|
||||
description: '敏感请求头列表'
|
||||
},
|
||||
// 日志清理
|
||||
{
|
||||
key: 'enable_auto_cleanup',
|
||||
value: systemConfig.value.enable_auto_cleanup,
|
||||
description: '是否启用自动清理任务'
|
||||
},
|
||||
]
|
||||
|
||||
await Promise.all(
|
||||
configItems.map(item =>
|
||||
adminApi.updateSystemConfig(item.key, item.value, item.description)
|
||||
)
|
||||
)
|
||||
// 更新原始值
|
||||
if (originalConfig.value) {
|
||||
originalConfig.value.request_log_level = systemConfig.value.request_log_level
|
||||
originalConfig.value.max_request_body_size = systemConfig.value.max_request_body_size
|
||||
originalConfig.value.max_response_body_size = systemConfig.value.max_response_body_size
|
||||
originalConfig.value.sensitive_headers = [...systemConfig.value.sensitive_headers]
|
||||
}
|
||||
success('日志配置已保存')
|
||||
} catch (err) {
|
||||
error('保存配置失败')
|
||||
log.error('保存日志配置失败:', err)
|
||||
} finally {
|
||||
logConfigLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAutoCleanupToggle(enabled: boolean) {
|
||||
const previousValue = systemConfig.value.enable_auto_cleanup
|
||||
systemConfig.value.enable_auto_cleanup = enabled
|
||||
try {
|
||||
await adminApi.updateSystemConfig(
|
||||
'enable_auto_cleanup',
|
||||
enabled,
|
||||
'是否启用自动清理任务'
|
||||
)
|
||||
success(enabled ? '已启用自动清理' : '已禁用自动清理')
|
||||
} catch (err) {
|
||||
error('保存配置失败')
|
||||
log.error('保存自动清理配置失败:', err)
|
||||
// 回滚状态
|
||||
systemConfig.value.enable_auto_cleanup = previousValue
|
||||
}
|
||||
}
|
||||
|
||||
async function saveCleanupConfig() {
|
||||
cleanupConfigLoading.value = true
|
||||
try {
|
||||
const configItems = [
|
||||
{
|
||||
key: 'detail_log_retention_days',
|
||||
value: systemConfig.value.detail_log_retention_days,
|
||||
@@ -1080,17 +1169,26 @@ async function saveSystemConfig() {
|
||||
},
|
||||
]
|
||||
|
||||
const promises = configItems.map(item =>
|
||||
adminApi.updateSystemConfig(item.key, item.value, item.description)
|
||||
await Promise.all(
|
||||
configItems.map(item =>
|
||||
adminApi.updateSystemConfig(item.key, item.value, item.description)
|
||||
)
|
||||
)
|
||||
|
||||
await Promise.all(promises)
|
||||
success('系统配置已保存')
|
||||
// 更新原始值
|
||||
if (originalConfig.value) {
|
||||
originalConfig.value.detail_log_retention_days = systemConfig.value.detail_log_retention_days
|
||||
originalConfig.value.compressed_log_retention_days = systemConfig.value.compressed_log_retention_days
|
||||
originalConfig.value.header_retention_days = systemConfig.value.header_retention_days
|
||||
originalConfig.value.log_retention_days = systemConfig.value.log_retention_days
|
||||
originalConfig.value.cleanup_batch_size = systemConfig.value.cleanup_batch_size
|
||||
originalConfig.value.audit_log_retention_days = systemConfig.value.audit_log_retention_days
|
||||
}
|
||||
success('日志清理配置已保存')
|
||||
} catch (err) {
|
||||
error('保存配置失败')
|
||||
log.error('保存配置失败:', err)
|
||||
log.error('保存日志清理配置失败:', err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
cleanupConfigLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
119
frontend/src/views/public/AuthCallback.vue
Normal file
119
frontend/src/views/public/AuthCallback.vue
Normal file
@@ -0,0 +1,119 @@
|
||||
<template>
|
||||
<div class="min-h-screen flex items-center justify-center px-6">
|
||||
<Card class="w-full max-w-md p-6 space-y-2">
|
||||
<h1 class="text-lg font-semibold text-foreground">
|
||||
正在处理认证...
|
||||
</h1>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
{{ hint }}
|
||||
</p>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import Card from '@/components/ui/card.vue'
|
||||
import apiClient from '@/api/client'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
const { success, error: showError } = useToast()
|
||||
|
||||
const hint = ref('请稍候...')
|
||||
|
||||
function consumeRedirectPath(): string | null {
|
||||
const redirectPath = sessionStorage.getItem('redirectPath')
|
||||
if (redirectPath) {
|
||||
sessionStorage.removeItem('redirectPath')
|
||||
return redirectPath
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function clearUrlState() {
|
||||
// 清理 fragment,避免刷新时重复处理
|
||||
// 同时清理 query(oauth_bound / error_code / error_detail)
|
||||
const newUrl = window.location.pathname
|
||||
window.history.replaceState({}, document.title, newUrl)
|
||||
}
|
||||
|
||||
function errorMessageFromCode(code: string): string {
|
||||
const map: Record<string, string> = {
|
||||
authorization_denied: '你已取消授权',
|
||||
provider_disabled: '该 OAuth Provider 已被禁用',
|
||||
provider_unavailable: 'OAuth Provider 不可用',
|
||||
invalid_callback: '回调参数无效',
|
||||
invalid_state: '登录状态已失效,请重试',
|
||||
token_exchange_failed: '令牌兑换失败',
|
||||
userinfo_fetch_failed: '获取用户信息失败',
|
||||
email_exists_local: '该邮箱已存在,请先登录后再绑定 OAuth',
|
||||
email_is_ldap: '该邮箱属于 LDAP 账号,请使用 LDAP 登录',
|
||||
email_is_oauth: '该邮箱已关联其他 OAuth 账号,请使用原账号登录',
|
||||
registration_disabled: '系统未开放注册,无法创建新账号',
|
||||
oauth_already_bound: '该第三方账号已被其他用户绑定',
|
||||
already_bound_provider: '你已绑定该 Provider',
|
||||
last_oauth_binding: '解绑失败:至少需要保留一个 OAuth 绑定',
|
||||
last_login_method: '解绑失败:解绑后将无法登录',
|
||||
ldap_no_oauth: 'LDAP 用户不支持 OAuth 绑定',
|
||||
}
|
||||
return map[code] || '认证失败,请重试'
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// 1) 绑定成功提示
|
||||
const oauthBound = route.query.oauth_bound
|
||||
if (typeof oauthBound === 'string' && oauthBound) {
|
||||
success(`已绑定 ${oauthBound}`)
|
||||
clearUrlState()
|
||||
const redirectPath = consumeRedirectPath()
|
||||
await router.replace(redirectPath || '/dashboard/settings')
|
||||
return
|
||||
}
|
||||
|
||||
// 2) 错误提示
|
||||
const errorCode = route.query.error_code
|
||||
if (typeof errorCode === 'string' && errorCode) {
|
||||
showError(errorMessageFromCode(errorCode))
|
||||
clearUrlState()
|
||||
const redirectPath = consumeRedirectPath()
|
||||
await router.replace(redirectPath || '/')
|
||||
return
|
||||
}
|
||||
|
||||
// 3) 登录成功:解析 fragment token
|
||||
const hash = window.location.hash.startsWith('#') ? window.location.hash.slice(1) : window.location.hash
|
||||
const params = new URLSearchParams(hash)
|
||||
const accessToken = params.get('access_token')
|
||||
const refreshToken = params.get('refresh_token')
|
||||
|
||||
clearUrlState()
|
||||
|
||||
if (!accessToken) {
|
||||
showError('未获取到访问令牌')
|
||||
await router.replace('/')
|
||||
return
|
||||
}
|
||||
|
||||
hint.value = '正在写入登录态...'
|
||||
apiClient.setToken(accessToken)
|
||||
if (refreshToken) {
|
||||
localStorage.setItem('refresh_token', refreshToken)
|
||||
}
|
||||
|
||||
authStore.syncToken()
|
||||
|
||||
hint.value = '正在获取用户信息...'
|
||||
await authStore.fetchCurrentUser()
|
||||
|
||||
success('登录成功')
|
||||
|
||||
const redirectPath = consumeRedirectPath()
|
||||
const target = redirectPath || (authStore.user?.role === 'admin' ? '/admin/dashboard' : '/dashboard')
|
||||
await router.replace(target)
|
||||
})
|
||||
</script>
|
||||
@@ -9,13 +9,23 @@
|
||||
<div class="lg:col-span-2 space-y-6">
|
||||
<!-- 基本信息 -->
|
||||
<Card class="p-6">
|
||||
<h3 class="text-lg font-medium text-foreground mb-4">
|
||||
基本信息
|
||||
</h3>
|
||||
<form
|
||||
class="space-y-4"
|
||||
@submit.prevent="updateProfile"
|
||||
>
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-lg font-medium text-foreground">
|
||||
基本信息
|
||||
</h3>
|
||||
<Button
|
||||
type="submit"
|
||||
:disabled="savingProfile || !hasProfileChanges"
|
||||
class="shadow-none hover:shadow-none"
|
||||
>
|
||||
{{ savingProfile ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label for="username">用户名</Label>
|
||||
@@ -26,11 +36,11 @@
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label for="email">邮箱</Label>
|
||||
<Label for="avatar">头像 URL</Label>
|
||||
<Input
|
||||
id="email"
|
||||
v-model="profileForm.email"
|
||||
type="email"
|
||||
id="avatar"
|
||||
v-model="preferencesForm.avatar_url"
|
||||
type="url"
|
||||
class="mt-1"
|
||||
/>
|
||||
</div>
|
||||
@@ -46,42 +56,53 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label for="avatar">头像 URL</Label>
|
||||
<Input
|
||||
id="avatar"
|
||||
v-model="preferencesForm.avatar_url"
|
||||
type="url"
|
||||
class="mt-1"
|
||||
/>
|
||||
<p class="mt-1 text-sm text-muted-foreground">
|
||||
输入头像图片的 URL 地址
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
:disabled="savingProfile"
|
||||
class="shadow-none hover:shadow-none"
|
||||
<!-- 邮箱字段:当系统配置了邮箱服务或用户已有邮箱时显示 -->
|
||||
<div
|
||||
v-if="emailConfigured || profileForm.email"
|
||||
class="grid grid-cols-1 md:grid-cols-2 gap-4"
|
||||
>
|
||||
{{ savingProfile ? '保存中...' : '保存修改' }}
|
||||
</Button>
|
||||
<div>
|
||||
<Label for="email">邮箱</Label>
|
||||
<Input
|
||||
id="email"
|
||||
v-model="profileForm.email"
|
||||
type="email"
|
||||
class="mt-1"
|
||||
:disabled="!emailConfigured"
|
||||
/>
|
||||
<p
|
||||
v-if="!emailConfigured && profileForm.email"
|
||||
class="mt-1 text-xs text-muted-foreground"
|
||||
>
|
||||
邮箱服务未配置,暂不可修改
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
<!-- 修改密码 (LDAP 用户不显示) -->
|
||||
<!-- 密码设置(LDAP 用户不显示) -->
|
||||
<Card
|
||||
v-if="profile?.auth_source !== 'ldap'"
|
||||
class="p-6"
|
||||
>
|
||||
<h3 class="text-lg font-medium text-foreground mb-4">
|
||||
修改密码
|
||||
</h3>
|
||||
<form
|
||||
class="space-y-4"
|
||||
@submit.prevent="changePassword"
|
||||
>
|
||||
<div>
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-lg font-medium text-foreground">
|
||||
{{ profile?.has_password ? '修改密码' : '设置密码' }}
|
||||
</h3>
|
||||
<Button
|
||||
type="submit"
|
||||
:disabled="changingPassword || !hasPasswordChanges"
|
||||
class="shadow-none hover:shadow-none"
|
||||
>
|
||||
{{ changingPassword ? '保存中...' : '保存' }}
|
||||
</Button>
|
||||
</div>
|
||||
<div v-if="profile?.has_password">
|
||||
<Label for="old-password">当前密码</Label>
|
||||
<Input
|
||||
id="old-password"
|
||||
@@ -91,7 +112,7 @@
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label for="new-password">新密码</Label>
|
||||
<Label for="new-password">{{ profile?.has_password ? '新密码' : '密码' }}</Label>
|
||||
<Input
|
||||
id="new-password"
|
||||
v-model="passwordForm.new_password"
|
||||
@@ -100,7 +121,7 @@
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label for="confirm-password">确认新密码</Label>
|
||||
<Label for="confirm-password">确认{{ profile?.has_password ? '新' : '' }}密码</Label>
|
||||
<Input
|
||||
id="confirm-password"
|
||||
v-model="passwordForm.confirm_password"
|
||||
@@ -108,16 +129,95 @@
|
||||
class="mt-1"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="submit"
|
||||
:disabled="changingPassword"
|
||||
class="shadow-none hover:shadow-none"
|
||||
>
|
||||
{{ changingPassword ? '修改中...' : '修改密码' }}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
<!-- OAuth 绑定 -->
|
||||
<Card class="p-6">
|
||||
<h3 class="text-lg font-medium text-foreground mb-4">
|
||||
OAuth 绑定
|
||||
</h3>
|
||||
|
||||
<div
|
||||
v-if="profile?.auth_source === 'ldap'"
|
||||
class="text-sm text-muted-foreground"
|
||||
>
|
||||
LDAP 用户不支持 OAuth 绑定
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="oauthUnavailable"
|
||||
class="text-sm text-muted-foreground"
|
||||
>
|
||||
OAuth 模块未启用或暂不可用
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="space-y-4"
|
||||
>
|
||||
<!-- 合并已绑定和可绑定为卡片网格 -->
|
||||
<div
|
||||
v-if="oauthLinks.length === 0 && bindableProviders.length === 0"
|
||||
class="text-sm text-muted-foreground"
|
||||
>
|
||||
暂无可用的 OAuth Provider
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="grid grid-cols-1 sm:grid-cols-2 gap-3"
|
||||
>
|
||||
<!-- 已绑定的 Provider -->
|
||||
<div
|
||||
v-for="link in oauthLinks"
|
||||
:key="link.provider_type"
|
||||
class="flex items-center justify-between gap-3 rounded-lg border border-border bg-muted/30 p-4"
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-medium truncate">
|
||||
{{ link.display_name }}
|
||||
</div>
|
||||
<div class="text-xs text-muted-foreground truncate">
|
||||
{{ link.provider_username || link.provider_email || '已绑定' }}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="oauthActionLoading"
|
||||
@click="handleUnbind(link.provider_type)"
|
||||
>
|
||||
解绑
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 可绑定的 Provider -->
|
||||
<div
|
||||
v-for="p in bindableProviders"
|
||||
:key="p.provider_type"
|
||||
class="flex items-center justify-between gap-3 rounded-lg border border-dashed border-border p-4 hover:border-primary/50 transition-colors"
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-medium truncate">
|
||||
{{ p.display_name }}
|
||||
</div>
|
||||
<div class="text-xs text-muted-foreground">
|
||||
未绑定
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="oauthActionLoading"
|
||||
@click="handleBind(p.provider_type)"
|
||||
>
|
||||
绑定
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<!-- 偏好设置 -->
|
||||
<Card class="p-6">
|
||||
<h3 class="text-lg font-medium text-foreground mb-4">
|
||||
@@ -192,7 +292,11 @@
|
||||
通知设置
|
||||
</h4>
|
||||
<div class="space-y-3">
|
||||
<div class="flex items-center justify-between py-2 border-b border-border/40 last:border-0">
|
||||
<!-- 邮件通知:仅当系统配置了邮箱服务时显示 -->
|
||||
<div
|
||||
v-if="emailConfigured"
|
||||
class="flex items-center justify-between py-2 border-b border-border/40 last:border-0"
|
||||
>
|
||||
<div class="flex-1">
|
||||
<Label
|
||||
for="email-notifications"
|
||||
@@ -322,9 +426,12 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { meApi, type Profile } from '@/api/me'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { oauthApi, type OAuthLinkInfo, type OAuthProviderInfo } from '@/api/oauth'
|
||||
import { useDarkMode, type ThemeMode } from '@/composables/useDarkMode'
|
||||
import Card from '@/components/ui/card.vue'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
@@ -340,9 +447,12 @@ import SelectItem from '@/components/ui/select-item.vue'
|
||||
import Switch from '@/components/ui/switch.vue'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { formatCurrency } from '@/utils/format'
|
||||
import { getApiUrl } from '@/utils/url'
|
||||
import { log } from '@/utils/logger'
|
||||
import { getErrorMessage } from '@/types/api-error'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const route = useRoute()
|
||||
const { success, error: showError } = useToast()
|
||||
const { setThemeMode } = useDarkMode()
|
||||
|
||||
@@ -377,6 +487,38 @@ const changingPassword = ref(false)
|
||||
const themeSelectOpen = ref(false)
|
||||
const languageSelectOpen = ref(false)
|
||||
|
||||
const oauthUnavailable = ref(false)
|
||||
const oauthActionLoading = ref(false)
|
||||
const oauthLinks = ref<OAuthLinkInfo[]>([])
|
||||
const bindableProviders = ref<OAuthProviderInfo[]>([])
|
||||
const emailConfigured = ref(false) // 系统是否配置了邮箱服务
|
||||
|
||||
// 原始值,用于检测是否有修改
|
||||
const originalProfileForm = ref({ email: '', username: '' })
|
||||
const originalPreferencesForm = ref({ avatar_url: '', bio: '' })
|
||||
|
||||
// 检测基本信息是否有修改
|
||||
const hasProfileChanges = computed(() => {
|
||||
return (
|
||||
profileForm.value.username !== originalProfileForm.value.username ||
|
||||
profileForm.value.email !== originalProfileForm.value.email ||
|
||||
preferencesForm.value.avatar_url !== originalPreferencesForm.value.avatar_url ||
|
||||
preferencesForm.value.bio !== originalPreferencesForm.value.bio
|
||||
)
|
||||
})
|
||||
|
||||
// 检测密码表单是否有内容
|
||||
const hasPasswordChanges = computed(() => {
|
||||
const hasPassword = profile.value?.has_password
|
||||
if (hasPassword) {
|
||||
// 已有密码:需要填写旧密码和新密码
|
||||
return !!(passwordForm.value.old_password && passwordForm.value.new_password && passwordForm.value.confirm_password)
|
||||
} else {
|
||||
// 设置密码:只需要填写新密码
|
||||
return !!(passwordForm.value.new_password && passwordForm.value.confirm_password)
|
||||
}
|
||||
})
|
||||
|
||||
function handleThemeChange(value: string) {
|
||||
preferencesForm.value.theme = value
|
||||
themeSelectOpen.value = false
|
||||
@@ -395,21 +537,86 @@ function handleLanguageChange(value: string) {
|
||||
onMounted(async () => {
|
||||
await loadProfile()
|
||||
await loadPreferences()
|
||||
await loadOAuthBindings()
|
||||
await loadEmailConfigured()
|
||||
})
|
||||
|
||||
async function loadEmailConfigured() {
|
||||
try {
|
||||
const settings = await authApi.getRegistrationSettings()
|
||||
emailConfigured.value = !!settings.email_configured
|
||||
} catch {
|
||||
emailConfigured.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadProfile() {
|
||||
try {
|
||||
profile.value = await meApi.getProfile()
|
||||
profileForm.value = {
|
||||
email: profile.value.email,
|
||||
email: profile.value.email || '',
|
||||
username: profile.value.username
|
||||
}
|
||||
// 保存原始值
|
||||
originalProfileForm.value = { ...profileForm.value }
|
||||
} catch (error) {
|
||||
log.error('加载个人信息失败:', error)
|
||||
showError('加载个人信息失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOAuthBindings() {
|
||||
oauthUnavailable.value = false
|
||||
oauthLinks.value = []
|
||||
bindableProviders.value = []
|
||||
|
||||
// profile 加载失败时跳过
|
||||
if (!profile.value) {
|
||||
oauthUnavailable.value = true
|
||||
return
|
||||
}
|
||||
|
||||
// LDAP 用户不支持绑定
|
||||
if (profile.value.auth_source === 'ldap') {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const [links, providers] = await Promise.all([
|
||||
oauthApi.getMyLinks(),
|
||||
oauthApi.getBindableProviders(),
|
||||
])
|
||||
oauthLinks.value = links
|
||||
bindableProviders.value = providers
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 503) {
|
||||
oauthUnavailable.value = true
|
||||
return
|
||||
}
|
||||
log.error('加载 OAuth 绑定信息失败:', err)
|
||||
oauthUnavailable.value = true
|
||||
}
|
||||
}
|
||||
|
||||
function handleBind(providerType: string) {
|
||||
// 保存返回路径(OAuth callback 会读取)
|
||||
sessionStorage.setItem('redirectPath', route.fullPath)
|
||||
window.location.href = getApiUrl(`/api/user/oauth/${providerType}/bind`)
|
||||
}
|
||||
|
||||
async function handleUnbind(providerType: string) {
|
||||
oauthActionLoading.value = true
|
||||
try {
|
||||
await oauthApi.unbind(providerType)
|
||||
success('解绑成功')
|
||||
await loadOAuthBindings()
|
||||
} catch (err) {
|
||||
showError(getErrorMessage(err, '解绑失败'))
|
||||
} finally {
|
||||
oauthActionLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPreferences() {
|
||||
try {
|
||||
const prefs = await meApi.getPreferences()
|
||||
@@ -432,6 +639,12 @@ async function loadPreferences() {
|
||||
}
|
||||
}
|
||||
|
||||
// 保存原始值
|
||||
originalPreferencesForm.value = {
|
||||
avatar_url: preferencesForm.value.avatar_url,
|
||||
bio: preferencesForm.value.bio
|
||||
}
|
||||
|
||||
// 如果本地主题和服务端不一致,同步到服务端(静默更新,不提示用户)
|
||||
const serverTheme = prefs.theme || 'light'
|
||||
if (localTheme !== serverTheme) {
|
||||
@@ -463,12 +676,18 @@ async function updateProfile() {
|
||||
}
|
||||
})
|
||||
|
||||
// 更新原始值
|
||||
originalProfileForm.value = { ...profileForm.value }
|
||||
originalPreferencesForm.value = {
|
||||
avatar_url: preferencesForm.value.avatar_url,
|
||||
bio: preferencesForm.value.bio
|
||||
}
|
||||
|
||||
success('个人信息已更新')
|
||||
await loadProfile()
|
||||
authStore.fetchCurrentUser()
|
||||
} catch (error) {
|
||||
log.error('更新个人信息失败:', error)
|
||||
showError('更新个人信息失败')
|
||||
} catch (err) {
|
||||
log.error('更新个人信息失败:', err)
|
||||
showError(getErrorMessage(err), '更新个人信息失败')
|
||||
} finally {
|
||||
savingProfile.value = false
|
||||
}
|
||||
@@ -476,30 +695,37 @@ async function updateProfile() {
|
||||
|
||||
async function changePassword() {
|
||||
if (passwordForm.value.new_password !== passwordForm.value.confirm_password) {
|
||||
showError('两次输入的密码不一致')
|
||||
showError('两次输入的密码不一致', '密码错误')
|
||||
return
|
||||
}
|
||||
|
||||
if (passwordForm.value.new_password.length < 6) {
|
||||
showError('密码长度至少6位')
|
||||
showError('密码长度至少6位', '密码错误')
|
||||
return
|
||||
}
|
||||
|
||||
const isSettingPassword = !profile.value?.has_password
|
||||
changingPassword.value = true
|
||||
try {
|
||||
await meApi.changePassword({
|
||||
old_password: passwordForm.value.old_password,
|
||||
old_password: isSettingPassword ? undefined : passwordForm.value.old_password,
|
||||
new_password: passwordForm.value.new_password
|
||||
})
|
||||
success('密码修改成功')
|
||||
success(isSettingPassword ? '密码设置成功' : '密码修改成功')
|
||||
passwordForm.value = {
|
||||
old_password: '',
|
||||
new_password: '',
|
||||
confirm_password: ''
|
||||
}
|
||||
} catch (error) {
|
||||
log.error('修改密码失败:', error)
|
||||
showError('修改密码失败,请检查当前密码是否正确')
|
||||
// 刷新 profile 以更新 has_password 状态
|
||||
if (isSettingPassword) {
|
||||
await loadProfile()
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('修改密码失败:', err)
|
||||
const title = isSettingPassword ? '密码设置失败' : '密码修改失败'
|
||||
const defaultMsg = isSettingPassword ? '请稍后重试' : '请检查当前密码是否正确'
|
||||
showError(getErrorMessage(err, defaultMsg), title)
|
||||
} finally {
|
||||
changingPassword.value = false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user