-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
3493 lines (3050 loc) · 124 KB
/
Copy pathserver.js
File metadata and controls
3493 lines (3050 loc) · 124 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
// ============ 智能考勤系统 API v3.5.1 ============
// 功能:学号登录、考勤密码保存、 自动签到订阅、邮箱VIP(Resend)、卡密系统、管理员后台
// 包含:邀请功能、系统通知配置、邮件宣传信息、时区修复、管理员删除用户、管理员代签到
// 新增:用户留言反馈系统
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const cors = require('cors');
const cron = require('node-cron');
const { spawn } = require('child_process');
const path = require('path');
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const PlantData = require('./PlantData');//zhiwu
const ControlCmd = require('./ControlCmd');
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST']
}
});
// ============ WebSocket 用户映射 ============
const userSockets = new Map();
io.on('connection', (socket) => {
console.log('🔌 WebSocket 客户端已连接:', socket.id);
socket.on('bindUser', (userId) => {
if (userId) {
userSockets.set(userId, socket.id);
console.log(`👤 用户 ${userId} 绑定 WebSocket: ${socket.id}`);
}
});
socket.on('disconnect', () => {
for (const [uid, sid] of userSockets.entries()) {
if (sid === socket.id) {
userSockets.delete(uid);
console.log(`👤 用户 ${uid} 断开 WebSocket`);
}
}
});
});
// ============ CORS 配置 ============
const allowedOrigins = [
'https://login.agai.online',
'https://api.agai.online',
'https://attendance-frontend.ag985211ag.workers.dev',
'http://localhost:3000',
'http://127.0.0.1:5500',
'http://localhost:5500'
];
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
console.log('❌ CORS 拒绝的域名:', origin);
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
optionsSuccessStatus: 200
}));
app.options('*', (req, res) => {
res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', 'true');
res.sendStatus(200);
});
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
app.use('/uploads', express.static(uploadsDir));
// ============ 数据库连接 ============
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
console.error('❌ MONGODB_URI 未设置!');
} else {
mongoose.connect(MONGODB_URI)
.then(() => console.log('✅ MongoDB 连接成功'))
.catch(err => console.error('❌ MongoDB 连接失败:', err.message));
}
// ============ 时区辅助函数 ============
function getBeijingTime(date = new Date()) {
return date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
}
// ============ 生成邀请码 ============
function generateInviteCode(length = 8) {
return crypto.randomBytes(length).toString('hex').substring(0, length).toUpperCase();
}
// ============ 数据模型 ============
const userSchema = new mongoose.Schema({
studentId: { type: String, required: true, unique: true },
name: { type: String, default: '' },
email: { type: String, default: '' },
emailVerified: { type: Boolean, default: false },
isVip: { type: Boolean, default: false },
vipExpireAt: { type: Date, default: null },
role: { type: String, enum: ['user', 'admin'], default: 'user' },
isActive: { type: Boolean, default: true },
attendancePassword: { type: String, default: 'Ahgydx@920' },
createdAt: { type: Date, default: Date.now },
lastLogin: Date,
totalSignCount: { type: Number, default: 0 },
successSignCount: { type: Number, default: 0 },
// 邀请功能字段
inviteCode: { type: String, unique: true, sparse: true },
invitedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
inviteCount: { type: Number, default: 0 },
// 二手市场收款码
payQR: {
wechat: { type: String, default: '' },
alipay: { type: String, default: '' }
},
isGuest: { type: Boolean, default: false },
source: { type: String, enum: ['attendance', 'market'], default: 'attendance' }
});
const subscriptionSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
name: { type: String, default: '晚寝签到' },
enabled: { type: Boolean, default: true },
scheduleType: { type: String, enum: ['daily', 'weekdays', 'custom'], default: 'weekdays' },
customDays: { type: [Number], default: [1, 2, 3, 4, 5] },
signTime: { type: String, default: '21:25' },
maxRetries: { type: Number, default: 3 },
notifyOnSuccess: { type: Boolean, default: true },
notifyOnFailure: { type: Boolean, default: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
const signLogSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
subscriptionId: { type: mongoose.Schema.Types.ObjectId, ref: 'Subscription' },
subscriptionName: { type: String, default: '手动签到' },
status: { type: String, enum: ['success', 'failed', 'pending'] },
message: { type: String, default: '' },
signTime: { type: Date, default: Date.now },
executedAt: { type: Date, default: Date.now }
});
const emailCodeSchema = new mongoose.Schema({
email: { type: String, required: true },
code: { type: String, required: true },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
used: { type: Boolean, default: false },
expiresAt: { type: Date, required: true },
createdAt: { type: Date, default: Date.now }
});
const cardSchema = new mongoose.Schema({
code: { type: String, required: true, unique: true },
days: { type: Number, default: 30 },
type: { type: String, enum: ['vip_30d', 'vip_90d', 'vip_365d'], default: 'vip_30d' },
status: { type: String, enum: ['unused', 'used'], default: 'unused' },
usedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
usedAt: Date,
createdAt: { type: Date, default: Date.now }
});
// 系统配置模型
const systemConfigSchema = new mongoose.Schema({
key: { type: String, required: true, unique: true },
value: mongoose.Schema.Types.Mixed,
updatedAt: { type: Date, default: Date.now }
});
// 邀请记录模型
const inviteLogSchema = new mongoose.Schema({
inviterId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
inviteeId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
rewardDays: { type: Number, default: 10 },
createdAt: { type: Date, default: Date.now }
});
// ============ 二手市场模型 ============
const marketItemSchema = new mongoose.Schema({
productNo: { type: String, unique: true, sparse: true },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
title: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
category: { type: String, enum: ['book', 'electronic', 'life', 'other'], default: 'other' },
images: { type: [String], default: [] },
paymentQR: { type: String, default: '' },
contact: {
qq: { type: String, default: '' },
wechat: { type: String, default: '' }
},
status: { type: String, enum: ['active', 'reserved', 'sold', 'removed'], default: 'active' },
views: { type: Number, default: 0 },
contactViews: { type: Number, default: 0 },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
marketItemSchema.index({ status: 1, category: 1, createdAt: -1 });
marketItemSchema.index({ title: 'text', description: 'text', productNo: 'text' });
const favoriteSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem', required: true },
createdAt: { type: Date, default: Date.now }
});
favoriteSchema.index({ userId: 1, productId: 1 }, { unique: true });
const chatRoomSchema = new mongoose.Schema({
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem' },
buyerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
sellerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
lastMessage: String,
lastMessageAt: Date,
createdAt: { type: Date, default: Date.now }
});
chatRoomSchema.index({ productId: 1, buyerId: 1 }, { unique: true });
const messageSchema = new mongoose.Schema({
roomId: { type: mongoose.Schema.Types.ObjectId, ref: 'ChatRoom', required: true },
senderId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
content: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});
const MarketItem = mongoose.models.MarketItem || mongoose.model('MarketItem', marketItemSchema);
const Favorite = mongoose.models.Favorite || mongoose.model('Favorite', favoriteSchema);
const ChatRoom = mongoose.models.ChatRoom || mongoose.model('ChatRoom', chatRoomSchema);
const Message = mongoose.models.Message || mongoose.model('Message', messageSchema);
// ============ 举报和拉黑模型 ============
const reportSchema = new mongoose.Schema({
reporterId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
targetUserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem' },
reason: { type: String, required: true },
status: { type: String, enum: ['pending', 'handled', 'dismissed'], default: 'pending' },
createdAt: { type: Date, default: Date.now }
});
const blockSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
blockedUserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
createdAt: { type: Date, default: Date.now }
});
blockSchema.index({ userId: 1, blockedUserId: 1 }, { unique: true });
const Report = mongoose.models.Report || mongoose.model('Report', reportSchema);
const Block = mongoose.models.Block || mongoose.model('Block', blockSchema);
// ============ 购物车模型 ============
const cartSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem', required: true },
createdAt: { type: Date, default: Date.now }
});
cartSchema.index({ userId: 1, productId: 1 }, { unique: true });
// ============ 二手市场订单模型 ============
const marketOrderSchema = new mongoose.Schema({
orderNo: { type: String, required: true, unique: true },
buyerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
sellerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem', required: true },
productNo: String,
title: String,
price: Number,
address: {
name: { type: String, required: true },
phone: { type: String, required: true },
detail: { type: String, required: true }
},
status: { type: String, enum: ['pending', 'confirmed', 'shipped', 'completed', 'cancelled'], default: 'pending' },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
const Cart = mongoose.models.Cart || mongoose.model('Cart', cartSchema);
const MarketOrder = mongoose.models.MarketOrder || mongoose.model('MarketOrder', marketOrderSchema);
const MARKET_CATEGORIES = ['book', 'electronic', 'life', 'other'];
const MARKET_ORDER_STATUS = ['pending', 'confirmed', 'shipped', 'completed', 'cancelled'];
function escapeRegExp(value = '') {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function clampNumber(value, min, max, fallback) {
const parsed = Number(value);
if (!Number.isFinite(parsed)) return fallback;
return Math.min(max, Math.max(min, parsed));
}
function normalizeMarketText(value, maxLength) {
return String(value || '').trim().slice(0, maxLength);
}
function normalizeMarketPrice(value) {
const price = Number(value);
if (!Number.isFinite(price) || price < 0 || price > 99999) return null;
return Math.round(price * 100) / 100;
}
function normalizeMarketImages(images) {
if (!Array.isArray(images)) return [];
return images
.filter(img => typeof img === 'string' && img.length <= 2 * 1024 * 1024 && /^data:image\/(png|jpe?g|webp);base64,/i.test(img))
.slice(0, 5);
}
function normalizeMarketContact(contact = {}) {
return {
qq: normalizeMarketText(contact.qq, 40),
wechat: normalizeMarketText(contact.wechat, 80)
};
}
function normalizeQrImage(value) {
if (value === '') return '';
if (typeof value !== 'string') return null;
if (value.length > 1024 * 1024) return null;
return /^data:image\/(png|jpe?g|webp);base64,/i.test(value) ? value : null;
}
async function hasMarketBlockBetween(userA, userB) {
if (!userA || !userB) return false;
return !!(await Block.exists({
$or: [
{ userId: userA, blockedUserId: userB },
{ userId: userB, blockedUserId: userA }
]
}));
}
async function releaseMarketItemIfNoOpenOrders(productId) {
const openOrder = await MarketOrder.exists({
productId,
status: { $in: ['pending', 'confirmed', 'shipped'] }
});
if (!openOrder) {
await MarketItem.updateOne({ _id: productId, status: 'reserved' }, { status: 'active', updatedAt: new Date() });
}
}
// 留言/反馈模型
const feedbackSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
title: { type: String, required: true },
content: { type: String, required: true },
type: { type: String, enum: ['bug', 'suggestion', 'question', 'other'], default: 'other' },
status: { type: String, enum: ['pending', 'read', 'replied', 'closed'], default: 'pending' },
adminReply: { type: String, default: '' },
repliedAt: { type: Date },
repliedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
// ============ 支付订单模型 ============
const paymentOrderSchema = new mongoose.Schema({
orderNo: { type: String, required: true, unique: true },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
amount: { type: Number, required: true },
days: { type: Number, default: 0 },
times: { type: Number, default: 0 },
cardCategory: { type: String, enum: ['days', 'times'], default: 'days' },
payMethod: { type: String, enum: ['wechat', 'alipay'], default: 'wechat' },
status: { type: String, enum: ['pending', 'paid', 'expired'], default: 'pending' },
cardId: { type: mongoose.Schema.Types.ObjectId, ref: 'Card' },
expireAt: { type: Date }, // ← 新增:订单过期时间
createdAt: { type: Date, default: Date.now },
paidAt: Date
});
const PaymentOrder = mongoose.models.PaymentOrder || mongoose.model('PaymentOrder', paymentOrderSchema);
const User = mongoose.models.User || mongoose.model('User', userSchema);
const Subscription = mongoose.models.Subscription || mongoose.model('Subscription', subscriptionSchema);
const SignLog = mongoose.models.SignLog || mongoose.model('SignLog', signLogSchema);
const EmailCode = mongoose.models.EmailCode || mongoose.model('EmailCode', emailCodeSchema);
const Card = mongoose.models.Card || mongoose.model('Card', cardSchema);
const SystemConfig = mongoose.models.SystemConfig || mongoose.model('SystemConfig', systemConfigSchema);
const InviteLog = mongoose.models.InviteLog || mongoose.model('InviteLog', inviteLogSchema);
const Feedback = mongoose.models.Feedback || mongoose.model('Feedback', feedbackSchema);
const AUTO_SIGN_NAME = '自动签到';
const AUTO_SIGN_TIME = '21:25';
const DEFAULT_AUTO_SIGN_DAYS = [1, 2, 3, 4, 5];
function normalizeAutoSignDays(days) {
const source = Array.isArray(days) && days.length > 0 ? days : DEFAULT_AUTO_SIGN_DAYS;
const normalized = [...new Set(
source
.map(day => Number(day))
.filter(day => Number.isInteger(day) && day >= 0 && day <= 6)
)].sort((a, b) => a - b);
return normalized.length > 0 ? normalized : DEFAULT_AUTO_SIGN_DAYS;
}
function formatAutoSignSetting(setting) {
return {
id: setting?._id || null,
_id: setting?._id || null,
name: AUTO_SIGN_NAME,
enabled: !!setting?.enabled,
scheduleType: 'custom',
customDays: setting ? normalizeAutoSignDays(setting.customDays) : DEFAULT_AUTO_SIGN_DAYS,
signTime: AUTO_SIGN_TIME,
maxRetries: 3,
notifyOnSuccess: setting ? setting.notifyOnSuccess !== false : true,
notifyOnFailure: setting ? setting.notifyOnFailure !== false : true,
createdAt: setting?.createdAt || null,
updatedAt: setting?.updatedAt || null
};
}
async function getAutoSignSetting(userId) {
return Subscription.findOne({ userId }).sort({ createdAt: 1 });
}
async function saveAutoSignSetting(userId, options = {}, targetId = null) {
const query = targetId ? { _id: targetId, userId } : { userId };
let setting = await Subscription.findOne(query).sort({ createdAt: 1 });
if (!setting) {
setting = new Subscription({ userId });
}
setting.name = AUTO_SIGN_NAME;
setting.enabled = options.enabled !== false;
setting.scheduleType = 'custom';
setting.customDays = normalizeAutoSignDays(options.customDays);
setting.signTime = AUTO_SIGN_TIME;
setting.maxRetries = 3;
setting.notifyOnSuccess = options.notifyOnSuccess !== false;
setting.notifyOnFailure = options.notifyOnFailure !== false;
setting.updatedAt = new Date();
await setting.save();
await Subscription.deleteMany({ userId, _id: { $ne: setting._id } });
return setting;
}
// ============ 初始化系统配置 ============
async function initSystemConfig() {
const defaults = [
{
key: 'dashboard_notice',
value: {
enabled: true,
title: '📢 系统公告',
content: '欢迎使用智能考勤系统!绑定邮箱即可获得 30 天 VIP。邀请好友注册,双方各得 10 天 VIP!',
style: 'info'
}
},
{ key: 'email_template', value: { footer: 'AG工作室 · 智能考勤系统', website: 'https://login.agai.online' } },
{ key: 'invite_reward_days', value: 10 }
];
for (const cfg of defaults) {
const exists = await SystemConfig.findOne({ key: cfg.key });
if (!exists) {
await SystemConfig.create(cfg);
console.log(`✅ 初始化配置: ${cfg.key}`);
}
}
console.log('✅ 系统配置初始化完成');
}
// ============ JWT 配置 ============
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
console.error('❌ JWT_SECRET 环境变量未设置!');
process.exit(1);
}
const JWT_EXPIRE = '30d';
const ADMIN_CREDENTIALS = parseAdminCredentials(process.env.ADMIN_CREDENTIALS || '111:0101');
function parseAdminCredentials(rawValue) {
return String(rawValue)
.split(',')
.map(item => item.trim())
.filter(Boolean)
.reduce((credentials, item) => {
const separatorIndex = item.indexOf(':');
if (separatorIndex <= 0) return credentials;
const account = item.slice(0, separatorIndex).trim();
const password = item.slice(separatorIndex + 1);
if (account && password) credentials.set(account, password);
return credentials;
}, new Map());
}
function timingSafeTextEqual(actual, expected) {
const actualHash = crypto.createHash('sha256').update(String(actual || '')).digest();
const expectedHash = crypto.createHash('sha256').update(String(expected || '')).digest();
return crypto.timingSafeEqual(actualHash, expectedHash);
}
function isConfiguredAdminAccount(studentId) {
return ADMIN_CREDENTIALS.has(String(studentId));
}
function validateAdminLogin(studentId, password) {
const expectedPassword = ADMIN_CREDENTIALS.get(String(studentId));
return Boolean(expectedPassword) && timingSafeTextEqual(password, expectedPassword);
}
// ============ 认证中间件 ============
const authMiddleware = async (req, res, next) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ success: false, message: '未登录' });
}
const token = authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ success: false, message: '令牌格式错误' });
}
const decoded = jwt.verify(token, JWT_SECRET);
const user = await User.findById(decoded.userId);
if (!user) {
return res.status(401).json({ success: false, message: '用户不存在' });
}
req.user = user;
// 游客只能访问市场相关API,禁止访问签到系统
if (user.studentId && user.studentId.startsWith('guest_')) {
const allowedPaths = [
'/api/market', '/api/user/payqr', '/api/quick-login',
'/api/user/profile', '/api/feedback'
];
const isAllowed = allowedPaths.some(p => req.path.startsWith(p));
if (!isAllowed) {
return res.status(403).json({ success: false, message: '游客无权访问此功能,请使用市场账号' });
}
}
next();
} catch (error) {
return res.status(401).json({ success: false, message: '登录已过期' });
}
};
const adminMiddleware = async (req, res, next) => {
try {
await authMiddleware(req, res, async () => {
if (req.user.role !== 'admin') {
return res.status(403).json({ success: false, message: '需要管理员权限' });
}
next();
});
} catch (error) {
res.status(401).json({ success: false, message: '未授权' });
}
};
// ============ 邮箱配置(Resend API)============
const RESEND_API_KEY = process.env.RESEND_API_KEY || '';
async function sendVerificationCode(email, code) {
if (!RESEND_API_KEY) {
console.log('📧 Resend 未配置,验证码:', code);
return false;
}
try {
const response = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${RESEND_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'AG工作室 <noreply@agai.online>',
to: email,
subject: '邮箱验证码 - AG工作室',
html: `
<div style="max-width: 450px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;">
<div style="text-align: center; margin-bottom: 24px;">
<h1 style="color: #667eea; margin: 0;">📋 AG工作室</h1>
<p style="color: #888; margin: 5px 0 0;">AG工作室</p>
</div>
<p style="font-size: 16px;">您的邮箱验证码是:</p>
<div style="font-size: 36px; font-weight: bold; color: #667eea; padding: 20px; background: #f5f7fa; text-align: center; border-radius: 12px; letter-spacing: 5px;">
${code}
</div>
<p style="margin-top: 20px; color: #666;">验证码 5 分钟内有效,请勿泄露给他人。</p>
<div style="margin-top: 24px; padding: 16px; background: linear-gradient(135deg, #667eea10 0%, #764ba210 100%); border-radius: 12px; text-align: center;">
<p style="margin: 0 0 8px 0; font-weight: 600; color: #667eea;">🎉 绑定邮箱即送 30 天 VIP</p>
<p style="margin: 0 0 12px 0; font-size: 13px; color: #666;">享受签到邮件通知 · 邀请好友再送 VIP</p>
<a href="https://login.agai.online" style="display: inline-block; padding: 8px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; text-decoration: none; border-radius: 20px; font-size: 14px; font-weight: 500;">立即体验</a>
</div>
<hr style="margin: 24px 0; border: none; border-top: 1px solid #eee;">
<p style="color: #999; font-size: 12px; text-align: center;">
AG工作室 · 智能考勤系统<br>
🌐 https://login.agai.online
</p>
</div>
`
})
});
if (response.ok) {
console.log('✅ 验证码邮件发送成功:', email);
return true;
} else {
const error = await response.text();
console.error('❌ Resend 发送失败:', error);
return false;
}
} catch (error) {
console.error('❌ 发送邮件异常:', error);
return false;
}
}
// ============ 发送 VIP 到账邮件 ============
async function sendVipGrantEmail(user, addedDays, newExpireAt) {
if (!RESEND_API_KEY) {
console.log('📧 Resend 未配置,跳过 VIP 邮件');
return false;
}
if (!user.email || !user.emailVerified) {
console.log(`📧 用户 ${user.studentId} 未绑定邮箱,跳过`);
return false;
}
const expireDate = newExpireAt ? new Date(newExpireAt).toLocaleDateString('zh-CN') : '永久';
const subject = `🎉 VIP 已到账 - AG工作室`;
try {
const response = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${RESEND_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'AG工作室 <noreply@agai.online>',
to: user.email,
subject: subject,
html: `
<div style="max-width:500px;margin:0 auto;padding:20px;font-family:Arial,sans-serif;">
<div style="text-align:center;margin-bottom:24px;">
<h1 style="color:#667eea;margin:0;">📋 AG工作室</h1>
</div>
<div style="background:#d4edda;padding:24px;border-radius:12px;border-left:4px solid #28a745;">
<p style="font-size:18px;font-weight:700;margin:0 0 12px 0;">🎉 VIP 已到账!</p>
<p style="margin:8px 0;"><strong>用户:</strong>${user.name || user.studentId}</p>
<p style="margin:8px 0;"><strong>增加天数:</strong>${addedDays} 天</p>
<p style="margin:8px 0;"><strong>有效期至:</strong>${expireDate}</p>
</div>
<div style="margin-top:24px;padding:16px;background:#f8f9fc;border-radius:12px;text-align:center;">
<p style="margin:0 0 12px 0;font-size:14px;color:#666;">
感谢您对 AG工作室 的信任与支持!<br>
签到邮件通知、自动签到等权益已正常生效。
</p>
<a href="https://login.agai.online" style="display:inline-block;padding:10px 24px;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:#fff;text-decoration:none;border-radius:20px;font-size:14px;">进入仪表盘</a>
</div>
<hr style="margin:24px 0;border:none;border-top:1px solid #eee;">
<p style="color:#999;font-size:12px;text-align:center;">
AG工作室 · 智能考勤系统<br>
🌐 https://login.agai.online
</p>
</div>
`
})
});
if (response.ok) {
console.log(`✅ VIP 到账邮件发送成功: ${user.email}`);
return true;
} else {
console.error(`❌ VIP 邮件发送失败:`, await response.text());
return false;
}
} catch (error) {
console.error('❌ 发送 VIP 邮件异常:', error);
return false;
}
}
async function sendSignNotification(email, studentId, result, subscriptionName, signTime = null) {
console.log(`📧 准备发送通知: email=${email}, studentId=${studentId}, success=${result.success}`);
if (!RESEND_API_KEY) {
console.log('📧 Resend 未配置,跳过通知');
return false;
}
const emoji = result.success ? '✅' : '❌';
const statusText = result.success ? '成功' : '失败';
const statusColor = result.success ? '#28a745' : '#dc3545';
const displayTime = signTime
? signTime.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })
: getBeijingTime();
try {
const response = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${RESEND_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'AG工作室 <noreply@agai.online>',
to: email,
subject: `${emoji} 签到${statusText}通知 - ${subscriptionName}`,
html: `
<div style="max-width: 450px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;">
<div style="text-align: center; margin-bottom: 24px;">
<h1 style="color: #667eea; margin: 0;">📋 签到通知</h1>
</div>
<div style="background: #f5f7fa; padding: 20px; border-radius: 12px;">
<p><strong>学号:</strong>${studentId}</p>
<p><strong>任务:</strong>${subscriptionName}</p>
<p><strong>时间:</strong>${displayTime}</p>
<p><strong>结果:</strong><span style="color: ${statusColor};">${result.message || statusText}</span></p>
</div>
<div style="margin-top: 24px; padding: 16px; background: linear-gradient(135deg, #667eea10 0%, #764ba210 100%); border-radius: 12px; text-align: center;">
<p style="margin: 0 0 8px 0; font-weight: 600; color: #667eea;">🚀 智能考勤 · 让签到更简单</p>
<p style="margin: 0 0 12px 0; font-size: 13px; color: #666;">自动签到 · 邮件通知 · 永久免费</p>
<a href="https://login.agai.online" style="display: inline-block; padding: 8px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; text-decoration: none; border-radius: 20px; font-size: 14px; font-weight: 500;">访问官网</a>
<p style="margin: 12px 0 0 0; font-size: 12px; color: #999;">邀请好友注册,双方各得 10 天 VIP!</p>
</div>
<hr style="margin: 24px 0; border: none; border-top: 1px solid #eee;">
<p style="color: #999; font-size: 12px; text-align: center;">
AG工作室 · 智能考勤系统<br>
📧 客服邮箱:support@agai.online<br>
🌐 官网:https://login.agai.online
</p>
</div>
`
})
});
if (response.ok) {
console.log('✅ 签到通知发送成功:', email);
return true;
} else {
const error = await response.text();
console.error('❌ 通知发送失败:', error);
return false;
}
} catch (error) {
console.error('❌ 发送通知异常:', error);
return false;
}
}
// ============ 发送赞助者通知邮件(供管理员调用) ============
async function sendSponsorEmailToAllVips(notice) {
if (!RESEND_API_KEY) {
console.log('📧 Resend 未配置,跳过邮件群发');
return;
}
// 获取所有邮箱已验证且为VIP的用户(排除游客)
const users = await User.find({ emailVerified: true, isVip: true, isGuest: { $ne: true } }).select('email studentId name');
if (users.length === 0) {
console.log('📧 没有符合条件的VIP用户');
return;
}
const subject = `🎉 ${notice.title || 'AG工作室感谢您的赞助!'}`;
const content = notice.content || '感谢您的支持,我们将继续努力!';
let successCount = 0, failCount = 0;
for (const user of users) {
try {
const response = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${RESEND_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'AG工作室 <noreply@agai.online>',
to: user.email,
subject: subject,
html: `
<div style="max-width:500px;margin:0 auto;padding:20px;font-family:Arial,sans-serif;">
<h2 style="color:#667eea;">📋 AG工作室</h2>
<div style="background:#f8f9fc;padding:20px;border-radius:12px;">
${content.replace(/\n/g, '<br>')}
</div>
<p style="color:#888;margin-top:20px;text-align:center;">此邮件由管理员发送,感谢您的支持!</p>
</div>
`
})
});
if (response.ok) successCount++; else failCount++;
} catch (e) { failCount++; }
// 避免触发邮件发送频率限制
await new Promise(r => setTimeout(r, 200));
}
console.log(`📧 赞助邮件群发完成:成功 ${successCount},失败 ${failCount}`);
}
// ============ 调用 Python 签到脚本 ============
async function realSign(studentId, password, maxRetries = 3) {
return new Promise((resolve) => {
const pythonScript = path.join(__dirname, 'attendance_runner.py');
const pythonProcess = spawn('python3', [pythonScript], {
timeout: 60000 // 60秒超时
});
let output = '';
let errorOutput = '';
let isResolved = false;
// 超时处理
const timeout = setTimeout(() => {
if (!isResolved) {
isResolved = true;
pythonProcess.kill();
console.error('⏰ Python 脚本执行超时');
resolve({ success: false, message: '签到脚本执行超时', errors: ['执行超时'] });
}
}, 55000); // 55秒超时
pythonProcess.stdout.on('data', (data) => {
output += data.toString();
console.log('Python stdout:', data.toString().substring(0, 200));
});
pythonProcess.stderr.on('data', (data) => {
errorOutput += data.toString();
console.error('Python stderr:', data.toString());
});
pythonProcess.on('close', (code) => {
if (isResolved) return;
isResolved = true;
clearTimeout(timeout);
console.log(`Python 进程退出,代码: ${code}`);
console.log('Python stdout 长度:', output.length);
console.log('Python stderr 长度:', errorOutput.length);
if (code !== 0) {
resolve({ success: false, message: '脚本执行失败', errors: [errorOutput || '未知错误'] });
return;
}
try {
const result = JSON.parse(output);
resolve(result);
} catch (e) {
console.error('解析 Python 输出失败:', output.substring(0, 500));
resolve({ success: false, message: '解析失败', errors: [output.substring(0, 200)] });
}
});
pythonProcess.on('error', (err) => {
if (isResolved) return;
isResolved = true;
clearTimeout(timeout);
console.error('Python 进程启动失败:', err);
resolve({ success: false, message: '无法启动签到脚本', errors: [err.message] });
});
// 发送输入数据
const inputData = JSON.stringify({
action: 'sign_single',
user: { studentId, password },
maxRetries
});
console.log('发送给 Python 的数据:', inputData.substring(0, 100));
pythonProcess.stdin.write(inputData);
pythonProcess.stdin.end();
});
}
// ============ 只验证密码(获取Token,不跑完整签到)============
async function verifyPassword(studentId, password) {
return new Promise((resolve) => {
const pythonScript = path.join(__dirname, 'attendance_runner.py');
const pythonProcess = spawn('python3', [pythonScript], {
timeout: 30000
});
let output = '';
let errorOutput = '';
let isResolved = false;
const timeout = setTimeout(() => {
if (!isResolved) {
isResolved = true;
pythonProcess.kill();
resolve({ success: false, message: '验证超时,请重试' });
}
}, 25000);
pythonProcess.stdout.on('data', (data) => { output += data.toString(); });
pythonProcess.stderr.on('data', (data) => {
errorOutput += data.toString();
console.error('验证密码 stderr:', data.toString());
});
pythonProcess.on('close', (code) => {
if (isResolved) return;
isResolved = true;
clearTimeout(timeout);
try {
const result = JSON.parse(output);
resolve({
success: result.success === true,
username: result.username || '',
message: result.message || ''
});
} catch (e) {
resolve({ success: false, message: '验证失败,请重试' });
}
});
pythonProcess.on('error', (err) => {
if (isResolved) return;
isResolved = true;
clearTimeout(timeout);
resolve({ success: false, message: '验证服务暂不可用' });
});
pythonProcess.stdin.write(JSON.stringify({
action: 'verify',
user: { studentId, password }
}));
pythonProcess.stdin.end();
});
}
// ============ 自动签到执行函数 ============
// ============ 自动签到执行函数(并发优化版)============
async function executeAutoSign() {
console.log('⏰ 自动签到任务开始:', getBeijingTime());
if (!MONGODB_URI) {
console.log('⚠️ 数据库未连接');
return;
}
try {
const today = new Date();
const dayOfWeek = today.getDay();
const subscriptions = await Subscription.find({ enabled: true }).populate('userId');
// 筛选今天需要签到的订阅
const todaySubscriptions = subscriptions.filter(sub => {
if (sub.scheduleType === 'daily') return true;
if (sub.scheduleType === 'weekdays') return dayOfWeek >= 1 && dayOfWeek <= 5;
if (sub.scheduleType === 'custom') {
return sub.customDays && sub.customDays.includes(dayOfWeek);
}
return false;
});
// 按用户分组
const userMap = new Map();
for (const sub of todaySubscriptions) {
const user = sub.userId;
if (user && user.isActive !== false) {
if (!userMap.has(user._id.toString())) {
userMap.set(user._id.toString(), { user, subscriptions: [] });
}
userMap.get(user._id.toString()).subscriptions.push(sub);
}