mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 01:10:23 +08:00
feat: 添加 OAuth 认证支持及相关改进
- 新增 OAuth 模块,支持 LinuxDo/GitHub/Google 等第三方登录 - 用户邮箱改为可选字段,支持无邮箱注册 - 新增模块配置验证状态 (config_validated/config_error) - 系统设置界面改为分块独立保存 - 用户设置新增 OAuth 绑定管理和首次密码设置 - 登录界面支持 OAuth 按钮展示 - 邮箱验证设置移至邮件设置页面
This commit is contained in:
@@ -65,14 +65,14 @@ export interface VerificationStatusResponse {
|
||||
}
|
||||
|
||||
export interface RegisterRequest {
|
||||
email: string
|
||||
email?: string
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface RegisterResponse {
|
||||
user_id: string
|
||||
email: string
|
||||
email?: string
|
||||
username: string
|
||||
message: string
|
||||
}
|
||||
@@ -80,6 +80,7 @@ export interface RegisterResponse {
|
||||
export interface RegistrationSettingsResponse {
|
||||
enable_registration: boolean
|
||||
require_email_verification: boolean
|
||||
email_configured: boolean
|
||||
}
|
||||
|
||||
export interface AuthSettingsResponse {
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { ActivityHeatmap } from '@/types/activity'
|
||||
|
||||
export interface Profile {
|
||||
id: string // UUID
|
||||
email: string
|
||||
email?: string | null
|
||||
username: string
|
||||
role: string
|
||||
is_active: boolean
|
||||
@@ -13,7 +13,8 @@ export interface Profile {
|
||||
created_at: string
|
||||
updated_at?: string
|
||||
last_login_at?: string
|
||||
auth_source?: 'local' | 'ldap'
|
||||
auth_source?: 'local' | 'ldap' | 'oauth'
|
||||
has_password?: boolean
|
||||
preferences?: UserPreferences
|
||||
}
|
||||
|
||||
@@ -132,7 +133,7 @@ export interface ApiKey {
|
||||
// 不再需要 ProviderBinding 接口
|
||||
|
||||
export interface ChangePasswordRequest {
|
||||
old_password: string
|
||||
old_password?: string // 可选:首次设置密码时不需要
|
||||
new_password: string
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ export interface ModuleStatus {
|
||||
available: boolean
|
||||
enabled: boolean
|
||||
active: boolean
|
||||
config_validated: boolean
|
||||
config_error: string | null
|
||||
display_name: string
|
||||
description: string
|
||||
category: 'auth' | 'monitoring' | 'security' | 'integration'
|
||||
|
||||
136
frontend/src/api/oauth.ts
Normal file
136
frontend/src/api/oauth.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import apiClient from './client'
|
||||
|
||||
export interface OAuthProviderInfo {
|
||||
provider_type: string
|
||||
display_name: string
|
||||
}
|
||||
|
||||
export interface OAuthProvidersResponse {
|
||||
providers: OAuthProviderInfo[]
|
||||
}
|
||||
|
||||
export interface OAuthLinkInfo {
|
||||
provider_type: string
|
||||
display_name: string
|
||||
provider_username?: string | null
|
||||
provider_email?: string | null
|
||||
linked_at?: string | null
|
||||
last_login_at?: string | null
|
||||
provider_enabled?: boolean
|
||||
}
|
||||
|
||||
export interface OAuthLinksResponse {
|
||||
links: OAuthLinkInfo[]
|
||||
}
|
||||
|
||||
// Admin
|
||||
export interface SupportedOAuthType {
|
||||
provider_type: string
|
||||
display_name: string
|
||||
default_authorization_url: string
|
||||
default_token_url: string
|
||||
default_userinfo_url: string
|
||||
default_scopes: string[]
|
||||
}
|
||||
|
||||
export interface OAuthProviderAdminConfig {
|
||||
provider_type: string
|
||||
display_name: string
|
||||
client_id: string
|
||||
has_secret: boolean
|
||||
authorization_url_override?: string | null
|
||||
token_url_override?: string | null
|
||||
userinfo_url_override?: string | null
|
||||
scopes?: string[] | null
|
||||
redirect_uri: string
|
||||
frontend_callback_url: string
|
||||
attribute_mapping?: Record<string, any> | null
|
||||
extra_config?: Record<string, any> | null
|
||||
is_enabled: boolean
|
||||
}
|
||||
|
||||
export interface OAuthProviderUpsertRequest {
|
||||
display_name: string
|
||||
client_id: string
|
||||
client_secret?: string
|
||||
authorization_url_override?: string | null
|
||||
token_url_override?: string | null
|
||||
userinfo_url_override?: string | null
|
||||
scopes?: string[] | null
|
||||
redirect_uri: string
|
||||
frontend_callback_url: string
|
||||
attribute_mapping?: Record<string, any> | null
|
||||
extra_config?: Record<string, any> | null
|
||||
is_enabled: boolean
|
||||
force?: boolean
|
||||
}
|
||||
|
||||
export interface OAuthProviderTestResponse {
|
||||
authorization_url_reachable: boolean
|
||||
token_url_reachable: boolean
|
||||
secret_status: 'likely_valid' | 'invalid' | 'unknown' | 'not_provided' | string
|
||||
details?: string
|
||||
}
|
||||
|
||||
export interface OAuthProviderTestRequest {
|
||||
client_id: string
|
||||
client_secret?: string
|
||||
authorization_url_override?: string | null
|
||||
token_url_override?: string | null
|
||||
redirect_uri: string
|
||||
}
|
||||
|
||||
export const oauthApi = {
|
||||
async getProviders(): Promise<OAuthProviderInfo[]> {
|
||||
const response = await apiClient.get<OAuthProvidersResponse>('/api/oauth/providers')
|
||||
return response.data.providers || []
|
||||
},
|
||||
|
||||
async getBindableProviders(): Promise<OAuthProviderInfo[]> {
|
||||
const response = await apiClient.get<OAuthProvidersResponse>('/api/user/oauth/bindable-providers')
|
||||
return response.data.providers || []
|
||||
},
|
||||
|
||||
async getMyLinks(): Promise<OAuthLinkInfo[]> {
|
||||
const response = await apiClient.get<OAuthLinksResponse>('/api/user/oauth/links')
|
||||
return response.data.links || []
|
||||
},
|
||||
|
||||
async unbind(providerType: string): Promise<{ message: string }> {
|
||||
const response = await apiClient.delete<{ message: string }>(`/api/user/oauth/${providerType}`)
|
||||
return response.data
|
||||
},
|
||||
|
||||
admin: {
|
||||
async getSupportedTypes(): Promise<SupportedOAuthType[]> {
|
||||
const response = await apiClient.get<SupportedOAuthType[]>('/api/admin/oauth/supported-types')
|
||||
return response.data || []
|
||||
},
|
||||
|
||||
async listProviderConfigs(): Promise<OAuthProviderAdminConfig[]> {
|
||||
const response = await apiClient.get<OAuthProviderAdminConfig[]>('/api/admin/oauth/providers')
|
||||
return response.data || []
|
||||
},
|
||||
|
||||
async getProviderConfig(providerType: string): Promise<OAuthProviderAdminConfig> {
|
||||
const response = await apiClient.get<OAuthProviderAdminConfig>(`/api/admin/oauth/providers/${providerType}`)
|
||||
return response.data
|
||||
},
|
||||
|
||||
async upsertProviderConfig(providerType: string, payload: OAuthProviderUpsertRequest): Promise<OAuthProviderAdminConfig> {
|
||||
const response = await apiClient.put<OAuthProviderAdminConfig>(`/api/admin/oauth/providers/${providerType}`, payload)
|
||||
return response.data
|
||||
},
|
||||
|
||||
async deleteProviderConfig(providerType: string): Promise<{ message: string }> {
|
||||
const response = await apiClient.delete<{ message: string }>(`/api/admin/oauth/providers/${providerType}`)
|
||||
return response.data
|
||||
},
|
||||
|
||||
async testProviderConfig(providerType: string, payload: OAuthProviderTestRequest): Promise<OAuthProviderTestResponse> {
|
||||
const response = await apiClient.post<OAuthProviderTestResponse>(`/api/admin/oauth/providers/${providerType}/test`, payload)
|
||||
return response.data
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,75 +1,111 @@
|
||||
<template>
|
||||
<Dialog
|
||||
v-model="isOpen"
|
||||
size="lg"
|
||||
size="md"
|
||||
no-padding
|
||||
>
|
||||
<div class="space-y-6">
|
||||
<div class="px-6 py-6 sm:px-8 sm:py-8">
|
||||
<!-- Logo 和标题 -->
|
||||
<div class="flex flex-col items-center text-center">
|
||||
<div class="mb-4 rounded-3xl border border-primary/30 dark:border-[#cc785c]/30 bg-primary/5 dark:bg-transparent p-4 shadow-inner shadow-white/40 dark:shadow-[#cc785c]/10">
|
||||
<img
|
||||
src="/aether_adaptive.svg"
|
||||
alt="Logo"
|
||||
class="h-16 w-16"
|
||||
>
|
||||
</div>
|
||||
<h2 class="text-2xl font-semibold text-slate-900 dark:text-white">
|
||||
欢迎回来
|
||||
<div class="flex flex-col items-center text-center mb-6">
|
||||
<img
|
||||
src="/aether_adaptive.svg"
|
||||
alt="Aether"
|
||||
class="h-10 w-10 mb-3"
|
||||
>
|
||||
<h2 class="text-xl font-semibold text-foreground">
|
||||
登录到 Aether
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<!-- Demo 模式提示 -->
|
||||
<div
|
||||
v-if="isDemo"
|
||||
class="rounded-lg border border-primary/20 dark:border-primary/30 bg-primary/5 dark:bg-primary/10 p-4"
|
||||
class="rounded-lg border border-primary/20 bg-primary/5 p-3 mb-5"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="flex-shrink-0 text-primary dark:text-primary/90">
|
||||
<svg
|
||||
class="h-5 w-5"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
<p class="text-xs font-medium text-foreground mb-2">
|
||||
演示模式
|
||||
</p>
|
||||
<div class="space-y-1.5">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors w-full"
|
||||
@click="fillDemoAccount('admin')"
|
||||
>
|
||||
<span class="inline-flex items-center justify-center w-4 h-4 rounded bg-primary/20 text-primary text-[10px] font-bold">A</span>
|
||||
<span>admin@demo.aether.io / demo123</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors w-full"
|
||||
@click="fillDemoAccount('user')"
|
||||
>
|
||||
<span class="inline-flex items-center justify-center w-4 h-4 rounded bg-muted text-muted-foreground text-[10px] font-bold">U</span>
|
||||
<span>user@demo.aether.io / demo123</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- OAuth 登录按钮 -->
|
||||
<div
|
||||
v-if="oauthProviders.length > 0"
|
||||
class="mb-5"
|
||||
>
|
||||
<!-- 单个 provider: 完整按钮 -->
|
||||
<div
|
||||
v-if="oauthProviders.length === 1"
|
||||
class="space-y-2"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="oauth-btn"
|
||||
@click="handleOAuthLogin(oauthProviders[0].provider_type)"
|
||||
>
|
||||
<span
|
||||
class="oauth-icon"
|
||||
v-html="getOAuthIcon(oauthProviders[0].provider_type)"
|
||||
/>
|
||||
<span>使用 {{ oauthProviders[0].display_name }} 登录</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 多个 provider: 图标按钮组 -->
|
||||
<div
|
||||
v-else
|
||||
class="flex flex-col items-center gap-3"
|
||||
>
|
||||
<span class="text-xs text-muted-foreground">使用以下方式登录</span>
|
||||
<div class="flex items-center justify-center gap-3">
|
||||
<button
|
||||
v-for="p in oauthProviders"
|
||||
:key="p.provider_type"
|
||||
type="button"
|
||||
class="oauth-icon-btn"
|
||||
:title="p.display_name"
|
||||
@click="handleOAuthLogin(p.provider_type)"
|
||||
>
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z"
|
||||
clip-rule="evenodd"
|
||||
<span
|
||||
class="oauth-icon-lg"
|
||||
v-html="getOAuthIcon(p.provider_type)"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="text-sm font-medium text-foreground">
|
||||
演示模式
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-muted-foreground">
|
||||
当前处于演示模式,所有数据均为模拟数据。
|
||||
</p>
|
||||
<div class="mt-3 space-y-2">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors group"
|
||||
@click="fillDemoAccount('admin')"
|
||||
>
|
||||
<span class="inline-flex items-center justify-center w-5 h-5 rounded bg-primary/20 dark:bg-primary/30 text-primary text-[10px] font-bold group-hover:bg-primary/30 dark:group-hover:bg-primary/40 transition-colors">A</span>
|
||||
<span>管理员:admin@demo.aether.io / demo123</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors group"
|
||||
@click="fillDemoAccount('user')"
|
||||
>
|
||||
<span class="inline-flex items-center justify-center w-5 h-5 rounded bg-muted text-muted-foreground text-[10px] font-bold group-hover:bg-muted/80 transition-colors">U</span>
|
||||
<span>普通用户:user@demo.aether.io / demo123</span>
|
||||
</button>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分隔线 -->
|
||||
<div
|
||||
v-if="oauthProviders.length > 0"
|
||||
class="flex items-center gap-3 mb-5"
|
||||
>
|
||||
<div class="flex-1 h-px bg-border" />
|
||||
<span class="text-xs text-muted-foreground px-2">或使用账号密码</span>
|
||||
<div class="flex-1 h-px bg-border" />
|
||||
</div>
|
||||
|
||||
<!-- 认证方式切换 -->
|
||||
<div
|
||||
v-if="showAuthTypeTabs"
|
||||
class="auth-type-tabs"
|
||||
class="auth-type-tabs mb-4"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -89,15 +125,19 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- 登录表单 -->
|
||||
<form
|
||||
class="space-y-4"
|
||||
@submit.prevent="handleLogin"
|
||||
>
|
||||
<div class="space-y-2">
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<Label for="login-email">{{ emailLabel }}</Label>
|
||||
<Label
|
||||
for="login-email"
|
||||
class="text-sm"
|
||||
>
|
||||
{{ emailLabel }}
|
||||
</Label>
|
||||
<button
|
||||
v-if="ldapExclusive && authType === 'ldap'"
|
||||
type="button"
|
||||
@@ -120,72 +160,69 @@
|
||||
v-model="form.email"
|
||||
type="text"
|
||||
required
|
||||
placeholder="username 或 email"
|
||||
placeholder="用户名或邮箱"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label for="login-password">密码</Label>
|
||||
<div class="space-y-1.5">
|
||||
<Label
|
||||
for="login-password"
|
||||
class="text-sm"
|
||||
>
|
||||
密码
|
||||
</Label>
|
||||
<Input
|
||||
id="login-password"
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
required
|
||||
placeholder="********"
|
||||
placeholder="输入密码"
|
||||
autocomplete="off"
|
||||
@keyup.enter="handleLogin"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 登录按钮 -->
|
||||
<Button
|
||||
type="submit"
|
||||
:disabled="authStore.loading"
|
||||
class="w-full h-10"
|
||||
>
|
||||
{{ authStore.loading ? '登录中...' : '登录' }}
|
||||
</Button>
|
||||
|
||||
<!-- 提示信息 -->
|
||||
<p
|
||||
v-if="!isDemo && !allowRegistration"
|
||||
class="text-xs text-slate-400 dark:text-muted-foreground/80"
|
||||
class="text-xs text-muted-foreground text-center"
|
||||
>
|
||||
如需开通账户,请联系管理员配置访问权限
|
||||
如需开通账户,请联系管理员
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<!-- 注册链接 -->
|
||||
<div
|
||||
v-if="allowRegistration"
|
||||
class="mt-4 text-center text-sm"
|
||||
class="mt-5 pt-5 border-t border-border text-center text-sm text-muted-foreground"
|
||||
>
|
||||
还没有账户?
|
||||
<Button
|
||||
variant="link"
|
||||
class="h-auto p-0"
|
||||
<button
|
||||
type="button"
|
||||
class="text-primary hover:text-primary/80 font-medium transition-colors"
|
||||
@click="handleSwitchToRegister"
|
||||
>
|
||||
立即注册
|
||||
</Button>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
class="w-full sm:w-auto border-slate-200 dark:border-slate-600 text-slate-500 dark:text-slate-400 hover:text-primary hover:border-primary/50 hover:bg-primary/5 dark:hover:text-primary dark:hover:border-primary/50 dark:hover:bg-primary/10"
|
||||
@click="isOpen = false"
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
:disabled="authStore.loading"
|
||||
class="w-full sm:w-auto bg-primary hover:bg-primary/90 text-white border-0"
|
||||
@click="handleLogin"
|
||||
>
|
||||
{{ authStore.loading ? '登录中...' : '登录' }}
|
||||
</Button>
|
||||
</template>
|
||||
</Dialog>
|
||||
|
||||
<!-- Register Dialog -->
|
||||
<RegisterDialog
|
||||
v-model:open="showRegisterDialog"
|
||||
:require-email-verification="requireEmailVerification"
|
||||
:email-configured="emailConfigured"
|
||||
@success="handleRegisterSuccess"
|
||||
@switch-to-login="handleSwitchToLogin"
|
||||
/>
|
||||
@@ -203,6 +240,19 @@ import { useToast } from '@/composables/useToast'
|
||||
import { isDemoMode, DEMO_ACCOUNTS } from '@/config/demo'
|
||||
import RegisterDialog from './RegisterDialog.vue'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { oauthApi, type OAuthProviderInfo } from '@/api/oauth'
|
||||
import { getApiUrl } from '@/utils/url'
|
||||
|
||||
// OAuth provider icons
|
||||
const OAUTH_ICONS: Record<string, string> = {
|
||||
linuxdo: `<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"><clipPath id="ld"><circle cx="60" cy="60" r="47"/></clipPath><circle fill="#f0f0f0" cx="60" cy="60" r="50"/><rect fill="#1c1c1e" clip-path="url(#ld)" x="10" y="10" width="100" height="30"/><rect fill="#f0f0f0" clip-path="url(#ld)" x="10" y="40" width="100" height="40"/><rect fill="#ffb003" clip-path="url(#ld)" x="10" y="80" width="100" height="30"/></svg>`,
|
||||
github: `<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/></svg>`,
|
||||
google: `<svg viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>`,
|
||||
}
|
||||
|
||||
function getOAuthIcon(providerType: string): string {
|
||||
return OAUTH_ICONS[providerType] || OAUTH_ICONS.github
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
@@ -220,6 +270,7 @@ const isOpen = ref(props.modelValue)
|
||||
const isDemo = computed(() => isDemoMode())
|
||||
const showRegisterDialog = ref(false)
|
||||
const requireEmailVerification = ref(false)
|
||||
const emailConfigured = ref(true) // 邮箱服务是否已配置
|
||||
const allowRegistration = ref(false) // 由系统配置控制,默认关闭
|
||||
|
||||
// LDAP authentication settings
|
||||
@@ -233,6 +284,8 @@ const localEnabled = ref(true)
|
||||
const ldapEnabled = ref(false)
|
||||
const ldapExclusive = ref(false)
|
||||
|
||||
const oauthProviders = ref<OAuthProviderInfo[]>([])
|
||||
|
||||
// 保存用户的认证类型偏好
|
||||
watch(authType, (newType) => {
|
||||
localStorage.setItem(PREFERRED_AUTH_TYPE_KEY, newType)
|
||||
@@ -296,6 +349,12 @@ async function handleLogin() {
|
||||
}
|
||||
}
|
||||
|
||||
function handleOAuthLogin(providerType: string) {
|
||||
// 如果 sessionStorage 中没有 redirectPath(用户直接点击登录而非被守卫拦截),
|
||||
// 则不设置,让 AuthCallback 使用默认跳转逻辑
|
||||
window.location.href = getApiUrl(`/api/oauth/${providerType}/authorize`)
|
||||
}
|
||||
|
||||
function handleSwitchToRegister() {
|
||||
isOpen.value = false
|
||||
showRegisterDialog.value = true
|
||||
@@ -315,13 +374,16 @@ function handleSwitchToLogin() {
|
||||
// Load authentication and registration settings on mount
|
||||
onMounted(async () => {
|
||||
try {
|
||||
// Load registration settings
|
||||
const regSettings = await authApi.getRegistrationSettings()
|
||||
const [regSettings, authSettings, providers] = await Promise.all([
|
||||
authApi.getRegistrationSettings(),
|
||||
authApi.getAuthSettings(),
|
||||
oauthApi.getProviders().catch(() => []),
|
||||
])
|
||||
|
||||
allowRegistration.value = !!regSettings.enable_registration
|
||||
requireEmailVerification.value = !!regSettings.require_email_verification
|
||||
emailConfigured.value = !!regSettings.email_configured
|
||||
|
||||
// Load authentication settings
|
||||
const authSettings = await authApi.getAuthSettings()
|
||||
localEnabled.value = authSettings.local_enabled
|
||||
ldapEnabled.value = authSettings.ldap_enabled
|
||||
ldapExclusive.value = authSettings.ldap_exclusive
|
||||
@@ -338,19 +400,85 @@ onMounted(async () => {
|
||||
} else {
|
||||
authType.value = 'local'
|
||||
}
|
||||
|
||||
oauthProviders.value = providers
|
||||
} catch {
|
||||
// If获取失败,保持默认:关闭注册 & 关闭邮箱验证 & 使用本地认证
|
||||
allowRegistration.value = false
|
||||
requireEmailVerification.value = false
|
||||
emailConfigured.value = false
|
||||
localEnabled.value = true
|
||||
ldapEnabled.value = false
|
||||
ldapExclusive.value = false
|
||||
authType.value = 'local'
|
||||
oauthProviders.value = []
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.oauth-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
padding: 0.625rem 1rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: hsl(var(--foreground));
|
||||
background: hsl(var(--background));
|
||||
border: 1px solid hsl(var(--border));
|
||||
border-radius: 0.5rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.oauth-btn:hover {
|
||||
background: hsl(var(--muted));
|
||||
border-color: hsl(var(--primary) / 0.5);
|
||||
}
|
||||
|
||||
.oauth-icon {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.oauth-icon :deep(svg) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.oauth-icon-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
background: hsl(var(--background));
|
||||
border: 1px solid hsl(var(--border));
|
||||
border-radius: 0.75rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.oauth-icon-btn:hover {
|
||||
background: hsl(var(--muted));
|
||||
border-color: hsl(var(--primary) / 0.5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.oauth-icon-lg {
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
}
|
||||
|
||||
.oauth-icon-lg :deep(svg) {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.auth-type-tabs {
|
||||
display: flex;
|
||||
border-bottom: 1px solid hsl(var(--border));
|
||||
@@ -358,7 +486,7 @@ onMounted(async () => {
|
||||
|
||||
.auth-tab {
|
||||
flex: 1;
|
||||
padding: 0.625rem 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: hsl(var(--muted-foreground));
|
||||
@@ -385,11 +513,11 @@ onMounted(async () => {
|
||||
}
|
||||
|
||||
.auth-tab.active {
|
||||
color: var(--book-cloth);
|
||||
color: hsl(var(--primary));
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.auth-tab.active::after {
|
||||
background: var(--book-cloth);
|
||||
background: hsl(var(--primary));
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
注册新账户
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-muted-foreground">
|
||||
请填写您的邮箱和个人信息完成注册
|
||||
{{ emailConfigured ? '请填写您的信息完成注册' : '请填写用户名和密码完成注册' }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -28,27 +28,40 @@
|
||||
data-form-type="other"
|
||||
@submit.prevent="handleSubmit"
|
||||
>
|
||||
<!-- Email -->
|
||||
<div class="space-y-2">
|
||||
<Label for="reg-email">邮箱 <span class="text-muted-foreground">*</span></Label>
|
||||
<!-- Email (仅当邮箱服务已配置时显示) -->
|
||||
<div
|
||||
v-if="emailConfigured"
|
||||
class="space-y-2"
|
||||
>
|
||||
<Label for="reg-email">
|
||||
邮箱
|
||||
<span
|
||||
v-if="requireEmailVerification"
|
||||
class="text-destructive"
|
||||
>*</span>
|
||||
<span
|
||||
v-else
|
||||
class="text-muted-foreground text-xs"
|
||||
>(可选)</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="reg-email"
|
||||
v-model="formData.email"
|
||||
type="email"
|
||||
placeholder="hello@example.com"
|
||||
required
|
||||
:required="requireEmailVerification"
|
||||
disable-autofill
|
||||
:disabled="isLoading || emailVerified"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Verification Code Section -->
|
||||
<!-- Verification Code Section (仅当需要邮箱验证时显示) -->
|
||||
<div
|
||||
v-if="requireEmailVerification"
|
||||
v-if="emailConfigured && requireEmailVerification"
|
||||
class="space-y-3"
|
||||
>
|
||||
<div class="flex items-center justify-between">
|
||||
<Label>验证码 <span class="text-muted-foreground">*</span></Label>
|
||||
<Label>验证码 <span class="text-destructive">*</span></Label>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
@@ -113,7 +126,7 @@
|
||||
|
||||
<!-- Username -->
|
||||
<div class="space-y-2">
|
||||
<Label for="reg-uname">用户名 <span class="text-muted-foreground">*</span></Label>
|
||||
<Label for="reg-uname">用户名 <span class="text-destructive">*</span></Label>
|
||||
<Input
|
||||
id="reg-uname"
|
||||
v-model="formData.username"
|
||||
@@ -127,7 +140,7 @@
|
||||
|
||||
<!-- Password -->
|
||||
<div class="space-y-2">
|
||||
<Label :for="`pwd-${formNonce}`">密码 <span class="text-muted-foreground">*</span></Label>
|
||||
<Label :for="`pwd-${formNonce}`">密码 <span class="text-destructive">*</span></Label>
|
||||
<Input
|
||||
:id="`pwd-${formNonce}`"
|
||||
v-model="formData.password"
|
||||
@@ -146,7 +159,7 @@
|
||||
|
||||
<!-- Confirm Password -->
|
||||
<div class="space-y-2">
|
||||
<Label :for="`pwd-confirm-${formNonce}`">确认密码 <span class="text-muted-foreground">*</span></Label>
|
||||
<Label :for="`pwd-confirm-${formNonce}`">确认密码 <span class="text-destructive">*</span></Label>
|
||||
<Input
|
||||
:id="`pwd-confirm-${formNonce}`"
|
||||
v-model="formData.confirmPassword"
|
||||
@@ -210,6 +223,7 @@ import Label from '@/components/ui/label.vue'
|
||||
interface Props {
|
||||
open?: boolean
|
||||
requireEmailVerification?: boolean
|
||||
emailConfigured?: boolean
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
@@ -220,7 +234,8 @@ interface Emits {
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
open: false,
|
||||
requireEmailVerification: false
|
||||
requireEmailVerification: false,
|
||||
emailConfigured: true
|
||||
})
|
||||
|
||||
const emit = defineEmits<Emits>()
|
||||
@@ -353,17 +368,19 @@ const sendCodeButtonText = computed(() => {
|
||||
})
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
// 基本信息:用户名和密码必填
|
||||
const hasBasicInfo =
|
||||
formData.value.email &&
|
||||
formData.value.username &&
|
||||
formData.value.password &&
|
||||
formData.value.confirmPassword
|
||||
|
||||
if (!hasBasicInfo) return false
|
||||
|
||||
// If email verification is required, check if verified
|
||||
if (props.requireEmailVerification && !emailVerified.value) {
|
||||
return false
|
||||
// 如果需要邮箱验证,邮箱和验证都必须完成
|
||||
if (props.requireEmailVerification) {
|
||||
if (!formData.value.email || !emailVerified.value) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Check password match
|
||||
@@ -608,11 +625,17 @@ const handleSubmit = async () => {
|
||||
loadingText.value = '注册中...'
|
||||
|
||||
try {
|
||||
const response = await authApi.register({
|
||||
email: formData.value.email,
|
||||
// 构建请求数据:邮箱可选
|
||||
const registerData: { email?: string; username: string; password: string } = {
|
||||
username: formData.value.username,
|
||||
password: formData.value.password
|
||||
})
|
||||
}
|
||||
// 只有当邮箱有值时才添加
|
||||
if (formData.value.email && formData.value.email.trim()) {
|
||||
registerData.email = formData.value.email
|
||||
}
|
||||
|
||||
const response = await authApi.register(registerData)
|
||||
|
||||
success(response.message || '欢迎加入!请登录以继续', '注册成功')
|
||||
|
||||
|
||||
@@ -118,14 +118,13 @@
|
||||
<Label
|
||||
for="form-email"
|
||||
class="text-sm font-medium"
|
||||
>邮箱 <span class="text-muted-foreground">*</span></Label>
|
||||
>邮箱</Label>
|
||||
<Input
|
||||
id="form-email"
|
||||
v-model="form.email"
|
||||
type="email"
|
||||
autocomplete="off"
|
||||
data-form-type="other"
|
||||
required
|
||||
class="h-10"
|
||||
/>
|
||||
</div>
|
||||
@@ -472,11 +471,10 @@ const { isEditMode, handleDialogUpdate, handleCancel } = useFormDialog({
|
||||
// 表单验证
|
||||
const isFormValid = computed(() => {
|
||||
const hasUsername = form.value.username.trim().length > 0
|
||||
const hasEmail = form.value.email.trim().length > 0
|
||||
const hasPassword = isEditMode.value || form.value.password.length >= 6
|
||||
// 编辑模式下如果填写了密码,必须确认密码一致
|
||||
const passwordConfirmed = !isEditMode.value || form.value.password.length === 0 || form.value.password === form.value.confirmPassword
|
||||
return hasUsername && hasEmail && hasPassword && passwordConfirmed
|
||||
return hasUsername && hasPassword && passwordConfirmed
|
||||
})
|
||||
|
||||
// 加载访问控制选项
|
||||
@@ -508,16 +506,11 @@ function toggleSelection(field: 'allowed_providers' | 'allowed_api_formats' | 'a
|
||||
|
||||
// 提交表单
|
||||
async function handleSubmit() {
|
||||
// 验证邮箱必填
|
||||
if (!form.value.email || !form.value.email.trim()) {
|
||||
return
|
||||
}
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
const data: UserFormData & { password?: string; unlimited?: boolean } = {
|
||||
username: form.value.username,
|
||||
email: form.value.email.trim(),
|
||||
email: form.value.email.trim() || '',
|
||||
quota_usd: form.value.unlimited ? null : form.value.quota,
|
||||
role: form.value.role,
|
||||
allowed_providers: form.value.allowed_providers.length > 0 ? form.value.allowed_providers : null,
|
||||
|
||||
@@ -362,7 +362,9 @@ import {
|
||||
X,
|
||||
Mail,
|
||||
Puzzle,
|
||||
type LucideIcon,
|
||||
} from 'lucide-vue-next'
|
||||
|
||||
import GithubIcon from '@/components/icons/GithubIcon.vue'
|
||||
|
||||
const router = useRouter()
|
||||
@@ -497,7 +499,7 @@ const navigation = computed(() => {
|
||||
]
|
||||
|
||||
// 系统菜单项(静态部分)
|
||||
const systemItems = [
|
||||
const systemItems: { name: string; href: string; icon: LucideIcon }[] = [
|
||||
{ name: '公告管理', href: '/admin/announcements', icon: Megaphone },
|
||||
{ name: '缓存监控', href: '/admin/cache-monitoring', icon: Gauge },
|
||||
{ name: 'IP 安全', href: '/admin/ip-security', icon: Shield },
|
||||
|
||||
@@ -19,6 +19,12 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => importWithRetry(() => import('@/views/public/LogoColorDemo.vue')),
|
||||
meta: { requiresAuth: false }
|
||||
},
|
||||
{
|
||||
path: '/auth/callback',
|
||||
name: 'AuthCallback',
|
||||
component: () => importWithRetry(() => import('@/views/public/AuthCallback.vue')),
|
||||
meta: { requiresAuth: false }
|
||||
},
|
||||
|
||||
{
|
||||
path: '/dashboard',
|
||||
@@ -133,6 +139,12 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => importWithRetry(() => import('@/views/admin/LdapSettings.vue')),
|
||||
meta: { module: 'ldap' }
|
||||
},
|
||||
{
|
||||
path: 'oauth',
|
||||
name: 'OAuthSettings',
|
||||
component: () => importWithRetry(() => import('@/views/admin/OAuthSettings.vue')),
|
||||
meta: { module: 'oauth' }
|
||||
},
|
||||
{
|
||||
path: 'audit-logs',
|
||||
name: 'AuditLogs',
|
||||
@@ -234,9 +246,10 @@ router.beforeEach(async (to, from, next) => {
|
||||
return
|
||||
}
|
||||
}
|
||||
// 如果模块未激活(available && enabled),重定向到管理员首页
|
||||
if (!moduleStore.isActive(moduleName)) {
|
||||
log.warn(`Module ${moduleName} is not active, redirecting to admin dashboard`)
|
||||
// 如果模块不可用(未部署),重定向到管理员首页
|
||||
// 注意:只检查 available,不检查 enabled/active,允许管理员配置未启用的模块
|
||||
if (!moduleStore.isAvailable(moduleName)) {
|
||||
log.warn(`Module ${moduleName} is not available, redirecting to admin dashboard`)
|
||||
next('/admin/dashboard')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ export const useModuleStore = defineStore('modules', () => {
|
||||
|
||||
/**
|
||||
* 设置模块启用状态
|
||||
* @throws 如果设置失败会抛出错误
|
||||
*/
|
||||
async function setEnabled(moduleName: string, enabled: boolean) {
|
||||
try {
|
||||
@@ -62,7 +63,8 @@ export const useModuleStore = defineStore('modules', () => {
|
||||
} catch (err: any) {
|
||||
log.error(`Failed to set module ${moduleName} enabled=${enabled}`, err)
|
||||
error.value = err.response?.data?.detail || '设置模块状态失败'
|
||||
return false
|
||||
// 重新抛出错误,让调用方可以获取详细错误信息
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface ApiErrorResponse {
|
||||
error?: {
|
||||
type?: string
|
||||
message?: string
|
||||
details?: Record<string, unknown>
|
||||
}
|
||||
detail?: string
|
||||
message?: string
|
||||
@@ -57,9 +58,12 @@ export function getErrorMessage(error: unknown, defaultMessage = '操作失败')
|
||||
if (error.response?.data?.message) {
|
||||
return error.response.data.message
|
||||
}
|
||||
// API 错误但没有可用的错误消息,返回默认消息
|
||||
// 不使用 error.message,因为那是 Axios 的默认消息如 "Request failed with status code 400"
|
||||
return defaultMessage
|
||||
}
|
||||
|
||||
// Error 实例
|
||||
// 非 API 错误的 Error 实例
|
||||
if (error instanceof Error) {
|
||||
return error.message
|
||||
}
|
||||
|
||||
11
frontend/src/utils/url.ts
Normal file
11
frontend/src/utils/url.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* 构建完整的 API URL
|
||||
*
|
||||
* 用于需要完整 URL 的场景(如 OAuth 重定向),
|
||||
* 处理 VITE_API_URL 环境变量和路径拼接。
|
||||
*/
|
||||
export function getApiUrl(path: string): string {
|
||||
const base = import.meta.env.VITE_API_URL || ''
|
||||
// 移除 base 尾部的 `/`,避免拼接成 `//api/...`
|
||||
return base ? `${base.replace(/\/$/, '')}${path}` : path
|
||||
}
|
||||
@@ -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