-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathLoginView.tsx
More file actions
1128 lines (1034 loc) · 36.8 KB
/
LoginView.tsx
File metadata and controls
1128 lines (1034 loc) · 36.8 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
@license
Copyright (c) 2015-2026 Lablup Inc. All rights reserved.
*/
/**
* LoginView - React implementation of the Backend.AI login component.
*
* Supports SESSION and API connection modes, OTP/TOTP flows,
* endpoint configuration, and integrates with existing React child components.
*
* Config is fetched and parsed entirely within React via useInitializeConfig.
* Login flow orchestration (auto-logout, tab counting, initial login) is
* handled by the useLoginOrchestration hook, replacing the Lit shell's
* firstUpdated() logic.
*/
import {
getDefaultLoginConfig,
type LoginConfigState,
} from '../helper/loginConfig';
import {
createBackendAIClient,
connectViaGQL,
loadConfigFromWebServer,
loginWithSAML,
loginWithOpenID,
} from '../helper/loginSessionAuth';
import { useLoginOrchestration } from '../hooks/useLoginOrchestration';
import {
useInitializeConfig,
useConfigRefreshPageEffect,
loginPluginState,
loginConfigState,
} from '../hooks/useWebUIConfig';
import { pluginApiEndpointState } from '../hooks/useWebUIPluginState';
import { preloadPostLoginChunks } from '../preload';
import { jotaiStore } from './DefaultProviders';
import LoginFormPanel from './LoginFormPanel';
import { App, Button, Form, type MenuProps } from 'antd';
import {
BAIModal,
BAIFlex,
BAIConfigProvider,
useBAILogger,
} from 'backend.ai-ui';
import { useAtomValue, useSetAtom } from 'jotai';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
type ConnectionMode = 'SESSION' | 'API';
/**
* Extract the error type suffix from a Backend.AI problem type URL.
* e.g., "https://api.backend.ai/probs/auth-failed" → "auth-failed"
*/
const extractErrorType = (typeUrl?: string): string => {
if (!typeUrl) return '';
const parts = typeUrl.split('/');
return parts[parts.length - 1] || '';
};
const LoginView: React.FC<{
/**
* When true, delays closing the login panel until MainLayout signals
* readiness (`main-layout-ready` event) to prevent a blank screen flash.
* Set to false for routes without MainLayout (e.g. /interactive-login).
* @default true
*/
waitForMainLayout?: boolean;
}> = ({ waitForMainLayout = true }) => {
'use memo';
const { t } = useTranslation();
const { modal } = App.useApp();
const { logger } = useBAILogger();
// Preload commonly needed lazy chunks while the user is on the login screen.
// This runs during browser idle time so the JS bundles are already cached
// by the time login completes and MainLayout renders.
useEffect(() => {
preloadPostLoginChunks();
}, []);
// Initialize config from config.toml (replaces Lit shell's _parseConfig + loadConfig)
const {
isLoaded: isConfigLoaded,
loginConfig: atomLoginConfig,
loadConfig,
} = useInitializeConfig();
// Set up proxy URL on backend client when connected
useConfigRefreshPageEffect();
// Login plugin name from config
const loginPlugin = useAtomValue(loginPluginState);
const setPluginApiEndpoint = useSetAtom(pluginApiEndpointState);
// State
const [loginConfig, setLoginConfig] = useState<LoginConfigState>(() =>
getDefaultLoginConfig(),
);
const [connectionMode, setConnectionMode] =
useState<ConnectionMode>('SESSION');
const [apiEndpoint, setApiEndpoint] = useState(() => {
const stored = localStorage.getItem('backendaiwebui.api_endpoint');
return stored ? stored.replace(/^"+|"+$/g, '') : '';
});
const [otpRequired, setOtpRequired] = useState(false);
const [needsOtpRegistration, setNeedsOtpRegistration] = useState(false);
const [totpRegistrationToken, setTotpRegistrationToken] = useState('');
const [needToResetPassword, setNeedToResetPassword] = useState(false);
// Use useRef instead of useState to avoid exposing plaintext credentials
// in React DevTools and to prevent unnecessary re-renders.
const expiredCredentialsRef = useRef<{
username: string;
password: string;
} | null>(null);
const [showSignupModal, setShowSignupModal] = useState(false);
const [signupPreloadedToken, setSignupPreloadedToken] = useState<
string | undefined
>();
const [isLoginPanelOpen, setIsLoginPanelOpen] = useState(false);
const [isBlockPanelOpen, setIsBlockPanelOpen] = useState(false);
const [blockMessage, setBlockMessage] = useState('');
const [blockType, setBlockType] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [loginError, setLoginError] = useState<{
message: string;
description?: string;
} | null>(null);
const [endpoints, setEndpoints] = useState<string[]>(() => {
return (globalThis as any).backendaioptions?.get('endpoints', []) ?? [];
});
const [showEndpointInput, setShowEndpointInput] = useState(true);
const [isEndpointDisabled, setIsEndpointDisabled] = useState(false);
const [form] = Form.useForm();
const clientRef =
useRef<ReturnType<typeof createBackendAIClient>['client']>(null);
const configRef = useRef<LoginConfigState>(loginConfig);
const blockTimerRef = useRef<ReturnType<typeof setTimeout>>(null);
const connectUsingSessionRef =
useRef<(showError?: boolean, endpointOverride?: string) => Promise<void>>(
null,
);
// Remembers that the user approved force-login (concurrent session override).
// Persists across retries (e.g., TOTP expiration after force approval) so
// the next login attempt automatically includes force=true.
// Reset when credentials or endpoint change to prevent unintended force-login
// against a different user/endpoint.
const forceLoginApprovedRef = useRef(false);
// Reset force-login approval when credentials or endpoint change
const watchedUserId = Form.useWatch('user_id', form);
const watchedPassword = Form.useWatch('password', form);
useEffect(() => {
forceLoginApprovedRef.current = false;
}, [apiEndpoint, watchedUserId, watchedPassword]);
// Trigger config loading on mount
useEffect(() => {
loadConfig();
}, [loadConfig]);
// When config finishes loading from the atom, apply it to local state
useEffect(() => {
if (!isConfigLoaded || !atomLoginConfig) return;
const newCfg = atomLoginConfig;
setLoginConfig(newCfg);
setConnectionMode(newCfg.connection_mode);
setApiEndpoint((prev) => newCfg.api_endpoint || prev);
// Handle endpoint visibility
if (newCfg.api_endpoint === '') {
setShowEndpointInput(true);
setIsEndpointDisabled(false);
} else {
setShowEndpointInput(false);
setIsEndpointDisabled(true);
}
}, [isConfigLoaded, atomLoginConfig]);
// Load login plugin when config is ready.
// Mirrors `PluginLoader.tsx`'s URL resolution so login plugins follow
// the same deployment model as page plugins: the file is served by the
// backend WebServer (or a Vite/static host that mounts `/dist/plugins/`).
// No build-time bundling — plugins can be deployed independently of the
// WebUI bundle.
useEffect(() => {
if (!isConfigLoaded || !loginPlugin) return;
// Sanitize the plugin name to prevent path traversal attacks.
// Only allow alphanumeric characters, hyphens, and underscores.
const sanitizedPlugin = loginPlugin.replace(/[^a-zA-Z0-9_-]/g, '');
if (!sanitizedPlugin || sanitizedPlugin !== loginPlugin) return;
const isElectronEnv = (globalThis as Record<string, unknown>).isElectron;
const pluginUrl =
isElectronEnv && apiEndpoint
? `${apiEndpoint}/dist/plugins/${sanitizedPlugin}.js`
: `/dist/plugins/${sanitizedPlugin}.js`;
// `@vite-ignore` opts out of Vite's static analysis. The URL is an
// absolute path (no relative `..` traversal), so esbuild's
// optimizeDeps scanner does not treat it as a module specifier.
import(/* @vite-ignore */ pluginUrl).catch(() => {
setLoginError({ message: t('error.LoginPluginLoadFailed') });
});
}, [isConfigLoaded, loginPlugin, apiEndpoint, t]);
// Keep configRef in sync
useEffect(() => {
configRef.current = loginConfig;
}, [loginConfig]);
// Sync apiEndpoint state changes to the form field.
// Ant Design's initialValues only applies on first render, so subsequent
// state updates (from config loading, localStorage restoration, etc.)
// must be explicitly synced to the form.
useEffect(() => {
if (apiEndpoint) {
form.setFieldsValue({ api_endpoint: apiEndpoint });
}
}, [apiEndpoint, form]);
// Language initialization: bridge selected_language -> general.language
// (replaces Lit shell's connectedCallback language setup)
useEffect(() => {
const supportLanguageCodes = [
'en',
'ko',
'de',
'el',
'es',
'fi',
'fr',
'id',
'it',
'ja',
'mn',
'ms',
'pl',
'pt',
'pt-BR',
'ru',
'th',
'tr',
'vi',
'zh-CN',
'zh-TW',
];
const selectedLang = (globalThis as any).backendaioptions?.get(
'selected_language',
);
// Try full locale first (e.g., 'zh-CN'), then base language (e.g., 'zh')
const browserLang = globalThis.navigator.language;
let defaultLang: string;
if (supportLanguageCodes.includes(browserLang)) {
defaultLang = browserLang;
} else {
const baseLang = browserLang.split('-')[0];
defaultLang = supportLanguageCodes.includes(baseLang) ? baseLang : 'en';
}
let lang: string;
if (!selectedLang || selectedLang === 'default') {
lang = defaultLang;
} else {
lang = supportLanguageCodes.includes(selectedLang)
? selectedLang
: defaultLang;
}
(globalThis as any).backendaioptions.set('language', lang, 'general');
}, []);
const notification = useCallback((text: string, detail?: string) => {
setLoginError({ message: text, description: detail });
}, []);
const open = useCallback(() => {
// Cancel any pending block timer so the block modal doesn't overlay
// the login panel (and any error notifications) after a login failure.
if (blockTimerRef.current) {
clearTimeout(blockTimerRef.current);
blockTimerRef.current = null;
}
setIsLoginPanelOpen(true);
setIsBlockPanelOpen(false);
// Dismiss splash when login form becomes visible (logged-out state)
(globalThis as any).__dismissSplash?.();
const urlParams = new URLSearchParams(window.location.search);
const tokenParam = urlParams.get('token');
if (
loginConfig.signup_support &&
apiEndpoint !== '' &&
tokenParam !== undefined &&
tokenParam !== null
) {
setSignupPreloadedToken(tokenParam);
setShowSignupModal(true);
}
}, [loginConfig.signup_support, apiEndpoint]);
const close = useCallback(() => {
// Cancel any pending block timer so a delayed timer from block()
// doesn't re-open the block panel after a successful login.
if (blockTimerRef.current) {
clearTimeout(blockTimerRef.current);
blockTimerRef.current = null;
}
setIsLoginPanelOpen(false);
setIsBlockPanelOpen(false);
setLoginError(null);
}, []);
const block = useCallback((message = '', type = '') => {
setBlockMessage(message);
setBlockType(type);
// Clear any existing block timer to prevent a stale timer from firing.
if (blockTimerRef.current) {
clearTimeout(blockTimerRef.current);
}
blockTimerRef.current = setTimeout(() => {
blockTimerRef.current = null;
// Use the functional updater pattern to read the current isLoginPanelOpen
// value at callback time, avoiding the stale closure that previously caused
// the block modal to overlay error notifications after a login failure.
setIsLoginPanelOpen((currentIsLoginPanelOpen) => {
if (!currentIsLoginPanelOpen) {
setIsBlockPanelOpen(true);
}
// Return unchanged value — this is a read-only check, not a state change.
return currentIsLoginPanelOpen;
});
}, 2000);
}, []);
const clearSavedLoginInfo = useCallback(() => {
localStorage.removeItem('backendaiwebui.login.api_key');
localStorage.removeItem('backendaiwebui.login.secret_key');
localStorage.removeItem('backendaiwebui.login.user_id');
localStorage.removeItem('backendaiwebui.login.password');
}, []);
// Shared post-connection setup used by both the regular session login
// (doGQLConnect) and the sToken SSO path. Keeps the two flows consistent:
// login_attempt/last_login counters, saved-credentials cleanup, panel
// close, connected-event dispatch, and endpoint persistence.
const postConnectSetup = useCallback(
(client: ReturnType<typeof createBackendAIClient>['client']) => {
const currentTime = Math.floor(Date.now() / 1000);
(globalThis as any).backendaioptions.set(
'last_login',
currentTime,
'general',
);
(globalThis as any).backendaioptions.set('login_attempt', 0, 'general');
const event = new CustomEvent('backend-ai-connected', {
detail: client,
});
document.dispatchEvent(event);
// Delay closing the login panel until MainLayout has rendered to avoid
// a blank screen flash between the login modal and the main UI.
// Routes without MainLayout (e.g. /interactive-login) pass
// waitForMainLayout={false} so the panel closes immediately.
if (!waitForMainLayout || (globalThis as any).__mainLayoutReady) {
close();
} else {
document.addEventListener('main-layout-ready', () => close(), {
once: true,
});
}
forceLoginApprovedRef.current = false;
clearSavedLoginInfo();
// Read the endpoint from the connected client to avoid stale closure
// values. When handleLogin calls setApiEndpoint(ep) then immediately
// invokes connectUsingSession, the closure still captures the OLD
// apiEndpoint (often "" on first launch). The client object always
// has the correct endpoint that was used for the connection.
const connectedEndpoint =
(globalThis as any).backendaiclient?._config?.endpoint || apiEndpoint;
localStorage.setItem('backendaiwebui.api_endpoint', connectedEndpoint);
setPluginApiEndpoint(connectedEndpoint);
},
[
close,
clearSavedLoginInfo,
apiEndpoint,
setPluginApiEndpoint,
waitForMainLayout,
],
);
const doGQLConnect = useCallback(
async (client: ReturnType<typeof createBackendAIClient>['client']) => {
// Read directly from Jotai store to get the latest config synchronously,
// including any merged webserver config from loadConfigFromWebServer().
// Using configRef.current here would return stale config because React
// hasn't re-rendered yet after the Jotai atom update.
const cfg = jotaiStore.get(loginConfigState) ?? configRef.current;
const updatedEndpoints = await connectViaGQL(client, cfg, endpoints);
setEndpoints(updatedEndpoints);
postConnectSetup(client);
},
[endpoints, postConnectSetup],
);
const connectUsingSession = useCallback(
async (showError = true, endpointOverride?: string) => {
const ep = (endpointOverride ?? apiEndpoint).trim();
if (ep === '') {
setIsBlockPanelOpen(false);
open();
return;
}
const userId = (form.getFieldValue('user_id') || '').trim();
const password = form.getFieldValue('password') || '';
const otp = form.getFieldValue('otp') || '';
const { client } = createBackendAIClient(userId, password, ep, 'SESSION');
clientRef.current = client;
try {
await client.get_manager_version();
} catch {
setIsBlockPanelOpen(false);
open();
setIsLoading(false);
if (showError) {
notification(t('error.CannotConnectToServer'));
}
return;
}
// Check if already logged in
let isLogon = false;
try {
isLogon = !!(await client.check_login());
} catch {
isLogon = false;
}
if (isLogon) {
try {
await doGQLConnect(client);
} catch (err: unknown) {
handleGQLError(err, showError);
}
return;
}
// Not yet authenticated. Show block panel while connecting (only for user-initiated login).
if (showError) {
block(t('login.PleaseWait'), t('login.ConnectingToCluster'));
}
// sToken (SSO) URL entry is handled entirely by STokenLoginBoundary
// at the route level (see routes.tsx `STokenGuard`). LoginView no
// longer reads sToken from the URL; when a token is present the
// boundary mounts LoginView only after authentication succeeds.
// Do session login
// client.login() returns only on success (authenticated === true).
// All failure cases throw: login errors carry `isLoginError: true` with
// `data.type` for classification; server errors carry `isError: true`
// with structured info from _wrapWithPromise.
try {
await client.login(otp, forceLoginApprovedRef.current);
await doGQLConnect(client);
return;
} catch (err: unknown) {
setIsBlockPanelOpen(false);
const handled = handleLoginError(err, showError, userId, password);
if (handled === 'keep-open') {
// A dedicated modal (password reset, TOTP registration) was opened.
// Keep the login panel open to preserve form values for child modals.
setIsLoading(false);
return;
}
}
setIsBlockPanelOpen(false);
open();
setIsLoading(false);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[apiEndpoint, form, endpoints, doGQLConnect, block, open, notification, t],
);
connectUsingSessionRef.current = connectUsingSession;
/**
* Unified login error handler. Classifies errors from client.login() and
* shows the appropriate notification or opens a dedicated modal.
*
* Returns 'keep-open' when a child modal (password reset, TOTP registration)
* needs the login panel to stay open (to preserve form values). Returns
* 'reopen' for all other cases so the caller reopens the login panel.
*/
const handleLoginError = useCallback(
(
err: unknown,
showError: boolean,
userId: string,
password: string,
): 'keep-open' | 'reopen' => {
const e = err as {
isLoginError?: boolean;
isError?: boolean;
type?: string;
title?: string;
message?: string;
description?: string;
statusCode?: number;
data?: Record<string, unknown>;
};
// --- Login errors (envelope responses from /server/login) ---
if (e.isLoginError && e.data) {
const errorType = extractErrorType(e.data.type as string);
const details = ((e.data.details as string) || '') as string;
switch (errorType) {
case 'password-expired':
expiredCredentialsRef.current = { username: userId, password };
setNeedToResetPassword(true);
return 'keep-open';
case 'require-totp-registration':
setTotpRegistrationToken(
e.data.two_factor_registration_token as string,
);
setNeedsOtpRegistration(true);
return 'keep-open';
case 'require-totp-authentication':
if (showError && otpRequired) {
notification(t('login.PleaseInputOTPCode'));
}
setOtpRequired(true);
setIsLoading(false);
return 'reopen';
case 'rejected-by-hook':
if (
details.includes('Invalid TOTP code provided') ||
details.includes('Failed to validate OTP')
) {
setOtpRequired(true);
form.setFieldValue('otp', '');
setIsLoading(false);
if (showError) {
notification(t('totp.InvalidTotpCode'));
}
} else if (showError) {
notification(t('error.LoginFailed'), details);
}
return 'reopen';
case 'active-login-session-exists':
if (forceLoginApprovedRef.current) {
// Force-login was already approved but server still returned 409.
logger.error(
'Force login failed: server returned 409 after force approval',
);
}
if (showError) {
modal.confirm({
title: t('login.ConcurrentSessionTitle'),
content: t('login.ConcurrentSessionDetected'),
okText: t('login.Login'),
cancelText: t('button.Cancel'),
centered: true,
zIndex: 10001,
onOk: () => {
forceLoginApprovedRef.current = true;
setIsLoading(true);
connectUsingSessionRef.current?.();
},
});
}
return 'reopen';
case 'login-session-expired':
if (showError) {
notification(t('login.SessionExpired'));
}
return 'reopen';
case 'auth-failed':
if (showError) {
if (details.toLowerCase().includes('email verification')) {
notification(t('login.EmailVerificationRequired'));
} else {
notification(t('error.LoginInformationMismatch'));
}
}
return 'reopen';
case 'monitor-role-login-forbidden':
if (showError) {
notification(t('login.MonitorRoleLoginForbidden'));
}
return 'reopen';
default:
// Legacy string-based fallbacks for backward compatibility
// with older backends that may not send a `type` field.
if (details.includes('User credential mismatch.')) {
if (showError) {
notification(t('error.LoginInformationMismatch'));
}
} else if (
details.includes('You must register Two-Factor Authentication.')
) {
setTotpRegistrationToken(
e.data.two_factor_registration_token as string,
);
setNeedsOtpRegistration(true);
return 'keep-open';
} else if (
details.includes(
'You must authenticate using Two-Factor Authentication.',
) ||
details.includes('OTP not provided')
) {
if (showError && otpRequired) {
notification(t('login.PleaseInputOTPCode'));
}
setOtpRequired(true);
setIsLoading(false);
return 'reopen';
} else if (
details.includes('Invalid TOTP code provided') ||
details.includes('Failed to validate OTP')
) {
setOtpRequired(true);
form.setFieldValue('otp', '');
setIsLoading(false);
if (showError) {
notification(t('totp.InvalidTotpCode'));
}
return 'reopen';
} else if (details.indexOf('Password expired on ') === 0) {
expiredCredentialsRef.current = { username: userId, password };
setNeedToResetPassword(true);
return 'keep-open';
} else if (showError) {
const fallbackMessage =
(typeof e.title === 'string' && e.title.trim()) ||
(typeof e.message === 'string' && e.message.trim()) ||
t('error.UnknownError');
notification(fallbackMessage);
}
return 'reopen';
}
}
// --- Server errors (429, 502, 503, etc. from _wrapWithPromise) ---
if (e.isError && e.type) {
const errorType = extractErrorType(e.type);
if (showError) {
switch (errorType) {
case 'login-blocked':
case 'too-many-requests':
case 'rate-limit-exceeded':
notification(t('error.TooManyLoginFailures'));
break;
case 'server-frozen':
notification(t('login.ServerMaintenance'));
break;
case 'bad-gateway':
notification(t('login.ServerUnreachable'));
break;
case 'invalid-api-params':
case 'generic-bad-request':
notification(e.title || t('error.LoginFailed'));
break;
default:
notification(
e.title || t('error.LoginFailed'),
e.description || e.message,
);
break;
}
}
return 'reopen';
}
// --- Unstructured errors (network failures, etc.) ---
if (showError) {
if (e.message) {
notification(e.title || t('error.LoginFailed'), e.message);
} else {
notification(t('error.LoginInformationMismatch'));
}
}
return 'reopen';
},
[notification, t, otpRequired, form, modal, logger],
);
const handleGQLError = useCallback(
(err: unknown, showError: boolean) => {
setIsBlockPanelOpen(false);
if (showError) {
const e = err as {
title?: string;
message?: string;
status?: number;
};
if (e.message) {
if (e.status === 408) {
notification(
t('error.LoginSucceededManagerNotResponding'),
e.message,
);
} else {
notification(e.title || t('error.LoginFailed'), e.message);
}
} else {
notification(t('error.LoginInformationMismatch'));
}
}
open();
setIsLoading(false);
},
[notification, t, open],
);
const connectUsingAPI = useCallback(
async (_showError = true, endpointOverride?: string) => {
const ep = (endpointOverride ?? apiEndpoint).trim();
const apiKey = form.getFieldValue('api_key') || '';
const secretKey = form.getFieldValue('secret_key') || '';
const { client } = createBackendAIClient(apiKey, secretKey, ep, 'API');
clientRef.current = client;
client.ready = false;
try {
await client.get_manager_version();
await doGQLConnect(client);
} catch {
notification(t('error.CannotConnectToServer'));
setIsLoading(false);
}
},
[apiEndpoint, form, doGQLConnect, notification, t],
);
const handleLogin = useCallback(async () => {
setLoginError(null);
const loginAttempt = (globalThis as any).backendaioptions.get(
'login_attempt',
0,
'general',
);
const lastLogin = (globalThis as any).backendaioptions.get(
'last_login',
Math.floor(Date.now() / 1000),
'general',
);
const currentTime = Math.floor(Date.now() / 1000);
if (
loginAttempt >= loginConfig.login_attempt_limit &&
currentTime - lastLogin > loginConfig.login_block_time
) {
(globalThis as any).backendaioptions.set(
'last_login',
currentTime,
'general',
);
(globalThis as any).backendaioptions.set('login_attempt', 0, 'general');
} else if (loginAttempt >= loginConfig.login_attempt_limit) {
(globalThis as any).backendaioptions.set(
'last_login',
currentTime,
'general',
);
(globalThis as any).backendaioptions.set(
'login_attempt',
loginAttempt + 1,
'general',
);
notification(t('login.TooManyAttempt'));
return;
} else {
(globalThis as any).backendaioptions.set(
'login_attempt',
loginAttempt + 1,
'general',
);
}
const epInput = form.getFieldValue('api_endpoint') || apiEndpoint;
const ep = epInput.replace(/\/+$/, '').trim();
setApiEndpoint(ep);
if (ep === '') {
notification(t('login.APIEndpointEmpty'));
return;
}
setIsLoading(true);
if ((globalThis as Record<string, unknown>).isElectron) {
await loadConfigFromWebServer(ep);
}
if (connectionMode === 'SESSION') {
const userId = (form.getFieldValue('user_id') || '').trim();
const password = form.getFieldValue('password') || '';
if (
!userId ||
userId === 'undefined' ||
!password ||
password === 'undefined'
) {
notification(t('login.PleaseInputLoginInfo'));
setIsLoading(false);
return;
}
await connectUsingSession(true, ep);
} else {
const apiKey = form.getFieldValue('api_key') || '';
const secretKey = form.getFieldValue('secret_key') || '';
if (
!apiKey ||
apiKey === 'undefined' ||
!secretKey ||
secretKey === 'undefined'
) {
notification(t('login.PleaseInputLoginInfo'));
setIsLoading(false);
return;
}
await connectUsingAPI(true, ep);
}
}, [
loginConfig,
form,
apiEndpoint,
connectionMode,
connectUsingSession,
connectUsingAPI,
notification,
t,
]);
// Resolve the effective API endpoint from state or localStorage.
const resolveEndpoint = useCallback((): string => {
let ep = apiEndpoint;
if (ep === '') {
const stored = localStorage.getItem('backendaiwebui.api_endpoint');
if (stored) {
ep = stored.replace(/^"+|"+$/g, '');
setApiEndpoint(ep);
}
}
return ep.trim().replace(/\/+$/, '');
}, [apiEndpoint]);
// Login method: attempts silent or interactive login depending on mode.
// Used by the orchestration hook as `onLogin`.
const login = useCallback(
async (showError = true) => {
const ep = resolveEndpoint();
if ((globalThis as Record<string, unknown>).isElectron) {
await loadConfigFromWebServer(ep);
}
if (connectionMode === 'SESSION') {
await connectUsingSession(showError, ep);
} else if (connectionMode === 'API') {
await connectUsingAPI(showError, ep);
} else {
open();
}
},
[
resolveEndpoint,
connectionMode,
connectUsingSession,
connectUsingAPI,
open,
],
);
// Check if a session login exists on the server.
// Used by the orchestration hook as `onCheckLogin`.
const checkLogin = useCallback(async (): Promise<boolean> => {
const ep = resolveEndpoint();
if ((globalThis as Record<string, unknown>).isElectron) {
await loadConfigFromWebServer(ep);
}
if (connectionMode === 'SESSION') {
if (ep === '') return false;
const { client } = createBackendAIClient('', '', ep, 'SESSION');
clientRef.current = client;
try {
await client.get_manager_version();
const isLogon = await client.check_login();
return !!isLogon;
} catch {
return false;
}
}
return false;
}, [resolveEndpoint, connectionMode]);
// Log out the current session on the server.
// Used by the orchestration hook as `onLogoutSession`.
const logoutSession = useCallback(async (): Promise<void> => {
if (clientRef.current) {
await clientRef.current.logout();
}
}, []);
// Orchestrate the initial login flow (auto-logout, tab counting, etc.)
// This replaces the Lit shell's firstUpdated() login orchestration.
useLoginOrchestration({
onLogin: login,
onOpen: open,
onBlock: block,
onCheckLogin: checkLogin,
onLogoutSession: logoutSession,
apiEndpoint,
connectionMode,
});
const handleConnectionModeChange = useCallback(
(mode: ConnectionMode) => {
if (!loginConfig.change_signin_support) return;
setConnectionMode(mode);
setLoginError(null);
localStorage.setItem('backendaiwebui.connection_mode', mode);
},
[loginConfig.change_signin_support],
);
const showSignupDialog = useCallback(
(preloadToken?: string) => {
const ep =
(form.getFieldValue('api_endpoint') || '').replace(/\/+$/, '') ||
apiEndpoint.trim();
if (ep === '') {
notification(t('error.APIEndpointIsEmpty'));
return;
}
setApiEndpoint(ep);
setSignupPreloadedToken(preloadToken);
setShowSignupModal(true);
},
[form, apiEndpoint, notification, t],
);
const deleteEndpoint = useCallback(
(endpoint: string) => {
const updated = endpoints.filter((e) => e !== endpoint);
setEndpoints(updated);
(globalThis as any).backendaioptions.set('endpoints', updated);
},
[endpoints],
);
const endpointMenuItems: MenuProps['items'] = [
{ key: 'header', label: t('login.EndpointHistory'), disabled: true },
...(endpoints.length === 0
? [{ key: 'empty', label: t('login.NoEndpointSaved') }]
: endpoints.map((ep) => ({
key: ep,
label: (
<BAIFlex justify="between" align="center" style={{ minWidth: 300 }}>
<span>{ep}</span>
<Button
type="text"
size="small"
danger
onClick={(e) => {
e.stopPropagation();
deleteEndpoint(ep);
}}
>
{t('button.Delete')}
</Button>