-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
983 lines (861 loc) · 39.6 KB
/
Copy pathauth.js
File metadata and controls
983 lines (861 loc) · 39.6 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
// ==================== 用户认证模块 ====================
// API基础URL(开发环境使用本地服务器,生产环境可配置)
// 注意:如果要测试本地服务器,确保浏览器访问的是 http://localhost:3000
const API_BASE_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname.startsWith('192.168.')
? 'http://localhost:3000/api'
: '/gtr/api'; // 生产环境使用相对路径,由Nginx反向代理处理
// 获取当前会话
function getUserSession() {
try {
const session = localStorage.getItem('userSession');
console.log('🔍 获取当前会话:', session ? '存在' : '不存在');
if (session) {
const parsedSession = JSON.parse(session);
console.log('📄 会话内容:', {
username: parsedSession.user?.username,
userId: parsedSession.user?.id,
hasToken: !!parsedSession.token,
loginTime: parsedSession.loginTime
});
// 会话数据版本迁移:检查是否包含AuthMe字段
if (parsedSession && parsedSession.user) {
const user = parsedSession.user;
const hasAuthmeFields = 'authmeBound' in user || 'authmeUsername' in user;
if (!hasAuthmeFields) {
console.warn('检测到旧版本会话数据(缺少AuthMe字段),正在清除并提示重新登录...');
console.log('当前用户数据:', user);
// 清除旧会话
localStorage.removeItem('userSession');
// 显示提示消息(如果toast函数可用)
if (typeof showToast === 'function') {
showToast('系统已升级,请重新登录以获取完整功能', 3000);
}
return null;
}
}
return parsedSession;
}
} catch (error) {
console.error('Error parsing user session:', error);
localStorage.removeItem('userSession');
}
return null;
}
// 保存会话
function saveUserSession(sessionData) {
try {
console.log('💾 保存会话数据:', {
username: sessionData.user?.username,
userId: sessionData.user?.id,
token: sessionData.token ? '***' : null,
timestamp: new Date().toISOString()
});
localStorage.setItem('userSession', JSON.stringify(sessionData));
// 验证保存是否成功
const saved = localStorage.getItem('userSession');
if (saved) {
const parsed = JSON.parse(saved);
console.log('✅ 验证保存结果:', {
savedUsername: parsed.user?.username,
matchesExpected: parsed.user?.username === sessionData.user?.username
});
if (parsed.user?.username !== sessionData.user?.username) {
console.error('❌ 严重错误:保存的会话用户名与预期不符!', {
expected: sessionData.user?.username,
actual: parsed.user?.username
});
}
}
} catch (error) {
console.error('Error saving user session:', error);
}
}
// 清除会话
function clearUserSession() {
localStorage.removeItem('userSession');
}
// Token过期弹窗防护标志(防止多个API同时触发弹窗)
let _isShowingTokenExpiredDialog = false;
// 处理Token过期:清除会话并弹出登录窗口
function handleTokenExpired() {
if (_isShowingTokenExpiredDialog) return;
_isShowingTokenExpiredDialog = true;
console.log('🔒 Token已过期,正在弹出登录窗口...');
clearUserSession();
if (typeof showToast === 'function') {
showToast(strings.preferences?.token_expired?.[lang] || '登录已过期,请重新登录', 3000);
}
showLoginDialog().then(() => {
_isShowingTokenExpiredDialog = false;
}).catch(() => {
_isShowingTokenExpiredDialog = false;
});
}
// 全局Fetch拦截器:自动检测Token过期并弹出登录窗口
(function _setupAuthInterceptor() {
const _originalFetch = window.fetch;
window.fetch = async function (...args) {
const response = await _originalFetch.apply(this, args);
// 检查认证相关错误(401/403 且后端标记 requiresReLogin)
if (response.status === 401 || response.status === 403) {
try {
const clone = response.clone();
const data = await clone.json();
if (data && data.requiresReLogin) {
handleTokenExpired();
}
} catch (e) {
// 非JSON响应或解析错误,忽略
}
}
return response;
};
})();
// 检查是否已登录
function isLoggedIn() {
const session = getUserSession();
return !!(session && session.token);
}
// 获取当前用户信息
function getCurrentUser() {
const session = getUserSession();
return session ? session.user : null;
}
// 通过用户名获取authmeUsername
async function getAuthmeUsernameByUsername(username = getCurrentUser()?.username) {
// 首先检查是否是当前登录用户
const currentUser = getCurrentUser();
if (currentUser && currentUser.username === username) {
console.log('获取当前用户的AuthMe用户名:', {
username: currentUser.username,
authmeUsername: currentUser.authmeUsername,
authmeBound: currentUser.authmeBound
});
return currentUser.authmeUsername || null;
}
// 如果不是当前用户,尝试通过API查询(需要认证)
const session = getUserSession();
if (!session || !session.token) {
console.warn('无法查询其他用户的authmeUsername:未登录');
return null;
}
try {
// 这里可以调用一个专门的API端点来查询
// 目前先返回null,因为后端没有提供公开查询接口
// 如果需要,可以在后端添加 /api/users/:username/authme 接口
console.warn('查询其他用户的authmeUsername功能尚未实现', { targetUsername: username });
return null;
} catch (error) {
console.error('查询authmeUsername失败:', error);
return null;
}
}
window.getAuthmeUsernameByUsername = getAuthmeUsernameByUsername;
// 验证Token有效性
async function validateToken() {
const session = getUserSession();
if (!session || !session.token) {
console.log('⚠️ 没有有效的会话或token');
return false;
}
console.log('🔐 开始验证Token,当前用户:', session.user?.username);
try {
const response = await fetch(`${API_BASE_URL}/auth/me`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${session.token}`,
'Content-Type': 'application/json'
}
});
console.log('📡 Token验证响应状态:', response.status);
if (!response.ok) {
console.warn('❌ Token验证失败,清除会话');
// 全局fetch拦截器会自动检测requiresReLogin并弹出登录窗口
// 这里作为兜底,确保会话被清除
if (!_isShowingTokenExpiredDialog) {
clearUserSession();
}
return false;
}
const data = await response.json();
const apiUser = data.data.user;
const localUser = session.user;
console.log('📥 Token验证返回数据:', {
success: data.success,
apiUsername: apiUser.username,
apiUserId: apiUser.id,
localUsername: localUser.username,
localUserId: localUser.id
});
// 关键检查:验证API返回的用户ID与token中的用户ID是否一致
try {
const tokenPayload = JSON.parse(atob(session.token.split('.')[1]));
console.log('🔍 Token中的用户ID:', tokenPayload.id);
if (apiUser.id !== tokenPayload.id) {
console.error('❌ 严重错误:API返回的用户ID与Token中的ID不一致!');
console.error(' - Token中的ID:', tokenPayload.id);
console.error(' - API返回的ID:', apiUser.id);
console.error(' - 这可能是JWT_SECRET配置错误或安全问题');
console.error(' - 为了保护用户会话,将清除当前session并强制重新登录');
// 强制重新登录
handleTokenExpired();
return false;
}
} catch(e) {
console.error('Token解码失败:', e);
}
// 验证通过,更新会话中的用户信息(合并字段,避免覆盖AuthMe字段)
const oldUsername = session.user?.username;
session.user = {
...session.user, // 保留原有字段
...data.data.user // 用后端返回的字段更新
};
console.log('🔄 更新会话用户信息:', {
oldUsername: oldUsername,
newUsername: session.user.username,
changed: oldUsername !== session.user.username
});
saveUserSession(session);
return true;
} catch (error) {
console.error('Token validation error:', error);
// 网络错误时不立即清除会话,允许离线使用
return true;
}
}
// 用户注册
async function registerUser(username, password, email = null, authmeUsername = null, authmePassword = null, verificationNote = null) {
try {
const requestBody = { username, password, email };
if (authmeUsername && authmePassword) {
requestBody.authmeUsername = authmeUsername;
requestBody.authmePassword = authmePassword;
} else if (verificationNote) {
requestBody.verificationNote = verificationNote;
}
const response = await fetch(`${API_BASE_URL}/auth/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
const data = await response.json();
if (!response.ok) {
if (data.errorCode === 'AUTHME_ALREADY_BOUND') {
throw new Error(data.message || strings.preferences.authme_already_bound[lang] || '该AuthMe账户已被其他用户绑定');
} else if (data.requiresAuthMeVerification) {
throw new Error(data.message || strings.preferences.authme_verification_failed[lang] || 'AuthMe验证失败');
}
throw new Error(data.message || 'Registration failed');
}
if (data.success) {
if (data.pendingReview) {
return { success: true, pendingReview: true, user: data.data.user };
}
saveUserSession({
token: data.data.token,
user: data.data.user,
loginTime: new Date().toISOString()
});
return { success: true, user: data.data.user };
}
return { success: false, message: data.message };
} catch (error) {
console.error('Registration error:', error);
return {
success: false,
message: error.message || 'Network error, please try again'
};
}
}
// 用户登录
async function loginUser(username, password) {
try {
const response = await fetch(`${API_BASE_URL}/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
console.log('登录API响应:', {
success: data.success,
user: data.data?.user,
hasAuthmeFields: {
authmeBound: data.data?.user?.authmeBound,
authmeUsername: data.data?.user?.authmeUsername,
authmeDisplayName: data.data?.user?.authmeDisplayName,
authmeAvatarUrl: data.data?.user?.authmeAvatarUrl
}
});
if (!response.ok) {
throw new Error(data.message || 'Login failed');
}
if (data.success) {
console.log('保存会话数据:', {
token: data.data.token ? '***' : null,
user: data.data.user
});
saveUserSession({
token: data.data.token,
user: data.data.user,
loginTime: new Date().toISOString()
});
return { success: true, user: data.data.user };
}
return { success: false, message: data.message };
} catch (error) {
console.error('Login error:', error);
return {
success: false,
message: error.message || 'Network error, please try again'
};
}
}
// 用户登出
async function logoutUser() {
const session = getUserSession();
if (session && session.token) {
try {
await fetch(`${API_BASE_URL}/auth/logout`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${session.token}`,
'Content-Type': 'application/json'
}
});
} catch (error) {
console.error('Logout API error:', error);
// 即使API调用失败,也要清除本地会话
}
}
clearUserSession();
return { success: true };
}
// 修改密码
async function changePassword(currentPassword, newPassword) {
const session = getUserSession();
if (!session || !session.token) {
return { success: false, message: 'Not logged in' };
}
try {
const response = await fetch(`${API_BASE_URL}/auth/password`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${session.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ currentPassword, newPassword })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Password change failed');
}
return { success: data.success, message: data.message };
} catch (error) {
console.error('Password change error:', error);
return {
success: false,
message: error.message || 'Network error, please try again'
};
}
}
// 显示登录对话框
async function showLoginDialog() {
// 从stations_info.json中随机选取一项的cover作为登录对话框的背景图
let backgroundImage = '';
let stationName = '';
let stationCode = '';
try {
const selectedImage = await window.getRandomCoverImage();
if (selectedImage) {
backgroundImage = selectedImage.img;
stationName = selectedImage.desc;
stationCode = selectedImage.link;
}
} catch (error) {
console.error('Failed to load cover image:', error);
}
return new Promise((resolve) => {
// 创建登录对话框内容
const dialogContent = document.createElement('div');
dialogContent.className = 'login-dialog-content';
dialogContent.innerHTML = `
<div class="login-form">
<div class="form-error" id="login-error" style="display: none; color: crimson; margin-top: 8px; font-size: 14px;"></div>
<div class="form-group">
<label for="login-username">${strings.preferences.username[lang] || '用户名'}</label>
<input type="text" id="login-username" class="form-input" placeholder="${strings.preferences.username_placeholder[lang] || '输入用户名'}" autocomplete="username">
</div>
<div class="form-group">
<label for="login-password">${strings.preferences.password[lang] || '密码'}</label>
<input type="password" id="login-password" class="form-input" placeholder="${strings.preferences.password_placeholder[lang] || '输入密码'}" autocomplete="current-password">
</div>
</div>
`;
const dialogButtons = document.createElement('div');
dialogButtons.className = 'dialog-buttons';
dialogButtons.innerHTML = `
<button class="btn" id="login-register-btn">${strings.preferences.register[lang] || '注册'}</button>
<button class="btn active" id="login-submit-btn">${strings.preferences.login[lang] || '登录'}</button>
`;
// 显示对话框
pushDialog(dialogContent, 'custom', strings.preferences.login[lang] || '登录', false, backgroundImage, dialogButtons)
.then(() => {
resolve(false);
});
// 绑定事件
const usernameInput = dialogContent.querySelector('#login-username');
const passwordInput = dialogContent.querySelector('#login-password');
const errorDiv = dialogContent.querySelector('#login-error');
const submitBtn = dialogButtons.querySelector('#login-submit-btn');
const registerBtn = dialogButtons.querySelector('#login-register-btn');
const dialogParent = dialogContent.parentNode;
const stationNameElement = document.createElement('div');
stationNameElement.classList.add('station-name');
stationNameElement.innerHTML = '<span class="material-symbols-outlined" style="font-size: 1.2em;">photo_camera</span><a href="'+stationCode+'" target="_blank" style="color: var(--color-text-secondary)">'+stationName+'</a>';
stationNameElement.style.display = stationName ? 'flex' : 'none';
stationNameElement.style.flexDirection = 'row';
stationNameElement.style.alignItems = 'center';
stationNameElement.style.gap = '2px';
stationNameElement.style.justifyContent = 'flex-end';
stationNameElement.style.transform = 'translateY(-0.5em)';
stationNameElement.style.padding = '0 1em';
stationNameElement.style.color = 'var(--color-text-secondary)';
stationNameElement.style.fontSize = '0.9em';
stationNameElement.style.width = '-webkit-fill-available';
stationNameElement.style.height = '0';
stationNameElement.style.textShadow = '0 2px 12px var(--color-background-card-solid);';
dialogParent.insertBefore(stationNameElement, dialogContent);
// 回车提交
passwordInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
submitBtn.click();
}
});
usernameInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
passwordInput.focus();
}
});
// 登录按钮点击事件
submitBtn.addEventListener('click', async () => {
const username = usernameInput.value.trim();
const password = passwordInput.value;
// 验证输入
if (!username || !password) {
errorDiv.textContent = strings.preferences.login_error_empty[lang] || '请输入用户名和密码';
errorDiv.style.display = 'block';
return;
}
// 禁用按钮,显示加载状态
submitBtn.disabled = true;
submitBtn.textContent = strings.preferences.logging_in[lang] || '登录中...';
errorDiv.style.display = 'none';
// 调用登录API
const result = await loginUser(username, password);
if (result.success) {
// 登录成功,关闭对话框并刷新页面
showToast(strings.preferences.login_success[lang] || '登录成功', 2000);
setTimeout(() => {
location.reload();
}, 500);
resolve(true);
} else {
// 登录失败,显示错误
errorDiv.textContent = result.message;
errorDiv.style.display = 'block';
submitBtn.disabled = false;
submitBtn.textContent = strings.preferences.login[lang] || '登录';
}
});
// 注册按钮点击事件
registerBtn.addEventListener('click', async () => {
// 关闭登录对话框,打开注册对话框
const dialogElement = dialogContent.closest('.dialog-overlay');
if (dialogElement) {
dialogElement.remove();
}
const registerResult = await showRegisterDialog();
if (registerResult) {
// 注册成功后自动登录
resolve(true);
window.location.reload();
} else {
// 注册取消或失败,重新显示登录对话框
showLoginDialog().then(resolve);
}
});
// 聚焦到用户名输入框
setTimeout(() => {
usernameInput.focus();
}, 100);
});
}
// 显示注册对话框
async function showRegisterDialog() {
return new Promise((resolve) => {
let useAuthme = true;
const dialogContent = document.createElement('div');
dialogContent.className = 'register-dialog-content';
dialogContent.innerHTML = `
<div class="register-form">
<div class="form-group">
<label for="register-username">${strings.preferences.username[lang] || '用户名'}</label>
<input type="text" id="register-username" class="form-input" placeholder="${strings.preferences.username_placeholder[lang] || '输入用户名(3-20个字符)'}" autocomplete="username">
</div>
<div class="form-group">
<label for="register-email">${strings.preferences.email[lang] || '邮箱(可选)'}</label>
<input type="email" id="register-email" class="form-input" placeholder="${strings.preferences.email_placeholder[lang] || '输入邮箱地址'}" autocomplete="email">
</div>
<div class="form-group">
<label for="register-password">${strings.preferences.password[lang] || '密码'}</label>
<input type="password" id="register-password" class="form-input" placeholder="${strings.preferences.password_placeholder_register[lang] || '输入密码(至少6个字符)'}" autocomplete="new-password">
</div>
<div class="form-group">
<label for="register-confirm-password">${strings.preferences.confirm_password[lang] || '确认密码'}</label>
<input type="password" id="register-confirm-password" class="form-input" placeholder="${strings.preferences.confirm_password_placeholder[lang] || '再次输入密码'}" autocomplete="new-password">
</div>
<div id="authme-section">
<div class="form-group">
<label for="register-authme-username">${strings.preferences.authme_username[lang] || '服务器账号用户名'} <span style="color: crimson;">*</span></label>
<input type="text" id="register-authme-username" class="form-input" placeholder="${strings.preferences.authme_username_placeholder[lang] || '输入服务器账号用户名'}" autocomplete="off">
</div>
<div class="form-group">
<label for="register-authme-password">${strings.preferences.authme_password[lang] || '服务器账号密码'} <span style="color: crimson;">*</span></label>
<input type="password" id="register-authme-password" class="form-input" placeholder="${strings.preferences.authme_password_placeholder[lang] || '输入服务器账号密码'}" autocomplete="off">
</div>
<div style="font-size: 12px; color: var(--color-text-secondary); transform: translateY(-2em);">
${strings.preferences.authme_required[lang] || '必须验证服务器账户才能注册'}
</div>
</div>
<div id="verification-section" style="display: none;">
<div class="form-group">
<label for="register-verification-note">${strings.preferences.verification_note[lang] || '申请说明'} <span style="color: crimson;">*</span></label>
<textarea id="register-verification-note" class="form-input" rows="4" placeholder="${strings.preferences.verification_note_placeholder[lang] || '请说明您注册的原因'}" style="resize: vertical;"></textarea>
</div>
<div style="font-size: 12px; color: var(--color-text-secondary); transform: translateY(-1em);">
${strings.preferences.pending_review[lang] || '提交后需等待管理员审核'}
</div>
</div>
<div id="toggle-authme-link" style="text-align: center; margin-top: -0.5em;">
<a href="#" style="color: var(--color-primary); font-size: 13px; text-decoration: none;">${strings.preferences.no_authme_account[lang] || '没有服务器账号?'}</a>
</div>
<div class="form-error" id="register-error" style="display: none; color: crimson; margin-top: 8px; font-size: 14px;"></div>
</div>
`;
const dialogButtons = document.createElement('div');
dialogButtons.className = 'dialog-buttons';
dialogButtons.innerHTML = `
<button class="btn btn-secondary" id="register-cancel-btn">${strings.general.cancel[lang] || '取消'}</button>
<button class="btn btn-primary" id="register-submit-btn">${strings.preferences.register[lang] || '注册'}</button>
`;
pushDialog(dialogContent, 'custom', strings.preferences.register[lang] || '注册', false, '', dialogButtons)
.then(() => {
resolve(false);
});
const usernameInput = dialogContent.querySelector('#register-username');
const emailInput = dialogContent.querySelector('#register-email');
const passwordInput = dialogContent.querySelector('#register-password');
const confirmPasswordInput = dialogContent.querySelector('#register-confirm-password');
const errorDiv = dialogContent.querySelector('#register-error');
const submitBtn = dialogButtons.querySelector('#register-submit-btn');
const cancelBtn = dialogButtons.querySelector('#register-cancel-btn');
const authmeUsernameInput = dialogContent.querySelector('#register-authme-username');
const authmePasswordInput = dialogContent.querySelector('#register-authme-password');
const verificationNoteInput = dialogContent.querySelector('#register-verification-note');
const authmeSection = dialogContent.querySelector('#authme-section');
const verificationSection = dialogContent.querySelector('#verification-section');
const toggleLink = dialogContent.querySelector('#toggle-authme-link a');
function switchMode() {
useAuthme = !useAuthme;
if (useAuthme) {
authmeSection.style.display = '';
verificationSection.style.display = 'none';
toggleLink.textContent = strings.preferences.no_authme_account[lang] || '没有服务器账号?';
} else {
authmeSection.style.display = 'none';
verificationSection.style.display = '';
toggleLink.textContent = strings.preferences.register_with_authme[lang] || '使用服务器账号注册';
}
errorDiv.style.display = 'none';
}
toggleLink.addEventListener('click', (e) => {
e.preventDefault();
switchMode();
});
confirmPasswordInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') submitBtn.click();
});
authmePasswordInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') submitBtn.click();
});
cancelBtn.addEventListener('click', () => {
const dialogElement = dialogContent.closest('.dialog-overlay');
if (dialogElement) dialogElement.remove();
resolve(false);
});
submitBtn.addEventListener('click', async () => {
const username = usernameInput.value.trim();
const email = emailInput.value.trim();
const password = passwordInput.value;
const confirmPassword = confirmPasswordInput.value;
if (!username || !password || !confirmPassword) {
errorDiv.textContent = strings.preferences.register_error_empty[lang] || '请填写所有必填字段';
errorDiv.style.display = 'block';
return;
}
if (username.length < 3 || username.length > 20) {
errorDiv.textContent = strings.preferences.register_error_username[lang] || '用户名长度必须在3-20个字符之间';
errorDiv.style.display = 'block';
return;
}
if (password.length < 6) {
errorDiv.textContent = strings.preferences.register_error_password[lang] || '密码长度至少为6个字符';
errorDiv.style.display = 'block';
return;
}
if (password !== confirmPassword) {
errorDiv.textContent = strings.preferences.register_error_password_mismatch[lang] || '两次输入的密码不一致';
errorDiv.style.display = 'block';
return;
}
submitBtn.disabled = true;
submitBtn.textContent = strings.preferences.registering[lang] || '注册中...';
errorDiv.style.display = 'none';
let result;
if (useAuthme) {
const authmeUsername = authmeUsernameInput.value.trim();
const authmePassword = authmePasswordInput.value;
if (!authmeUsername || !authmePassword) {
errorDiv.textContent = strings.preferences.authme_verification_failed[lang] + ': ' + (strings.preferences.authme_account_not_found[lang] || '请输入AuthMe用户名和密码');
errorDiv.style.display = 'block';
submitBtn.disabled = false;
submitBtn.textContent = strings.preferences.register[lang] || '注册';
return;
}
result = await registerUser(username, password, email || null, authmeUsername, authmePassword);
} else {
const verificationNote = verificationNoteInput.value.trim();
if (!verificationNote || verificationNote.length < 10) {
errorDiv.textContent = strings.preferences.verification_note_required[lang] || '请填写申请说明(至少10个字符)';
errorDiv.style.display = 'block';
submitBtn.disabled = false;
submitBtn.textContent = strings.preferences.register[lang] || '注册';
return;
}
result = await registerUser(username, password, email || null, null, null, verificationNote);
}
if (result.success) {
if (result.pendingReview) {
showToast(strings.preferences.register_pending_review[lang] || '注册申请已提交,请等待管理员审核', 4000);
} else {
showToast(strings.preferences.register_success[lang] || '注册成功', 2000);
}
const dialogElement = dialogContent.closest('.modal-overlay');
if (dialogElement) {
closeDialog(dialogElement);
}
if (!result.pendingReview) {
setTimeout(() => { window.location.reload(); }, 500);
}
resolve(true);
} else {
errorDiv.textContent = result.message;
errorDiv.style.display = 'block';
submitBtn.disabled = false;
submitBtn.textContent = strings.preferences.register[lang] || '注册';
}
});
setTimeout(() => {
usernameInput.focus();
}, 100);
});
}
// 显示登出确认对话框
async function showLogoutDialog() {
const confirmed = await pushDialog(
strings.preferences.logout_confirm[lang] || '确定要登出吗?',
'confirm-danger'
);
if (confirmed) {
const result = await logoutUser();
if (result.success) {
showToast(strings.preferences.logout_success[lang] || '已登出', 2000);
setTimeout(() => {
location.reload();
}, 500);
}
}
}
// 更新登录状态UI
async function updateLoginStatusUI() {
const loginStatus = document.getElementById('loginStatus');
const toggleLogin = document.getElementById('toggleLogin');
if (!loginStatus || !toggleLogin) return;
const user = getCurrentUser();
if (user) {
const authmeUsername = await getAuthmeUsernameByUsername(user.username) || '';
console.log('已登录', user);
loginStatus.innerHTML = '<img src="https://mc-heads.hydcraft.cn/avatar/' + (authmeUsername || 'MHF_Steve') + '/24.png" alt="' + user.username + '" style="border-radius: 4px"><span>' + user.username + '</span>';
loginStatus.style.display = 'flex';
loginStatus.style.alignItems = 'center';
loginStatus.style.gap = '0.5em';
toggleLogin.textContent = strings.preferences.logout[lang] || '登出';
toggleLogin.style.color = 'crimson';
toggleLogin.removeEventListener('click', handleLoginClick);
toggleLogin.addEventListener('click', handleLogoutClick);
const cloudSyncItem = document.getElementById('cloudSyncItem');
if (cloudSyncItem) cloudSyncItem.style.display = '';
if (user.username === 'admin') {
const adminLink = document.getElementById('adminLink');
if (adminLink) adminLink.style.display = 'inline-block';
}
const verificationStatus = user.verificationStatus || 'approved';
if (verificationStatus === 'pending') {
showToast(strings.preferences.account_pending_review[lang] || '您的账户正在等待管理员审核,部分功能暂不可用。', 5000);
} else if (verificationStatus === 'rejected') {
showToast(strings.preferences.verification_rejected[lang] || '您的注册申请未通过审核', 5000);
}
} else {
// 未登录状态
loginStatus.textContent = strings.preferences.not_logged_in[lang] || '未登录';
toggleLogin.textContent = strings.preferences.login[lang] || '登录';
toggleLogin.style.color = 'var(--color-primary)';
// 移除旧的监听器,添加新的
toggleLogin.removeEventListener('click', handleLogoutClick);
toggleLogin.addEventListener('click', handleLoginClick);
// Hide cloud sync status
const cloudSyncItem = document.getElementById('cloudSyncItem');
if (cloudSyncItem) cloudSyncItem.style.display = 'none';
// 隐藏管理入口
const adminLink = document.getElementById('adminLink');
if (adminLink) {
adminLink.style.display = 'none';
}
}
window.dispatchEvent(new CustomEvent('authStateChanged', { detail: { loggedIn: !!user } }));
}
// 登录按钮点击处理
async function handleLoginClick() {
await showLoginDialog();
}
// 登出按钮点击处理
async function handleLogoutClick() {
await showLogoutDialog();
}
// 初始化认证系统
async function initAuth() {
console.log('🚀 初始化认证系统...');
const session = getUserSession();
if (session && session.token) {
console.log('📋 发现已保存的会话,用户:', session.user?.username);
const isValid = await validateToken();
if (!isValid) {
console.log('❌ Token无效或已过期');
} else {
console.log('✅ Token验证成功');
}
} else {
console.log('ℹ️ 没有已保存的会话');
}
updateLoginStatusUI();
}
function isVerified() {
const user = getCurrentUser();
if (!user) return false;
if (user.username === 'admin') return true;
return (user.verificationStatus || 'approved') === 'approved';
}
function getVerificationStatus() {
const user = getCurrentUser();
if (!user) return null;
if (user.username === 'admin') return 'approved';
return user.verificationStatus || 'approved';
}
// 获取当前用户的设备列表
async function getDevices() {
const session = getUserSession();
if (!session || !session.token) {
return { success: false, message: 'Not logged in' };
}
try {
const response = await fetch(`${API_BASE_URL}/user/devices`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${session.token}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (!response.ok) throw new Error(data.message);
return data;
} catch (error) {
console.error('Get devices error:', error);
return { success: false, message: error.message || 'Network error' };
}
}
// 移除指定设备(远程登出)
async function removeDevice(deviceId) {
const session = getUserSession();
if (!session || !session.token) {
return { success: false, message: 'Not logged in' };
}
try {
const response = await fetch(`${API_BASE_URL}/user/devices/${encodeURIComponent(deviceId)}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${session.token}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (!response.ok) throw new Error(data.message);
return data;
} catch (error) {
console.error('Remove device error:', error);
return { success: false, message: error.message || 'Network error' };
}
}
// 获取登录历史记录
async function getLoginLog(limit = 50, offset = 0) {
const session = getUserSession();
if (!session || !session.token) {
return { success: false, message: 'Not logged in' };
}
try {
const response = await fetch(`${API_BASE_URL}/user/login-log?limit=${limit}&offset=${offset}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${session.token}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (!response.ok) throw new Error(data.message);
return data;
} catch (error) {
console.error('Get login log error:', error);
return { success: false, message: error.message || 'Network error' };
}
}
// 导出函数供其他模块使用
window.auth = {
isLoggedIn,
getCurrentUser,
getUserSession,
isVerified,
getVerificationStatus,
login: showLoginDialog,
logout: showLogoutDialog,
register: showRegisterDialog,
changePassword,
validateToken,
init: initAuth,
handleTokenExpired,
getDevices,
removeDevice,
getLoginLog
};