forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-binding-dialog.tsx
More file actions
454 lines (424 loc) · 13.2 KB
/
Copy pathuser-binding-dialog.tsx
File metadata and controls
454 lines (424 loc) · 13.2 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
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 {
Mail,
Globe,
MessageCircle,
Send,
Link2,
Unlink,
Loader2,
Eye,
EyeOff,
} from 'lucide-react'
import { useState, useEffect, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { SiGithub, SiDiscord } from 'react-icons/si'
import { toast } from 'sonner'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { Dialog } from '@/components/dialog'
import { StatusBadge } from '@/components/status-badge'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip'
import { api } from '@/lib/api'
import {
getUser,
getUserOAuthBindings,
adminClearUserBinding,
adminUnbindCustomOAuth,
type OAuthBinding,
} from '../../api'
import type { User } from '../../types'
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
userId: number | null
onUnbindSuccess?: () => void
}
interface BindingItem {
key: string
label: string
icon: React.ReactNode
value: string
type: 'builtin' | 'custom'
providerId?: string
isBound: boolean
isEnabled: boolean
}
interface StatusInfo {
github_oauth?: boolean
discord_oauth?: boolean
oidc_enabled?: boolean
wechat_login?: boolean
telegram_oauth?: boolean
linuxdo_oauth?: boolean
custom_oauth_providers?: Array<{
id: string
name: string
icon?: string
}>
}
const BUILTIN_BINDINGS: ReadonlyArray<{
key: string
field: string
label: string
icon: React.ReactNode
statusKey: keyof StatusInfo | null
}> = [
{
key: 'email',
field: 'email',
label: 'Email',
icon: <Mail className='h-4 w-4' />,
statusKey: null,
},
{
key: 'github_id',
field: 'github_id',
label: 'GitHub',
icon: <SiGithub className='h-4 w-4' />,
statusKey: 'github_oauth',
},
{
key: 'discord_id',
field: 'discord_id',
label: 'Discord',
icon: <SiDiscord className='h-4 w-4' />,
statusKey: 'discord_oauth',
},
{
key: 'wechat_id',
field: 'wechat_id',
label: 'WeChat',
icon: <MessageCircle className='h-4 w-4' />,
statusKey: 'wechat_login',
},
{
key: 'oidc_id',
field: 'oidc_id',
label: 'OIDC',
icon: <Globe className='h-4 w-4' />,
statusKey: 'oidc_enabled',
},
{
key: 'telegram_id',
field: 'telegram_id',
label: 'Telegram',
icon: <Send className='h-4 w-4' />,
statusKey: 'telegram_oauth',
},
{
key: 'linux_do_id',
field: 'linux_do_id',
label: 'LinuxDO',
icon: <Globe className='h-4 w-4' />,
statusKey: 'linuxdo_oauth',
},
]
function CustomProviderIcon(props: { iconUrl?: string }) {
if (!props.iconUrl) return <Link2 className='h-4 w-4' />
return (
<img
src={props.iconUrl}
alt=''
className='h-4 w-4 rounded-sm object-contain'
onError={(e) => {
e.currentTarget.style.display = 'none'
}}
/>
)
}
export function UserBindingDialog(props: Props) {
const { t } = useTranslation()
const [user, setUser] = useState<User | null>(null)
const [oauthBindings, setOauthBindings] = useState<OAuthBinding[]>([])
const [statusInfo, setStatusInfo] = useState<StatusInfo>({})
const [loading, setLoading] = useState(false)
const [showBoundOnly, setShowBoundOnly] = useState(true)
const [unbindTarget, setUnbindTarget] = useState<BindingItem | null>(null)
const [unbinding, setUnbinding] = useState(false)
const fetchData = useCallback(async () => {
if (!props.userId) return
setLoading(true)
try {
const [userRes, oauthRes, statusRes] = await Promise.all([
getUser(props.userId),
getUserOAuthBindings(props.userId).catch(() => ({
success: false,
data: [],
})),
api
.get('/api/status')
.then((r) => r.data)
.catch(() => ({
success: false,
data: {},
})),
])
if (userRes.success && userRes.data) {
setUser(userRes.data)
}
if (oauthRes.success && oauthRes.data) {
setOauthBindings(oauthRes.data as OAuthBinding[])
}
if (statusRes.success && statusRes.data) {
setStatusInfo(statusRes.data as StatusInfo)
}
} catch {
toast.error(t('Failed to load'))
} finally {
setLoading(false)
}
}, [props.userId, t])
useEffect(() => {
if (props.open && props.userId) {
setShowBoundOnly(true)
fetchData()
} else {
setUser(null)
setOauthBindings([])
setStatusInfo({})
}
}, [props.open, props.userId, fetchData])
const allBindings = useMemo<BindingItem[]>(() => {
const items: BindingItem[] = []
for (const field of BUILTIN_BINDINGS) {
const value = user
? String((user as Record<string, unknown>)[field.field] || '')
: ''
const isBound = !!value
const isEnabled =
field.statusKey == null ? true : Boolean(statusInfo[field.statusKey])
items.push({
key: field.key,
label: field.label,
icon: field.icon,
value: isBound ? value : '',
type: 'builtin',
isBound,
isEnabled,
})
}
const oauthBindingMap = new Map(
oauthBindings.map((b) => [String(b.provider_id), b])
)
const customProviders = statusInfo.custom_oauth_providers || []
const seenProviderIds = new Set<string>()
for (const provider of customProviders) {
seenProviderIds.add(String(provider.id))
const binding = oauthBindingMap.get(String(provider.id))
items.push({
key: `oauth_${provider.id}`,
label: provider.name || provider.id,
icon: <CustomProviderIcon iconUrl={provider.icon} />,
value: binding?.external_id || '',
type: 'custom',
providerId: String(provider.id),
isBound: !!binding,
isEnabled: true,
})
}
for (const binding of oauthBindings) {
if (!seenProviderIds.has(String(binding.provider_id))) {
items.push({
key: `oauth_${binding.provider_id}`,
label: binding.provider_name || binding.provider_id,
icon: <Link2 className='h-4 w-4' />,
value: binding.external_id || '-',
type: 'custom',
providerId: String(binding.provider_id),
isBound: true,
isEnabled: false,
})
}
}
return items
}, [user, oauthBindings, statusInfo])
const displayedBindings = showBoundOnly
? allBindings.filter((b) => b.isBound)
: allBindings
const boundCount = allBindings.filter((b) => b.isBound).length
const handleUnbind = async () => {
if (!unbindTarget || !props.userId) return
setUnbinding(true)
try {
let res
if (unbindTarget.type === 'builtin') {
res = await adminClearUserBinding(props.userId, unbindTarget.key)
} else if (unbindTarget.providerId) {
res = await adminUnbindCustomOAuth(
props.userId,
unbindTarget.providerId
)
}
if (res?.success) {
toast.success(
t('Unbound {{provider}}', { provider: unbindTarget.label })
)
await fetchData()
props.onUnbindSuccess?.()
} else {
toast.error(res?.message || t('Unbind failed'))
}
} catch {
toast.error(t('Unbind failed'))
} finally {
setUnbinding(false)
setUnbindTarget(null)
}
}
return (
<>
<Dialog
open={props.open}
onOpenChange={props.onOpenChange}
title={
<>
<Link2 className='h-5 w-5' />
{t('Account Binding Management')}
</>
}
description={t('Manage account bindings for this user')}
contentClassName='sm:max-w-lg'
titleClassName='flex items-center gap-2'
descriptionClassName='sr-only'
contentHeight='auto'
bodyClassName='space-y-4'
>
{loading ? (
<div className='flex items-center justify-center py-8'>
<Loader2 className='text-muted-foreground h-6 w-6 animate-spin' />
</div>
) : (
<div className='space-y-3'>
<div className='flex items-center justify-between'>
{user && (
<p className='text-muted-foreground text-sm'>
{user.username} (ID: {user.id})
</p>
)}
<TooltipProvider>
<Tooltip>
<TooltipTrigger
render={
<Button
variant='ghost'
size='sm'
className='h-7 gap-1.5 px-2 text-xs'
onClick={() => setShowBoundOnly((v) => !v)}
/>
}
>
{showBoundOnly ? (
<Eye className='h-3.5 w-3.5' />
) : (
<EyeOff className='h-3.5 w-3.5' />
)}
{showBoundOnly ? t('Show All') : t('Bound Only')}
</TooltipTrigger>
<TooltipContent>
{showBoundOnly
? t('Show all providers including unbound')
: t('Show only bound providers')}
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<Separator />
<ScrollArea className='max-h-[50vh]'>
{displayedBindings.length === 0 ? (
<p className='text-muted-foreground py-4 text-center text-sm'>
{showBoundOnly
? t('This user has no bindings')
: t('No providers available')}
</p>
) : (
<div className='grid grid-cols-1 gap-2 pr-3 lg:grid-cols-2'>
{displayedBindings.map((binding) => (
<div
key={binding.key}
className={`flex items-center justify-between rounded-md border px-3 py-2.5 ${
!binding.isBound ? 'opacity-50' : ''
}`}
>
<div className='flex min-w-0 items-center gap-2.5'>
<div className='text-muted-foreground shrink-0'>
{binding.icon}
</div>
<div className='min-w-0'>
<div className='flex items-center gap-1.5'>
<span className='text-sm font-medium'>
{binding.label}
</span>
{!binding.isEnabled && (
<StatusBadge
variant='neutral'
label={t('Disabled')}
copyable={false}
size='sm'
/>
)}
</div>
<p className='text-muted-foreground max-w-[140px] truncate text-xs'>
{binding.isBound ? binding.value : t('Not bound')}
</p>
</div>
</div>
{binding.isBound && (
<Button
variant='ghost'
size='sm'
className='text-destructive hover:text-destructive h-7 w-7 shrink-0 p-0'
onClick={() => setUnbindTarget(binding)}
>
<Unlink className='h-3.5 w-3.5' />
</Button>
)}
</div>
))}
</div>
)}
</ScrollArea>
<p className='text-muted-foreground text-xs'>
{t('Bound')}: {boundCount} / {allBindings.length}
</p>
</div>
)}
</Dialog>
<ConfirmDialog
open={!!unbindTarget}
onOpenChange={(open) => !open && setUnbindTarget(null)}
title={t('Confirm Unbind')}
desc={t(
'Are you sure you want to unbind {{provider}} for this user? The user will no longer be able to log in via this method.',
{
provider: unbindTarget?.label || '',
}
)}
confirmText={t('Confirm Unbind')}
destructive
handleConfirm={handleUnbind}
isLoading={unbinding}
/>
</>
)
}