-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2066 lines (1736 loc) · 75.7 KB
/
app.js
File metadata and controls
2066 lines (1736 loc) · 75.7 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
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const jwt = require('jsonwebtoken');
const generateToken = (user) => {
return jwt.sign(user, process.env.JWT_SECRET, { expiresIn: '7d' }); // 토큰 유효기간 7일
};
const cors = require('cors');
const cron = require('node-cron');
const app = express();
const port = 3000;
const pool = require('./db'); // MySQL 연결 파일 가져오기
const cookieParser = require('cookie-parser');
app.use(cors({
origin: ['https://h4capston.site', 'http://localhost:5173'],
credentials: true,
}));
app.use(cookieParser());
app.use(express.json());
// app.use(async (req, res, next) => {
// const userId = req.user.id; // 사용자 ID
// const connection = await pool.getConnection();
// try {
// // 사용자 정보 가져오기
// const [userRows] = await connection.query(
// `SELECT level, state FROM user_data WHERE user_id = ?`,
// [userId]
// );
// if (userRows.length === 0) {
// return res.status(404).json({ error: '사용자를 찾을 수 없습니다.' });
// }
// const user = userRows[0];
// let newState = user.state;
// // 레벨에 따라 state 자동 업데이트
// if (user.level >= 7 && user.state !== 4) {
// newState = 4; // 레벨 7 이상이면 state는 4
// } else if (user.level >= 5 && user.state !== 3) {
// newState = 3; // 레벨 5 이상이면 state는 3
// } else if (user.level >= 3 && user.state !== 2) {
// newState = 2; // 레벨 3 이상이면 state는 2
// }
// // state가 변경되었으면 업데이트
// if (newState !== user.state) {
// await connection.query(
// `UPDATE user_data SET state = ? WHERE user_id = ?`,
// [newState, userId]
// );
// }
// next(); // 요청이 진행되도록 next() 호출
// } catch (error) {
// console.error('자동 state 업데이트 오류:', error);
// res.status(500).json({ error: '서버 오류' });
// } finally {
// connection.release(); // DB 연결 종료
// }
// });
// app.use(async (req, res, next) => {
// const userId = req.user.id; // 인증된 사용자의 ID
// const connection = await pool.getConnection();
// try {
// // 사용자의 경험치와 현재 레벨 정보 가져오기
// const [userRows] = await connection.query(
// `SELECT experience, level FROM user_data WHERE user_id = ?`,
// [userId]
// );
// if (userRows.length === 0) {
// return res.status(404).json({ error: '사용자를 찾을 수 없습니다.' });
// }
// const user = userRows[0];
// let newLevel = user.level;
// // 경험치에 따른 레벨 계산 (100 경험치 단위로 레벨 증가)
// if (user.experience >= 1000 && user.level < 10) {
// newLevel = 10;
// } else if (user.experience >= 900 && user.level < 9) {
// newLevel = 9;
// } else if (user.experience >= 800 && user.level < 8) {
// newLevel = 8;
// } else if (user.experience >= 700 && user.level < 7) {
// newLevel = 7;
// } else if (user.experience >= 600 && user.level < 6) {
// newLevel = 6;
// } else if (user.experience >= 500 && user.level < 5) {
// newLevel = 5;
// } else if (user.experience >= 400 && user.level < 4) {
// newLevel = 4;
// } else if (user.experience >= 300 && user.level < 3) {
// newLevel = 3;
// } else if (user.experience >= 200 && user.level < 2) {
// newLevel = 2;
// } else if (user.experience >= 100 && user.level < 1) {
// newLevel = 1;
// }
// // 레벨이 변경되었다면 업데이트
// if (newLevel !== user.level) {
// await connection.query(
// `UPDATE user_data SET level = ? WHERE user_id = ?`,
// [newLevel, userId]
// );
// }
// next(); // 요청이 진행되도록 next() 호출
// } catch (error) {
// console.error('레벨 자동 업데이트 오류:', error);
// res.status(500).json({ error: '서버 오류' });
// } finally {
// connection.release(); // DB 연결 종료
// }
// });
app.get('/', (req, res) => {
res.send("hi, we're h4!");
});
app.get('/auth/kakao', (req, res) => {
const kakaoAuthUrl = `https://kauth.kakao.com/oauth/authorize?client_id=${process.env.KAKAO_CLIENT_ID}&redirect_uri=${process.env.KAKAO_REDIRECT_URI}&response_type=code`;
res.redirect(kakaoAuthUrl);
});
/**
* 2. 카카오 로그인 후, 인가 코드(code)를 받아 백엔드에서 처리
*/
app.get('/auth/kakao/callback', async (req, res) => {
const { code } = req.query;
if (!code) {
return res.status(400).json({ error: '인가 코드가 없습니다.' });
}
try {
const tokenResponse = await axios.post('https://kauth.kakao.com/oauth/token', null, {
params: {
grant_type: 'authorization_code',
client_id: process.env.KAKAO_CLIENT_ID,
client_secret: process.env.KAKAO_CLIENT_SECRET,
redirect_uri: process.env.KAKAO_REDIRECT_URI,
code,
},
});
const accessToken = tokenResponse.data.access_token;
const userResponse = await axios.get('https://kapi.kakao.com/v2/user/me', {
headers: { Authorization: `Bearer ${accessToken}` },
});
const user = {
id: userResponse.data.id.toString(),
email: userResponse.data.kakao_account.email || null,
nickname: userResponse.data.kakao_account.profile.nickname,
provider: 'kakao',
};
const connection = await pool.getConnection();
let redirectPath = '/main';
try {
let [existingUser] = await connection.query(
`SELECT * FROM users WHERE email = ?`,
[user.email]
);
if (existingUser.length === 0) {
[existingUser] = await connection.query(
`SELECT * FROM users WHERE id = ?`,
[user.id]
);
}
if (existingUser.length === 0) {
// 신규 회원 가입
await connection.query(
`INSERT INTO users (id, email, nickname, provider) VALUES (?, ?, ?, ?)`,
[user.id, user.email, user.nickname, user.provider]
);
// 기본 운동 목표와 함께 user_data 및 daily_quests 초기화
await connection.query(
`INSERT INTO user_data (user_id, level, coin, targetExercise, targetcount, targetSet, targetCheck, gender, top, pants, state, experience, challenge_level)
VALUES (?, 1, 500, 0, 0, 0, 0, NULL, NULL, NULL, 1, 100, 1)`, // 경험치 기본값 100, challenge_level 기본값 1
[user.id]
);
// 도전과제(누적형) 초기화
await connection.query(
`INSERT INTO challenge_quests (user_id, level) VALUES (?, 1)`, // 기본 challenge_level 1
[user.id]
);
// 기본 퀘스트 목표 설정 (레벨 1 기준)
const levelGoals = [
{ level: 1, squat: 7, plank: 30, pushup: 5 },
{ level: 2, squat: 8, plank: 35, pushup: 6 },
{ level: 3, squat: 9, plank: 40, pushup: 7 },
{ level: 4, squat: 10, plank: 45, pushup: 8 },
{ level: 5, squat: 11, plank: 50, pushup: 9 },
{ level: 6, squat: 12, plank: 55, pushup: 10 },
{ level: 7, squat: 13, plank: 60, pushup: 11 },
{ level: 8, squat: 14, plank: 65, pushup: 12 },
{ level: 9, squat: 15, plank: 70, pushup: 13 },
{ level: 10, squat: 16, plank: 70, pushup: 14 }
];
for (let i = 0; i < levelGoals.length; i++) {
const goals = levelGoals[i];
await connection.query(
`INSERT INTO daily_quests (user_id, exercise_type, level, goal_count, experience, coin, is_success)
VALUES
(?, 'squat', ?, ?, 35, 20, FALSE),
(?, 'plank', ?, ?, 35, 20, FALSE),
(?, 'pushup', ?, ?, 35, 20, FALSE)`,
[
user.id, goals.level, goals.squat, // first entry: squat
user.id, goals.level, goals.plank, // second entry: situp
user.id, goals.level, goals.pushup // third entry: pushup
]
);
}
// 도전 과제 초기화 (누적형 목표)
const levelGoals_challenge = [
{ level: 1, squat: 50, plank: 50, pushup: 30 },
{ level: 2, squat: 55, plank: 55, pushup: 35 },
{ level: 3, squat: 60, plank: 60, pushup: 40 },
{ level: 4, squat: 65, plank: 65, pushup: 45 },
{ level: 5, squat: 70, plank: 70, pushup: 50 },
{ level: 6, squat: 75, plank: 75, pushup: 55 },
{ level: 7, squat: 80, plank: 80, pushup: 60 },
{ level: 8, squat: 85, plank: 85, pushup: 65 },
{ level: 9, squat: 90, plank: 90, pushup: 70 },
{ level: 10, squat: 95, plank: 95, pushup: 75 }
];
for (let i = 0; i < levelGoals_challenge.length; i++) {
const goals = levelGoals_challenge[i];
await connection.query(
`INSERT INTO challenge_quests (user_id, level, exercise_type, goal_count, is_success, coin, exp)
VALUES
(?, ?, 'squat', ?, 0, 500, 100),
(?, ?, 'plank', ?, 0, 500, 100),
(?, ?, 'pushup', ?, 0, 500, 100)`,
[
user.id, goals.level, goals.squat, // 첫 번째 항목: squat
user.id, goals.level, goals.plank, // 두 번째 항목: plank
user.id, goals.level, goals.pushup // 세 번째 항목: pushup
]
);
}
// `outer` 아이템을 `wardrobe`에 추가
const outerItems = [
{ item_id: 1, item_type: 'outer', item_name: 'outer1' },
{ item_id: 2, item_type: 'outer', item_name: 'outer2' },
{ item_id: 3, item_type: 'outer', item_name: 'outer3' },
{ item_id: 4, item_type: 'outer', item_name: 'outer4' },
{ item_id: 5, item_type: 'outer', item_name: 'outer5' },
{ item_id: 6, item_type: 'outer', item_name: 'outer6' }
];
for (const item of outerItems) {
await connection.query(
`INSERT INTO wardrobe (user_id, item_id, item_type, item_name, equipped)
VALUES (?, ?, ?, ?, 0)`,
[user.id, item.item_id, item.item_type, item.item_name] // equipped는 기본적으로 0 (착용 안 함)
);
}
redirectPath = '/signup';
} else {
// 기존 사용자라면 정보 업데이트
await connection.query(
`UPDATE users SET email = ?, nickname = ? WHERE id = ?`,
[user.email, user.nickname, user.id]
);
}
} finally {
connection.release();
}
const token = generateToken({ id: user.id });
console.log(token);
res.cookie('token', token, {
secure: true,
sameSite: 'None',
});
res.redirect(`https://h4capston.site${redirectPath}`);
//res.redirect(`http://localhost:5173${redirectPath}`);
} catch (error) {
console.error("카카오 로그인 오류:", error);
res.status(400).json({ error: '카카오 로그인 실패' });
}
});
app.get('/auth/naver', (req, res) => {
const state = Math.random().toString(36).substring(2, 15); // CSRF 방지를 위한 상태 값
const naverAuthUrl = `https://nid.naver.com/oauth2.0/authorize?client_id=${process.env.NAVER_CLIENT_ID}&redirect_uri=${process.env.NAVER_REDIRECT_URI}&response_type=code&state=${state}`;
res.redirect(naverAuthUrl);
});
// **네이버 로그인**
app.get('/auth/naver/callback', async (req, res) => {
const { code, state } = req.query;
try {
const tokenResponse = await axios.post('https://nid.naver.com/oauth2.0/token', null, {
params: {
grant_type: 'authorization_code',
client_id: process.env.NAVER_CLIENT_ID,
client_secret: process.env.NAVER_CLIENT_SECRET,
redirect_uri: process.env.NAVER_REDIRECT_URI,
code,
state,
},
});
const accessToken = tokenResponse.data.access_token;
const userResponse = await axios.get('https://openapi.naver.com/v1/nid/me', {
headers: { Authorization: `Bearer ${accessToken}` },
});
const user = {
id: userResponse.data.response.id,
email: userResponse.data.response.email || null,
nickname: userResponse.data.response.nickname,
provider: 'naver',
};
const connection = await pool.getConnection();
let redirectPath = '/main';
try {
let [existingUser] = await connection.query(
`SELECT * FROM users WHERE email = ?`,
[user.email]
);
if (existingUser.length === 0) {
[existingUser] = await connection.query(
`SELECT * FROM users WHERE id = ?`,
[user.id]
);
}
if (existingUser.length === 0) {
// 신규 회원 가입
await connection.query(
`INSERT INTO users (id, email, nickname, provider) VALUES (?, ?, ?, ?)`,
[user.id, user.email, user.nickname, user.provider]
);
// 기본 운동 목표와 함께 user_data 및 daily_quests 초기화
await connection.query(
`INSERT INTO user_data (user_id, level, coin, targetExercise, targetcount, targetSet, targetCheck, gender, top, pants, state, experience, challenge_level)
VALUES (?, 1, 500, 0, 0, 0, 0, NULL, NULL, NULL, 1, 100, 1)`, // 경험치 기본값 100, challenge_level 기본값 1
[user.id]
);
// 기본 퀘스트 목표 설정 (레벨 1 기준)
const levelGoals = [
{ level: 1, squat: 7, plank: 30, pushup: 5 },
{ level: 2, squat: 8, plank: 35, pushup: 6 },
{ level: 3, squat: 9, plank: 40, pushup: 7 },
{ level: 4, squat: 10, plank: 45, pushup: 8 },
{ level: 5, squat: 11, plank: 50, pushup: 9 },
{ level: 6, squat: 12, plank: 55, pushup: 10 },
{ level: 7, squat: 13, plank: 60, pushup: 11 },
{ level: 8, squat: 14, plank: 65, pushup: 12 },
{ level: 9, squat: 15, plank: 70, pushup: 13 },
{ level: 10, squat: 16, plank: 70, pushup: 14 }
];
for (let i = 0; i < levelGoals.length; i++) {
const goals = levelGoals[i];
await connection.query(
`INSERT INTO daily_quests (user_id, exercise_type, level, goal_count, experience, coin, is_success)
VALUES
(?, 'squat', ?, ?, 35, 20, FALSE),
(?, 'plank', ?, ?, 35, 20, FALSE),
(?, 'pushup', ?, ?, 35, 20, FALSE)`,
[
user.id, goals.level, goals.squat, // first entry: squat
user.id, goals.level, goals.plank, // second entry: situp
user.id, goals.level, goals.pushup // third entry: pushup
]
);
}
// 도전 과제 초기화 (누적형 목표)
const levelGoals_challenge = [
{ level: 1, squat: 50, plank: 50, pushup: 30 },
{ level: 2, squat: 55, plank: 55, pushup: 35 },
{ level: 3, squat: 60, plank: 60, pushup: 40 },
{ level: 4, squat: 65, plank: 65, pushup: 45 },
{ level: 5, squat: 70, plank: 70, pushup: 50 },
{ level: 6, squat: 75, plank: 75, pushup: 55 },
{ level: 7, squat: 80, plank: 80, pushup: 60 },
{ level: 8, squat: 85, plank: 85, pushup: 65 },
{ level: 9, squat: 90, plank: 90, pushup: 70 },
{ level: 10, squat: 95, plank: 95, pushup: 75 }
];
for (let i = 0; i < levelGoals_challenge.length; i++) {
const goals = levelGoals_challenge[i];
await connection.query(
`INSERT INTO challenge_quests (user_id, level, exercise_type, goal_count, is_success, coin, exp)
VALUES
(?, ?, 'squat', ?, 0, 500, 100),
(?, ?, 'plank', ?, 0, 500, 100),
(?, ?, 'pushup', ?, 0, 500, 100)`,
[
user.id, goals.level, goals.squat, // 첫 번째 항목: squat
user.id, goals.level, goals.plank, // 두 번째 항목: plank
user.id, goals.level, goals.pushup // 세 번째 항목: pushup
]
);
}
// `outer` 아이템을 `wardrobe`에 추가
const outerItems = [
{ item_id: 1, item_type: 'outer', item_name: 'outer1' },
{ item_id: 2, item_type: 'outer', item_name: 'outer2' },
{ item_id: 3, item_type: 'outer', item_name: 'outer3' },
{ item_id: 4, item_type: 'outer', item_name: 'outer4' },
{ item_id: 5, item_type: 'outer', item_name: 'outer5' },
{ item_id: 6, item_type: 'outer', item_name: 'outer6' }
];
for (const item of outerItems) {
await connection.query(
`INSERT INTO wardrobe (user_id, item_id, item_type, item_name, equipped)
VALUES (?, ?, ?, ?, 0)`,
[user.id, item.item_id, item.item_type, item.item_name] // equipped는 기본적으로 0 (착용 안 함)
);
}
redirectPath = '/signup';
} else {
// 기존 사용자라면 정보 업데이트
await connection.query(
`UPDATE users SET email = ?, nickname = ? WHERE id = ?`,
[user.email, user.nickname, user.id]
);
}
} finally {
connection.release();
}
const token = generateToken({ id: user.id });
res.cookie('token', token, {
httpOnly: true,
secure: true,
sameSite: 'Lax',
maxAge: 7 * 24 * 60 * 60 * 1000,
});
res.redirect(`https://h4capston.site${redirectPath}`);
//res.redirect(`http://localhost:5173${redirectPath}`);
} catch (error) {
console.error('네이버 로그인 오류:', error);
res.status(400).json({ error: '네이버 로그인 실패' });
}
});
app.get('/auth/google', (req, res) => {
const googleAuthUrl = `https://accounts.google.com/o/oauth2/auth?client_id=${process.env.GOOGLE_CLIENT_ID}&redirect_uri=${process.env.GOOGLE_REDIRECT_URI}&response_type=code&scope=email%20profile`;
res.redirect(googleAuthUrl);
});
// **구글 로그인**
app.get('/auth/google/callback', async (req, res) => {
const { code } = req.query;
if (!code) {
return res.status(400).json({ error: '인가 코드가 없습니다.' });
}
try {
const tokenResponse = await axios.post('https://oauth2.googleapis.com/token', null, {
params: {
grant_type: 'authorization_code',
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
redirect_uri: process.env.GOOGLE_REDIRECT_URI,
code,
},
});
const accessToken = tokenResponse.data.access_token;
const userResponse = await axios.get('https://www.googleapis.com/oauth2/v1/userinfo', {
headers: { Authorization: `Bearer ${accessToken}` },
});
const user = {
id: userResponse.data.id,
email: userResponse.data.email || null,
nickname: userResponse.data.name,
provider: 'google',
};
const connection = await pool.getConnection();
let redirectPath = '/main';
try {
let [existingUser] = await connection.query(
`SELECT * FROM users WHERE email = ?`,
[user.email]
);
if (existingUser.length === 0) {
[existingUser] = await connection.query(
`SELECT * FROM users WHERE id = ?`,
[user.id]
);
}
if (existingUser.length === 0) {
// 신규 회원 가입
await connection.query(
`INSERT INTO users (id, email, nickname, provider) VALUES (?, ?, ?, ?)`,
[user.id, user.email, user.nickname, user.provider]
);
// 기본 운동 목표와 함께 user_data 및 daily_quests 초기화
await connection.query(
`INSERT INTO user_data (user_id, level, coin, targetExercise, targetcount, targetSet, targetCheck, gender, top, pants, state, experience, challenge_level)
VALUES (?, 1, 500, 0, 0, 0, 0, NULL, NULL, NULL, 1, 100, 1)`, // 경험치 기본값 100, challenge_level 기본값 1
[user.id]
);
// 도전과제(누적형) 초기화
await connection.query(
`INSERT INTO challenge_quests (user_id, level) VALUES (?, 1)`, // 기본 challenge_level 1
[user.id]
);
// 기본 퀘스트 목표 설정 (레벨 1 기준)
const levelGoals = [
{ level: 1, squat: 7, plank: 30, pushup: 5 },
{ level: 2, squat: 8, plank: 35, pushup: 6 },
{ level: 3, squat: 9, plank: 40, pushup: 7 },
{ level: 4, squat: 10, plank: 45, pushup: 8 },
{ level: 5, squat: 11, plank: 50, pushup: 9 },
{ level: 6, squat: 12, plank: 55, pushup: 10 },
{ level: 7, squat: 13, plank: 60, pushup: 11 },
{ level: 8, squat: 14, plank: 65, pushup: 12 },
{ level: 9, squat: 15, plank: 70, pushup: 13 },
{ level: 10, squat: 16, plank: 70, pushup: 14 }
];
for (let i = 0; i < levelGoals.length; i++) {
const goals = levelGoals[i];
await connection.query(
`INSERT INTO daily_quests (user_id, exercise_type, level, goal_count, experience, coin, is_success)
VALUES
(?, 'squat', ?, ?, 35, 20, FALSE),
(?, 'plank', ?, ?, 35, 20, FALSE),
(?, 'pushup', ?, ?, 35, 20, FALSE)`,
[
user.id, goals.level, goals.squat, // first entry: squat
user.id, goals.level, goals.plank, // second entry: situp
user.id, goals.level, goals.pushup // third entry: pushup
]
);
}
// 도전 과제 초기화 (누적형 목표)
const levelGoals_challenge = [
{ level: 1, squat: 50, plank: 50, pushup: 30 },
{ level: 2, squat: 55, plank: 55, pushup: 35 },
{ level: 3, squat: 60, plank: 60, pushup: 40 },
{ level: 4, squat: 65, plank: 65, pushup: 45 },
{ level: 5, squat: 70, plank: 70, pushup: 50 },
{ level: 6, squat: 75, plank: 75, pushup: 55 },
{ level: 7, squat: 80, plank: 80, pushup: 60 },
{ level: 8, squat: 85, plank: 85, pushup: 65 },
{ level: 9, squat: 90, plank: 90, pushup: 70 },
{ level: 10, squat: 95, plank: 95, pushup: 75 }
];
for (let i = 0; i < levelGoals_challenge.length; i++) {
const goals = levelGoals_challenge[i];
await connection.query(
`INSERT INTO challenge_quests (user_id, level, exercise_type, goal_count, is_success, coin, exp)
VALUES
(?, ?, 'squat', ?, 0, 500, 100),
(?, ?, 'plank', ?, 0, 500, 100),
(?, ?, 'pushup', ?, 0, 500, 100)`,
[
user.id, goals.level, goals.squat, // 첫 번째 항목: squat
user.id, goals.level, goals.plank, // 두 번째 항목: plank
user.id, goals.level, goals.pushup // 세 번째 항목: pushup
]
);
}
// `outer` 아이템을 `wardrobe`에 추가
const outerItems = [
{ item_id: 1, item_type: 'outer', item_name: 'outer1' },
{ item_id: 2, item_type: 'outer', item_name: 'outer2' },
{ item_id: 3, item_type: 'outer', item_name: 'outer3' },
{ item_id: 4, item_type: 'outer', item_name: 'outer4' },
{ item_id: 5, item_type: 'outer', item_name: 'outer5' },
{ item_id: 6, item_type: 'outer', item_name: 'outer6' }
];
for (const item of outerItems) {
await connection.query(
`INSERT INTO wardrobe (user_id, item_id, item_type, item_name, equipped)
VALUES (?, ?, ?, ?, 0)`,
[user.id, item.item_id, item.item_type, item.item_name] // equipped는 기본적으로 0 (착용 안 함)
);
}
redirectPath = '/signup';
} else {
// 기존 사용자라면 정보 업데이트
await connection.query(
`UPDATE users SET email = ?, nickname = ? WHERE id = ?`,
[user.email, user.nickname, user.id]
);
}
} finally {
connection.release();
}
const token = generateToken({ id: user.id });
res.cookie('token', token, {
httpOnly: true,
secure: false,
sameSite: 'Lax',
});
res.redirect(`https://h4capston.site${redirectPath}`);
} catch (error) {
console.error("구글 로그인 오류:", error);
res.status(400).json({ error: '구글 로그인 실패' });
}
});
// MainData = {
// level: number;
// coin: number;
// targetExercise: string;
// targetcount: number;
// targetSet: number;
// targetCheck: number;
// character: {
// gender: string;
// top: string | null;
// pants: string | null;
// state: number | null;
// };
// };
const authenticate = (req, res, next) => {
const token = req.cookies.token;
if (!token) {
return res.status(401).json({ error: '인증 토큰이 X' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ error: '유효하지 않은 토큰입니다.' });
}
};
function getExerciseKoreanName(type) {
const map = {
squat: "스쿼트",
pushup: "팔굽혀펴기",
plank: "플랭크"
};
return map[type] || type;
}
app.get('/main', authenticate, async (req, res) => {
const userId = req.user.id;
const connection = await pool.getConnection();
console.log(userId);
try {
// 1. 사용자 정보 조회 (레벨 포함)
const [userRows] = await connection.query(`
SELECT experience, coin, level, targetExercise, targetcount, targetSet, targetCheck,
gender, top, pants, state
FROM user_data
WHERE user_id = ?
`, [userId]);
if (userRows.length === 0) {
return res.status(404).json({ error: '사용자 데이터를 찾을 수 없습니다.' });
}
const userData = userRows[0];
// 2. 오늘 날짜 기반 운동 종목 결정
const today = new Date();
const dayOfYear = Math.floor((today - new Date(today.getFullYear(), 0, 0)) / 86400000);
const exerciseTypes = ['squat', 'pushup', 'plank'];
const exerciseType = `squat` //exerciseTypes[dayOfYear % 3];
// 3. daily_quests에서 해당 유저의 오늘 할당된 퀘스트 정보 가져오기 (level 기준)
const [questRows] = await connection.query(`
SELECT * FROM daily_quests
WHERE user_id = ? AND exercise_type = ? AND level = ?
`, [userId, 'squat', userData.level]);
let todayQuest = null;
if (questRows.length > 0) {
const quest = questRows[0];
todayQuest = {
date: today.toISOString().split('T')[0],
exercise_type: exerciseType,
name: getExerciseName(exerciseType),
icon: getExerciseIcon(exerciseType),
count: quest.goal_count,
sets: quest.sets,
completed: quest.completed_sets >= quest.goal_count,
reward: quest.coin,
exp: quest.experience
};
// 4. 유저 테이블에 오늘의 퀘스트 상태 업데이트
await connection.query(`
UPDATE user_data
SET targetExercise = ?, targetcount = ?, targetSet = ?, targetCheck = ?
WHERE user_id = ?
`, [exerciseType, quest.goal_count, quest.sets, quest.completed_sets, userId]);
}
// 5. 반환 데이터 구성
// 5. 반환 데이터 구성
function formatClothing(typeValue, type) {
if (!typeValue) return null;
const match = typeValue.match(/\d+/);
if (!match) return null;
const number = match[0];
return type === 'top' ? `top[${number}]` : `pants[${number}]`;
}
const MainData = {
level: userData.experience,
coin: userData.coin,
targetExercise: getExerciseKoreanName(userData.targetExercise),
targetcount: userData.targetcount,
targetSet: userData.targetSet,
targetCheck: userData.targetCheck,
character: {
gender: userData.gender,
top: formatClothing(userData.top, 'top'),
pants: formatClothing(userData.pants, 'pants'),
state: userData.state
},
todayQuest: todayQuest
};
res.json(MainData);
} catch (error) {
console.error("메인 데이터 조회 오류:", error);
res.status(500).json({ error: '서버 오류' });
} finally {
connection.release();
}
});
//친구 검색
app.post('/search-user', authenticate, async (req, res) => {
const { nickname } = req.body;
if (!nickname || nickname.trim() === '') {
return res.status(400).json({ error: '닉네임을 입력해주세요.' });
}
const connection = await pool.getConnection();
try {
const [rows] = await connection.query(`
SELECT u.id AS user_id, u.nickname, ud.level
FROM users u
JOIN user_data ud ON u.id = ud.user_id
WHERE u.nickname LIKE ?
LIMIT 20
`, [`%${nickname}%`]);
res.json(rows);
} catch (error) {
console.error('닉네임 검색 오류:', error);
res.status(500).json({ error: '서버 오류가 발생했습니다.' });
} finally {
connection.release();
}
});
// 친구 추가
app.post('/addFriend', authenticate, async (req, res) => {
const { friendNickname } = req.body;
const userId = req.user.id; // 현재 로그인한 사용자 ID
if (!friendNickname) {
return res.status(400).json({ error: '친구 닉네임을 입력하세요.' });
}
const connection = await pool.getConnection();
try {
// 1️⃣ 친구의 user_id 찾기
const [friendData] = await connection.query(
`SELECT id, nickname FROM users WHERE nickname = ?`,
[friendNickname]
);
if (friendData.length === 0) {
return res.status(404).json({ error: '해당 닉네임을 가진 사용자가 없습니다.' });
}
const friendId = friendData[0].id;
const friendNick = friendData[0].nickname;
const [existingFriend] = await connection.query(
`SELECT * FROM friends WHERE user_id = ? AND friend_id = ?`,
[userId, friendId]
);
if (existingFriend.length > 0) {
return res.status(400).json({ error: '이미 친구로 추가된 사용자입니다.' });
}
await connection.query(
`INSERT INTO friends (user_id, friend_id, friend_nickname) VALUES (?, ?, ?)`,
[userId, friendId, friendNick]
);
res.json({ message: '친구 추가 성공', friend: friendNick });
} catch (error) {
console.error('친구 추가 오류:', error);
res.status(500).json({ error: '서버 오류' });
} finally {
connection.release();
}
});
// 친구 목록 가져오기
app.get('/friends', authenticate, async (req, res) => {
const userId = req.user.id;
const connection = await pool.getConnection();
try {
// 내가 추가한 친구 목록 조회
const [friendsList] = await connection.query(
`SELECT u.nickname, ud.level
FROM friends f
JOIN users u ON f.friend_id = u.id
JOIN user_data ud ON ud.user_id = u.id
WHERE f.user_id = ?`,
[userId]
);
// 나를 친구로 추가한 사람들 조회
const [friendsAddedMe] = await connection.query(
`SELECT u.nickname, ud.level
FROM friends f
JOIN users u ON f.user_id = u.id
JOIN user_data ud ON ud.user_id = u.id
WHERE f.friend_id = ?`,
[userId]
);
// 닉네임 + 레벨 중복 제거
const allFriends = [...friendsList, ...friendsAddedMe].filter(
(friend, index, self) =>
index === self.findIndex((f) => f.nickname === friend.nickname)
);
res.json({ friends: allFriends });
} catch (error) {
console.error('친구 목록 조회 오류:', error);
res.status(500).json({ error: '서버 오류' });
} finally {
connection.release();
}
});
// 친구 삭제
app.delete('/removeFriend', authenticate, async (req, res) => {
const { friendNickname } = req.body;
const userId = req.user.id;
if (!friendNickname) {
return res.status(400).json({ error: '삭제할 친구의 닉네임을 입력하세요.' });
}
const connection = await pool.getConnection();
try {
const [friendData] = await connection.query(
`SELECT id FROM users WHERE nickname = ?`,
[friendNickname]
);
if (friendData.length === 0) {
return res.status(404).json({ error: '해당 닉네임을 가진 사용자가 없습니다.' });
}
const friendId = friendData[0].id;
// 2️⃣ 친구 관계 삭제 (내가 추가한 친구 or 상대가 나를 추가한 경우)
const [deleteResult] = await connection.query(
`DELETE FROM friends WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)`,
[userId, friendId, friendId, userId]
);
if (deleteResult.affectedRows === 0) {
return res.status(400).json({ error: '해당 사용자는 친구 목록에 없습니다.' });
}
res.json({ message: '친구 삭제 성공', friend: friendNickname });
} catch (error) {
console.error('친구 삭제 오류:', error);
res.status(500).json({ error: '서버 오류' });
} finally {
connection.release();
}
});
// 성별추가
app.post('/signup', authenticate, async (req, res) => {
const userId = req.user.id;
const { gender, nickname } = req.body;
// ✅ 유효성 검사
if (!gender || !['male', 'female', 'unknown'].includes(gender)) {
return res.status(400).json({ error: '유효한 성별을 입력하세요. (male, female, unknown)' });
}
if (!nickname || nickname.trim().length < 1) {
return res.status(400).json({ error: '닉네임을 입력하세요.' });
}
const connection = await pool.getConnection();
try {
// ✅ 닉네임 중복 검사 (본인 제외)
const [duplicateCheck] = await connection.query(
`SELECT id FROM users WHERE nickname = ? AND id != ?`,
[nickname, userId]
);
if (duplicateCheck.length > 0) {
return res.status(409).json({ error: '이미 사용 중인 닉네임입니다.' });
}
// ✅ 닉네임 및 성별 업데이트
const [result] = await connection.query(
`UPDATE users SET gender = ?, nickname = ? WHERE id = ?`,
[gender, nickname, userId]
);
const [result2] = await connection.query(
`UPDATE user_data SET gender = ? WHERE user_id = ?`,
[gender, userId]
);
if (result.affectedRows === 0) {
return res.status(404).json({ error: '해당 사용자를 찾을 수 없습니다.' });
}
res.json({ message: '성별 및 닉네임이 업데이트되었습니다.', gender, nickname });
} catch (error) {
console.error('성별/닉네임 업데이트 오류:', error);