forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__root.tsx
More file actions
182 lines (161 loc) · 5.54 KB
/
Copy path__root.tsx
File metadata and controls
182 lines (161 loc) · 5.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useQueryClient, type QueryClient } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import {
createRootRouteWithContext,
Outlet,
redirect,
useNavigate,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { useEffect } from 'react'
import { NavigationProgress } from '@/components/navigation-progress'
import { Toaster } from '@/components/ui/sonner'
import { ThemeCustomizationProvider } from '@/context/theme-customization-provider'
import { saveAffiliateCode } from '@/features/auth/lib/storage'
import { GeneralError } from '@/features/errors/general-error'
import { NotFoundError } from '@/features/errors/not-found-error'
import { getSetupStatus } from '@/features/setup/api'
import { useSystemConfig } from '@/hooks/use-system-config'
import {
bootstrapAuthentication,
clearAuthenticatedClientState,
clearAuthentication,
} from '@/lib/auth-session'
import { subscribeAuthSessionEvents } from '@/lib/auth-session-sync'
import { resolveLegacyRoute } from '@/lib/legacy-route'
import { useAuthStore } from '@/stores/auth-store'
function RootComponent() {
const navigate = useNavigate()
const queryClient = useQueryClient()
// Load system configuration (logo, system name, etc.) from backend
useSystemConfig({ autoLoad: true })
useEffect(() => {
const aff = new URLSearchParams(window.location.search).get('aff')?.trim()
if (aff) {
saveAffiliateCode(aff)
}
}, [])
useEffect(
() =>
useAuthStore.subscribe((state, previousState) => {
const sid = state.auth.session?.sid
const previousSID = previousState.auth.session?.sid
if (sid !== previousSID) {
queryClient.clear()
}
}),
[queryClient]
)
useEffect(
() =>
subscribeAuthSessionEvents((event) => {
const currentSID = useAuthStore.getState().auth.session?.sid
if (event.kind === 'authenticated') {
if (event.sid === currentSID) return
if (currentSID) {
clearAuthentication(false)
}
window.location.reload()
return
}
if (currentSID && event.sid === currentSID) {
clearAuthenticatedClientState(queryClient, false)
void navigate({ to: '/sign-in', replace: true })
}
}),
[navigate, queryClient]
)
return (
<ThemeCustomizationProvider>
<NavigationProgress />
<Outlet />
<Toaster closeButton duration={5000} position='top-center' richColors />
{import.meta.env.MODE === 'development' && (
<>
<ReactQueryDevtools buttonPosition='bottom-left' />
<TanStackRouterDevtools position='bottom-right' />
</>
)}
</ThemeCustomizationProvider>
)
}
// 缓存 setup 状态检查结果,避免每次导航都重复调用 API
// 使用 localStorage 持久化,避免页面刷新后重复检查
const SETUP_CHECKED_KEY = 'setup_status_checked'
function getSetupStatusFromCache(): boolean {
try {
if (typeof window !== 'undefined') {
return window.localStorage.getItem(SETUP_CHECKED_KEY) === 'true'
}
} catch {
/* empty */
}
return false
}
function setSetupStatusCache(value: boolean): void {
try {
if (typeof window !== 'undefined') {
if (value) {
window.localStorage.setItem(SETUP_CHECKED_KEY, 'true')
} else {
window.localStorage.removeItem(SETUP_CHECKED_KEY)
}
}
} catch {
/* empty */
}
}
// 内存中的标记,避免同一会话中重复检查
let setupStatusChecked = getSetupStatusFromCache()
export const Route = createRootRouteWithContext<{
queryClient: QueryClient
}>()({
// 应用初始化与路由解析前统一校验会话
beforeLoad: async ({ location }) => {
const legacyTarget = resolveLegacyRoute(location.href)
if (legacyTarget) {
throw redirect({ href: legacyTarget, replace: true })
}
const pathname = location?.pathname || ''
const needsSetupCheck =
!setupStatusChecked && !pathname.startsWith('/setup')
const authBootstrap = bootstrapAuthentication()
// 只检查 setup 状态(如果需要)
if (needsSetupCheck) {
const [status] = await Promise.all([
getSetupStatus().catch((error) => {
if (import.meta.env.DEV) {
// eslint-disable-next-line no-console
console.warn('[root.beforeLoad] setup status check failed', error)
}
return null
}),
authBootstrap,
])
if (status?.success && status.data && !status.data.status) {
throw redirect({ to: '/setup' })
}
setupStatusChecked = true
setSetupStatusCache(true)
} else {
await authBootstrap
}
},
component: RootComponent,
notFoundComponent: NotFoundError,
errorComponent: GeneralError,
})