-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1568 lines (1360 loc) · 57 KB
/
server.js
File metadata and controls
1568 lines (1360 loc) · 57 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
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
// Upewnij się, że katalog uploads istnieje
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
console.log('📁 Utworzono katalog uploads');
}
// Udostępnij katalog uploads jako statyczny z dodatkowymi headerami bezpieczeństwa
app.use('/uploads', (req, res, next) => {
// Ustaw headery bezpieczeństwa dla plików
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Content-Security-Policy', "default-src 'none'; img-src 'self'");
// Sprawdź czy to jest rzeczywiście plik obrazka na podstawie rozszerzenia
const filePath = req.path;
const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
const ext = path.extname(filePath).toLowerCase();
if (!allowedExts.includes(ext)) {
return res.status(403).json({ error: 'Niedozwolony typ pliku' });
}
next();
}, express.static(path.join(__dirname, 'uploads')));
const multer = require('multer');
const cors = require('cors');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const sanitizeHtml = require('sanitize-html');
const bcrypt = require('bcryptjs');
const sqlite3 = require('sqlite3').verbose();
const nodemailer = require('nodemailer');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser'); // Dodane dla obsługi cookies
const db = new sqlite3.Database('./users.db'); // <-- tylko raz!
// JWT Secret key - ładowany ze zmiennych środowiskowych
const SECRET = process.env.JWT_SECRET || 'super_tajny_klucz_ZMIEN_TO_W_PRODUKCJI';
/*
=== STRUKTURA BAZY DANYCH ===
1. TABELA users:
- id (INTEGER, PRIMARY KEY, AUTOINCREMENT)
- firstName, lastName, userClass, phone, messenger, instagram (TEXT)
- mail (TEXT, UNIQUE)
- password (TEXT) - zahashowane bcrypt
- role (TEXT, DEFAULT 'user') - role: 'user', 'admin', 'przewodniczący'
- blockedUntil (TEXT) - data końca blokady w formacie ISO
- blockReason (TEXT) - powód blokady
2. TABELA books:
- id (INTEGER, PRIMARY KEY, AUTOINCREMENT)
- subject, title, publisher, year, grade, price, stan (TEXT)
- photo (TEXT) - URL do zdjęcia
- date (TEXT) - data dodania w formacie ISO
- userMail, userFirstName, userLastName, userClass, userPhone, userMessenger, userInstagram (TEXT)
3. TABELA spotet:
- id (INTEGER, PRIMARY KEY, AUTOINCREMENT)
- text (TEXT) - treść wiadomości
- photo (TEXT) - opcjonalne zdjęcie
- date (TEXT) - data w formacie ISO
- authorMail (TEXT) - mail autora
4. TABELA spotet_comments:
- id (INTEGER, PRIMARY KEY, AUTOINCREMENT)
- spotetId (INTEGER) - ID wiadomości spotet
- text (TEXT) - treść komentarza
- date (TEXT) - data w formacie ISO
- authorMail (TEXT) - mail autora
- isAnonymous (INTEGER, DEFAULT 0) - czy komentarz anonimowy
5. TABELA ogloszenia:
- id (INTEGER, PRIMARY KEY, AUTOINCREMENT)
- title (TEXT) - tytuł ogłoszenia
- text (TEXT) - treść ogłoszenia
- photo (TEXT) - opcjonalne zdjęcie
- date (TEXT) - data w formacie ISO
- authorMail (TEXT) - mail autora
- authorRole (TEXT) - rola autora
- pending (INTEGER, DEFAULT 0) - czy czeka na akceptację
6. TABELA ogloszenia_comments:
- id (INTEGER, PRIMARY KEY, AUTOINCREMENT)
- ogloszenieId (INTEGER) - ID ogłoszenia
- text (TEXT) - treść komentarza
- date (TEXT) - data w formacie ISO
- authorMail (TEXT) - mail autora
- isAnonymous (INTEGER, DEFAULT 0) - czy komentarz anonimowy
*/
// Tworzenie wszystkich tabel z pełnymi kolumnami
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
firstName TEXT,
lastName TEXT,
userClass TEXT,
phone TEXT,
messenger TEXT,
instagram TEXT,
mail TEXT UNIQUE,
password TEXT,
role TEXT DEFAULT 'user',
blockedUntil TEXT,
blockReason TEXT
)`);
db.run(`CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
subject TEXT,
title TEXT,
publisher TEXT,
year TEXT,
grade TEXT,
price TEXT,
stan TEXT,
photo TEXT,
date TEXT,
userMail TEXT,
userFirstName TEXT,
userLastName TEXT,
userClass TEXT,
userPhone TEXT,
userMessenger TEXT,
userInstagram TEXT
)`);
db.run(`CREATE TABLE IF NOT EXISTS spotet (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT,
photo TEXT,
date TEXT,
authorMail TEXT
)`);
db.run(`CREATE TABLE IF NOT EXISTS spotet_comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
spotetId INTEGER,
text TEXT,
date TEXT,
authorMail TEXT,
isAnonymous INTEGER DEFAULT 0
)`);
db.run(`CREATE TABLE IF NOT EXISTS ogloszenia (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
text TEXT,
photo TEXT,
date TEXT,
authorMail TEXT,
authorRole TEXT,
pending INTEGER DEFAULT 0
)`);
db.run(`CREATE TABLE IF NOT EXISTS ogloszenia_comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ogloszenieId INTEGER,
text TEXT,
date TEXT,
authorMail TEXT,
isAnonymous INTEGER DEFAULT 0
)`);
// Dodawanie konta admin i testowego (tylko raz)
async function addUsers() {
const hash = await bcrypt.hash('NpWz5678', 10);
// Konto admin
db.run(
`INSERT OR IGNORE INTO users (firstName, lastName, userClass, phone, messenger, instagram, mail, password, role)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
['Admin', 'Systemu', 'admin', '', '', '', 'admin@lo2.przemysl.edu.pl', hash, 'admin']
);
}
addUsers();
// Odkomentuj, aby dodać konta przy pierwszym uruchomieniu
app.use(cors({
origin: [
'https://wiktorksiazka.api.pei.pl',
'https://pei.pl',
'https://www.pei.pl',
'http://localhost:8081',
'http://localhost:8082',
'http://192.168.74.225:8081',
'http://192.168.74.225:8082',
'exp://192.168.74.225:8081',
'exp://192.168.74.225:8082',
'exp://l_nwawc-anonymous-8082.exp.direct' // Expo tunnel
],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'x-user-mail', 'x-user-role', 'Authorization'],
credentials: true // Wymagane dla cookies
}));
// Middleware dla cookies
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Pamięć na oferty (tymczasowa, bez bazy danych)
const offers = [];
// Konfiguracja Multera do zapisu zdjęć z bezpieczeństwem
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads'); // katalog musi istnieć!
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
// Wymuś bezpieczne rozszerzenie
const ext = path.extname(file.originalname).toLowerCase();
const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
const finalExt = allowedExts.includes(ext) ? ext : '.jpg';
cb(null, uniqueSuffix + finalExt);
}
});
// Filtr bezpieczeństwa dla plików
const fileFilter = (req, file, cb) => {
// Sprawdź MIME type
const allowedMimes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
if (!allowedMimes.includes(file.mimetype)) {
return cb(new Error('Niedozwolony typ pliku. Dozwolone: JPG, PNG, GIF, WEBP'), false);
}
// Sprawdź rozszerzenie
const ext = path.extname(file.originalname).toLowerCase();
const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
if (!allowedExts.includes(ext)) {
return cb(new Error('Niedozwolone rozszerzenie pliku'), false);
}
// Sprawdź nazwę pliku - usuń niebezpieczne znaki
const sanitizedName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '');
if (sanitizedName.length === 0) {
return cb(new Error('Nieprawidłowa nazwa pliku'), false);
}
cb(null, true);
};
const upload = multer({
storage,
fileFilter,
limits: {
fileSize: 5 * 1024 * 1024, // 5MB limit
files: 1 // tylko 1 plik
}
});
// Middleware do sprawdzania bezpieczeństwa plików
const validateUploadSecurity = (req, res, next) => {
// Sprawdź Headers bezpieczeństwa
req.headers['x-content-type-options'] = 'nosniff';
req.headers['x-frame-options'] = 'DENY';
next();
};
// Użyj middleware przed wszystkimi endpointami upload
app.use('/api/books', validateUploadSecurity);
app.use('/api/spotet', validateUploadSecurity);
// Endpoint POST - dodawanie oferty
app.post('/api/books', authAndBlockCheck, (req, res) => {
console.log('�🚀🚀 NOWY REQUEST DO /api/books! 🚀🚀🚀');
console.log('�🔄 /api/books POST - Otrzymane dane:', {
body: req.body,
hasFile: !!req.file,
user: req.user ? req.user.mail : 'BRAK'
});
// Obsługa uploadu z multer
upload.single('photo')(req, res, (err) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({ error: 'Plik jest za duży. Maksymalny rozmiar: 5MB' });
}
return res.status(400).json({ error: 'Błąd uploadu: ' + err.message });
} else if (err) {
return res.status(400).json({ error: err.message });
}
// Dane książki z formularza
const { subject, title, publisher, year, grade, price, stan } = req.body;
// Dane użytkownika z konta (z middleware)
const user = req.user;
console.log('🔍 User z middleware:', user ? user.mail : 'BRAK');
if (!user || !user.mail || !user.mail.endsWith('@lo2.przemysl.edu.pl')) {
console.log('❌ Błąd autoryzacji:', {
hasUser: !!user,
mail: user?.mail,
endsWithSchool: user?.mail?.endsWith('@lo2.przemysl.edu.pl')
});
return res.status(400).json({ message: 'Musisz być zalogowany, aby dodać książkę.' });
}
console.log('🔍 Sprawdzanie pliku:', { hasFile: !!req.file });
if (!req.file) {
console.log('❌ Brak zdjęcia');
return res.status(400).json({ error: 'Brak zdjęcia (photo)' });
}
// Loguj informacje o uploadowanym pliku
console.log('📸 Upload pliku:', {
originalname: req.file.originalname,
filename: req.file.filename,
mimetype: req.file.mimetype,
size: req.file.size,
user: user.mail
});
const photoUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
const date = new Date().toISOString();
db.run(
`INSERT INTO books (subject, title, publisher, year, grade, price, stan, photo, date, userMail, userFirstName, userLastName, userClass, userPhone, userMessenger, userInstagram)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[subject, title, publisher, year, grade, price, stan, photoUrl, date, user.mail, user.firstName, user.lastName, user.userClass, user.phone, user.messenger, user.instagram],
function (err) {
if (err) return res.status(500).json({ message: 'Błąd serwera przy dodawaniu książki.' });
res.status(201).json({ id: this.lastID });
}
);
});
});
// Pobierz wszystkie oferty
app.get('/api/books', (req, res) => {
db.all('SELECT * FROM books ORDER BY date DESC', [], (err, rows) => {
if (err) return res.status(500).json({ message: 'Błąd serwera przy pobieraniu książek.' });
res.json(rows);
});
});
// Pobierz jedną ofertę po ID
app.get('/api/books/:id', (req, res) => {
db.get('SELECT * FROM books WHERE id = ?', [req.params.id], (err, row) => {
if (err) return res.status(500).json({ message: 'Błąd bazy danych' });
if (!row) return res.status(404).json({ message: 'Nie znaleziono oferty' });
res.json(row);
});
});
// Edytuj ofertę po ID
app.put('/api/books/:id', (req, res) => {
const { subject, title, publisher, year, grade, price, stan, photo } = req.body;
db.run(
`UPDATE books SET subject = ?, title = ?, publisher = ?, year = ?, grade = ?, price = ?, stan = ?, photo = ? WHERE id = ?`,
[subject, title, publisher, year, grade, price, stan, photo, req.params.id],
function(err) {
if (err) return res.status(500).json({ message: 'Błąd aktualizacji oferty' });
res.json({ message: 'Oferta zaktualizowana' });
}
);
});
// Usuń ofertę (admin/przewodniczący dowolną, user tylko swoją)
app.delete('/api/books/:id', authAndBlockCheck, (req, res) => {
const { id } = req.params;
const currentUser = req.user; // Z middleware authAndBlockCheck
db.get('SELECT * FROM books WHERE id = ?', [id], (err, book) => {
if (err) return res.status(500).json({ message: 'Błąd serwera przy sprawdzaniu oferty.' });
if (!book) return res.status(404).json({ message: 'Nie znaleziono oferty' });
// Pozwól adminowi/przewodniczącemu lub właścicielowi
if (
currentUser.mail === book.userMail ||
currentUser.mail === 'admin@lo2.przemysl.edu.pl' ||
currentUser.role === 'admin' ||
currentUser.role === 'przewodniczący' ||
currentUser.role === 'przewodniczacy'
) {
db.run('DELETE FROM books WHERE id = ?', [id], function (err2) {
if (err2) return res.status(500).json({ message: 'Błąd serwera przy usuwaniu oferty' });
res.json({ message: 'Oferta usunięta' });
});
} else {
res.status(403).json({ message: 'Brak uprawnień do usunięcia tej oferty' });
}
});
});
// ====================================================================
// ✅ SYSTEM WERYFIKACJI EMAILA PRZEZ KOD
// ====================================================================
// Tabela dla kodów weryfikacyjnych
db.run(`CREATE TABLE IF NOT EXISTS verification_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL,
code TEXT NOT NULL,
expires_at TEXT NOT NULL,
used INTEGER DEFAULT 0,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)`);
// Funkcja generowania kodu weryfikacyjnego
function generateVerificationCode() {
return Math.random().toString().slice(2, 8).padStart(6, '0');
}
// ✅ ENDPOINT: Wysłanie kodu weryfikacyjnego na email
app.post('/api/send-verification-code', async (req, res) => {
try {
const { email, name } = req.body;
// Walidacja
if (!email || !name) {
return res.status(400).json({
success: false,
message: 'Email i imię są wymagane'
});
}
// Sprawdź format emaila
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return res.status(400).json({
success: false,
message: 'Nieprawidłowy format email'
});
}
// Sprawdź czy email już nie istnieje w bazie
db.get('SELECT * FROM users WHERE mail = ?', [email], async (err, existingUser) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({
success: false,
message: 'Błąd serwera'
});
}
if (existingUser) {
return res.status(400).json({
success: false,
message: 'Użytkownik z tym emailem już istnieje'
});
}
// Wygeneruj kod
const code = generateVerificationCode();
const expiresAt = new Date(Date.now() + 15 * 60 * 1000).toISOString(); // 15 minut
// Usuń stare kody dla tego emaila
db.run('DELETE FROM verification_codes WHERE email = ?', [email], (deleteErr) => {
if (deleteErr) {
console.error('Error deleting old codes:', deleteErr);
}
// Zapisz nowy kod
db.run(
'INSERT INTO verification_codes (email, code, expires_at) VALUES (?, ?, ?)',
[email, code, expiresAt],
async function(insertErr) {
if (insertErr) {
console.error('Error saving verification code:', insertErr);
return res.status(500).json({
success: false,
message: 'Błąd zapisu kodu weryfikacyjnego'
});
}
// Wyślij email z kodem
try {
const htmlMessage = `
<h2 style='color:#FF6B35;'>Wirtualny korytarz LO2</h2>
<p style='font-size:1.1em;'>Weryfikacja konta:</p>
<h3 style='color:#333;'>Twój kod weryfikacyjny</h3>
<div style='border:2px dashed #FF6B35; background:#f9f9f9; padding:18px; font-size:2em; text-align:center; letter-spacing:4px; margin:18px 0 24px 0; color:#FF6B35; font-weight:bold;'>
${code}
</div>
<p>Cześć <b>${name}</b>!</p>
<p>Wpisz powyższy kod w aplikacji mobilnej, aby potwierdzić swój adres e-mail i zakończyć rejestrację.</p>
<p><strong>Kod jest ważny przez 15 minut.</strong></p>
<hr>
<small style='color:#888;'>Wiadomość wygenerowana automatycznie przez aplikację Wirtualny korytarz LO2.<br>
Wysłano: ${new Date().toLocaleString('pl-PL')} z IP: ${req.ip}</small>
`;
await sendMail(
email,
'Kod weryfikacyjny - Wirtualny korytarz LO2',
htmlMessage,
'peizamowieniaikontaktpei@gmail.com'
);
console.log(`✅ Kod weryfikacyjny wysłany na ${email}: ${code}`);
res.json({
success: true,
message: 'Kod weryfikacyjny został wysłany na podany adres email',
expiresIn: 15 // minuty
});
} catch (emailError) {
console.error('Email sending error:', emailError);
// Usuń kod z bazy jeśli nie udało się wysłać emaila
db.run('DELETE FROM verification_codes WHERE id = ?', [this.lastID]);
res.status(500).json({
success: false,
message: 'Błąd wysyłania emaila. Spróbuj ponownie.'
});
}
}
);
});
});
} catch (error) {
console.error('Send verification code error:', error);
res.status(500).json({
success: false,
message: 'Błąd serwera'
});
}
});
// ✅ ENDPOINT: Weryfikacja kodu
app.post('/api/verify-code', async (req, res) => {
try {
const { email, code } = req.body;
// Walidacja
if (!email || !code) {
return res.status(400).json({
success: false,
message: 'Email i kod są wymagane'
});
}
// Znajdź kod w bazie
db.get(
'SELECT * FROM verification_codes WHERE email = ? AND code = ? AND used = 0 ORDER BY created_at DESC LIMIT 1',
[email, code],
(err, verificationRecord) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({
success: false,
message: 'Błąd serwera'
});
}
if (!verificationRecord) {
return res.status(400).json({
success: false,
message: 'Nieprawidłowy kod weryfikacyjny'
});
}
// Sprawdź czy kod nie wygasł
const now = new Date();
const expiresAt = new Date(verificationRecord.expires_at);
if (now > expiresAt) {
return res.status(400).json({
success: false,
message: 'Kod weryfikacyjny wygasł. Poproś o nowy kod.'
});
}
// NIE oznaczamy kodu jako użyty - zostanie oznaczony dopiero przy rejestracji
console.log(`✅ Kod zweryfikowany pomyślnie dla ${email}`);
res.json({
success: true,
message: 'Kod weryfikacyjny poprawny. Możesz kontynuować rejestrację.',
verified: true
});
}
);
} catch (error) {
console.error('Verify code error:', error);
res.status(500).json({
success: false,
message: 'Błąd serwera'
});
}
});
// REJESTRACJA (ZMODYFIKOWANA - z weryfikacją kodu)
app.post('/api/register', async (req, res) => {
console.log('🔄 /api/register - Otrzymane dane:', req.body);
const { firstName, lastName, userClass, phone, messenger, instagram, mail, password, verificationCode } = req.body;
console.log('🔍 Sprawdzanie czy użytkownik już istnieje:', mail);
db.get('SELECT * FROM users WHERE mail = ?', [mail], async (err, row) => {
if (err) {
console.error('❌ Database error checking user:', err);
return res.status(500).json({ message: 'Błąd bazy danych' });
}
if (row) {
console.log('❌ Użytkownik już istnieje:', mail);
return res.status(400).json({ message: 'Użytkownik z tym mailem już istnieje' });
}
console.log('🔍 Sprawdzanie kodu weryfikacyjnego:', verificationCode, 'dla:', mail);
// Weryfikacja kodu
db.get(
'SELECT * FROM verification_codes WHERE email = ? AND code = ? AND used = 0',
[mail, verificationCode],
async (err, verificationRecord) => {
if (err) {
console.error('❌ Database error checking verification code:', err);
return res.status(500).json({ message: 'Błąd bazy danych' });
}
if (!verificationRecord) {
console.log('❌ Nieprawidłowy kod weryfikacyjny dla:', mail, 'kod:', verificationCode);
return res.status(400).json({ message: 'Nieprawidłowy lub użyty kod weryfikacyjny' });
}
console.log('✅ Znaleziono kod weryfikacyjny:', verificationRecord);
// Sprawdź czy kod nie wygasł
const now = new Date();
const expiresAt = new Date(verificationRecord.expires_at);
if (now > expiresAt) {
return res.status(400).json({ message: 'Kod weryfikacyjny wygasł. Poproś o nowy kod.' });
}
const hash = await bcrypt.hash(password, 10);
db.run(
`INSERT INTO users (firstName, lastName, userClass, phone, messenger, instagram, mail, password)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[firstName, lastName, userClass, phone, messenger, instagram, mail, hash],
function (err) {
if (err) return res.status(500).json({ message: 'Błąd zapisu do bazy' });
// Generuj token JWT po udanej rejestracji
const newUser = { firstName, lastName, userClass, phone, messenger, instagram, mail, role: 'user' };
const token = jwt.sign(newUser, SECRET, { expiresIn: '30d' });
// Ustaw httpOnly cookie z tokenem
res.cookie('jwt_token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // Secure tylko w production
sameSite: 'strict',
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 dni
domain: process.env.NODE_ENV === 'production' ? '.pei.pl' : undefined // Domain tylko w production
});
// Oznacz kod jako użyty
db.run('UPDATE verification_codes SET used = 1 WHERE id = ?', [verificationRecord.id]);
res.json({
message: 'Rejestracja zakończona',
user: newUser
});
}
);
}
);
});
});
// LOGOWANIE
app.post('/api/login', (req, res) => {
const { mail, password } = req.body;
db.get('SELECT * FROM users WHERE mail = ?', [mail], async (err, user) => {
if (err) return res.status(500).json({ message: 'Błąd bazy danych' });
if (!user) return res.status(400).json({ message: 'Nieprawidłowy e-mail lub hasło' });
// SPRAWDŹ BLOKADĘ PRZED SPRAWDZENIEM HASŁA!
if (user.blockedUntil && new Date(user.blockedUntil) > new Date()) {
const ms = new Date(user.blockedUntil) - new Date();
const min = Math.ceil(ms / 60000);
return res.status(403).json({
message: `Konto zablokowane do ${user.blockedUntil} (${min} min). Powód: ${user.blockReason || 'brak'}`
});
}
// Dopiero teraz sprawdzaj hasło!
const ok = await bcrypt.compare(password, user.password);
if (!ok) return res.status(400).json({ message: 'Nieprawidłowy e-mail lub hasło' });
// Generowanie tokenu JWT
const token = jwt.sign({ mail: user.mail, role: user.role }, SECRET, { expiresIn: '7d' });
// Ustaw httpOnly cookie z tokenem
res.cookie('jwt_token', token, {
httpOnly: true, // Niedostępne dla JavaScript
secure: process.env.NODE_ENV === 'production', // Secure tylko w production
sameSite: 'strict', // CSRF protection
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 dni w milisekundach
domain: process.env.NODE_ENV === 'production' ? '.pei.pl' : undefined // Domain tylko w production
});
// Usuń pole password z usera przed wysłaniem!
const { password: _, ...userData } = user;
// Zwróć dane użytkownika bez tokenu (token jest w cookie)
res.json({ user: userData, message: 'Zalogowano pomyślnie' });
});
});
// WYLOGOWANIE - endpoint do usuwania cookie
app.post('/api/logout', (req, res) => {
// Usuń cookie z tokenem
res.clearCookie('jwt_token', {
domain: process.env.NODE_ENV === 'production' ? '.pei.pl' : undefined,
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict'
});
res.json({ message: 'Wylogowano pomyślnie' });
});
// WERYFIKACJA TOKENU - endpoint do sprawdzania ważności tokenu i pobierania danych użytkownika
app.post('/api/verify-token', (req, res) => {
// Sprawdź token tylko w cookie (już nie fallback na Authorization header)
let token = req.cookies.jwt_token;
if (!token) {
return res.status(401).json({ message: 'Brak tokenu autoryzacji' });
}
jwt.verify(token, SECRET, (err, decoded) => {
if (err) {
return res.status(401).json({ message: 'Nieprawidłowy lub wygasły token' });
}
// Pobierz aktualną wersję użytkownika z bazy
db.get('SELECT * FROM users WHERE mail = ?', [decoded.mail], (err, user) => {
if (err || !user) {
return res.status(401).json({ message: 'Użytkownik nie istnieje' });
}
// Sprawdź blokadę
if (user.blockedUntil && new Date(user.blockedUntil) > new Date()) {
const ms = new Date(user.blockedUntil) - new Date();
const min = Math.ceil(ms / 60000);
return res.status(403).json({
message: `Konto zablokowane do ${user.blockedUntil} (${min} min). Powód: ${user.blockReason || 'brak'}`
});
}
// Usuń hasło z odpowiedzi
const { password: _, ...userData } = user;
res.json({
valid: true,
user: userData,
token: token // zwróć ten sam token dla kompatybilności
});
});
});
});
// Usuń konto użytkownika (i powiązane książki)
app.delete('/api/users/:mail', (req, res) => {
const mail = req.params.mail;
db.run('DELETE FROM users WHERE mail = ?', [mail], function (err) {
if (err) return res.status(500).json({ message: 'Błąd serwera przy usuwaniu konta' });
res.json({ message: 'Konto zostało usunięte' });
});
});
app.put('/api/users/:mail', (req, res) => {
const { firstName, lastName, userClass, phone, messenger, instagram, blockedUntil, blockReason, role } = req.body;
db.run(
`UPDATE users SET firstName = ?, lastName = ?, userClass = ?, phone = ?, messenger = ?, instagram = ?, blockedUntil = ?, blockReason = ?, role = ? WHERE mail = ?`,
[firstName, lastName, userClass, phone, messenger, instagram, blockedUntil, blockReason, role, req.params.mail],
function(err) {
if (err) return res.status(500).json({ message: 'Błąd aktualizacji danych' });
res.json({ message: 'Dane użytkownika zaktualizowane' });
}
);
});
// Middleware do sprawdzania roli admina (opcjonalnie, jeśli masz autoryzację po sesji/tokenie)
function isAdmin(req, res, next) {
// Jeśli masz sesję lub JWT, sprawdź czy user jest adminem
// Przykład: if (req.user && req.user.role === 'admin') next();
// Jeśli nie masz autoryzacji, sprawdzaj po mailu (nie jest to bezpieczne, ale działa lokalnie):
if (req.body.mail === 'admin@lo2.przemysl.edu.pl') return next();
res.status(403).json({ message: 'Brak uprawnień' });
}
// Endpoint do usuwania wszystkich ofert (tylko admin)
app.delete('/api/books', isAdmin, (req, res) => {
db.run('DELETE FROM books', function(err) {
if (err) return res.status(500).json({ message: 'Błąd usuwania ofert' });
res.json({ message: 'Wszystkie oferty zostały usunięte' });
});
});
// Endpoint: zwracanie szczegółów żądania HTTP jako JSON
app.get('/request-info', (req, res) => {
res.json({
method: req.method,
url: req.originalUrl,
headers: req.headers,
ip: req.ip,
protocol: req.protocol,
hostname: req.hostname,
query: req.query,
body: req.body
});
});
// Test endpoint dla diagnozy połączenia
app.get('/api/test', (req, res) => {
res.json({
message: 'Backend działa!',
timestamp: new Date().toISOString(),
ip: req.ip,
userAgent: req.get('User-Agent')
});
});
// Uruchom serwer na wszystkich interfejsach
const PORT = 8000; // Zmieniono z 3000 na 8000
app.listen(PORT, '0.0.0.0', () => {
console.log(`🚀 Serwer działa na http://0.0.0.0:${PORT} (lub przez domenę jeśli dostępna)`);
});
// Pobierz wszystkich użytkowników (tylko admin)
app.get('/api/users', authAndBlockCheck, (req, res) => {
// Tylko admin może przeglądać listę użytkowników
if (req.user.role !== 'admin') {
return res.status(403).json({ message: 'Brak uprawnień. Tylko admin może przeglądać listę użytkowników.' });
}
db.all('SELECT id, firstName, lastName, userClass, phone, messenger, instagram, mail, role, blockedUntil, blockReason FROM users', [], (err, rows) => {
if (err) return res.status(500).json({ message: 'Błąd bazy danych' });
// Usuń hasła z odpowiedzi (dodatkowe zabezpieczenie)
const usersWithoutPasswords = rows.map(user => {
const { password, ...userWithoutPassword } = user;
return userWithoutPassword;
});
res.json(usersWithoutPasswords);
});
});
app.get('/api/users/:mail', authAndBlockCheck, (req, res) => {
db.get('SELECT * FROM users WHERE mail = ?', [req.params.mail], (err, row) => {
if (err) return res.status(500).json({ message: 'Błąd bazy danych' });
if (!row) return res.status(404).json({ message: 'Nie znaleziono użytkownika' });
// Sprawdź czy użytkownik ma uprawnienia - może przeglądać tylko swoje dane lub admin może wszystkie
const requestingUser = req.user; // z middleware authAndBlockCheck
if (requestingUser.mail !== req.params.mail && requestingUser.role !== 'admin') {
return res.status(403).json({ message: 'Brak uprawnień do przeglądania danych tego użytkownika' });
}
// Usuń hasło z odpowiedzi
const { password, ...userData } = row;
res.json(userData);
});
});
// Dodawanie anonimowej wiadomości (z opcjonalnym zdjęciem)
// Użyj tej samej bezpiecznej konfiguracji multer dla spotted
const spotetUpload = multer({
storage,
fileFilter,
limits: {
fileSize: 5 * 1024 * 1024, // 5MB limit
files: 1 // tylko 1 plik
}
});
// DODANO: authAndBlockCheck jako middleware!
app.post('/api/spotet', authAndBlockCheck, (req, res) => {
// Obsługa uploadu z multer
spotetUpload.single('photo')(req, res, (err) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({ error: 'Plik jest za duży. Maksymalny rozmiar: 5MB' });
}
return res.status(400).json({ error: 'Błąd uploadu: ' + err.message });
} else if (err) {
return res.status(400).json({ error: err.message });
}
const { text } = req.body;
// BEZPIECZEŃSTWO: Pobierz authorMail z tokena, nie z requesta
const user = req.user; // Z middleware authAndBlockCheck
const authorMail = user.mail;
if (!authorMail) return res.status(401).json({ message: 'Musisz być zalogowany.' });
if (!text || text.trim().length === 0) return res.status(400).json({ message: 'Wiadomość nie może być pusta.' });
let photoUrl = '';
if (req.file) {
// Loguj informacje o uploadowanym pliku
console.log('📸 Upload pliku spotted:', {
originalname: req.file.originalname,
filename: req.file.filename,
mimetype: req.file.mimetype,
size: req.file.size,
user: authorMail
});
photoUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
}
const date = new Date().toISOString();
db.run(
`INSERT INTO spotet (text, photo, date, authorMail) VALUES (?, ?, ?, ?)`,
[text, photoUrl, date, authorMail],
function(err) {
if (err) return res.status(500).json({ message: 'Błąd serwera przy dodawaniu wiadomości.' });
res.status(201).json({ id: this.lastID });
}
);
});
});
// Pobierz wszystkie anonimowe wiadomości
app.get('/api/spotet', (req, res) => {
// Sprawdź czy user jest zalogowany i czy jest adminem - używaj cookies
let token = req.cookies.jwt_token;
let isUserAdmin = false;
let currentUserMail = null;
if (token) {
try {
const decoded = jwt.verify(token, SECRET);
currentUserMail = decoded.mail;
isUserAdmin = decoded.role === 'admin';
} catch (err) {
// Token nieprawidłowy, kontynuuj jako niezalogowany
}
}
db.all(`
SELECT spotet.id, spotet.text, spotet.photo, spotet.date, spotet.authorMail, users.role as authorRole
FROM spotet
LEFT JOIN users ON spotet.authorMail = users.mail
ORDER BY date DESC
`, [], (err, rows) => {
if (err) return res.status(500).json({ message: 'Błąd serwera przy pobieraniu wiadomości.' });
// Filtruj dane w zależności od uprawnień użytkownika
const filteredRows = rows.map(row => ({
...row,
authorMail: isUserAdmin ? row.authorMail : null, // Tylko admin widzi emaile
isCurrentUserAdmin: isUserAdmin,
currentUserMail: currentUserMail
}));
res.json(filteredRows);
});
});
app.delete('/api/spotet/:id', (req, res) => {
const { id } = req.params;
db.run('DELETE FROM spotet WHERE id = ?', [id], function(err) {
if (err) return res.status(500).json({ message: 'Błąd serwera przy usuwaniu.' });
res.json({ message: 'Usunięto.' });
});
});
// Dodawanie komentarza do wiadomości
app.post('/api/spotet/:id/comment', authAndBlockCheck, (req, res) => {
const { id } = req.params;
const { text, isAnonymous } = req.body;
// BEZPIECZEŃSTWO: Pobierz autorMail z tokena, nie z requesta
const user = req.user; // Z middleware authAndBlockCheck
const authorMail = user.mail;
if (!text || text.trim().length === 0) {
return res.status(400).json({ message: 'Komentarz nie może być pusty.' });
}
const date = new Date().toISOString();
db.run(
`INSERT INTO spotet_comments (spotetId, text, date, authorMail, isAnonymous)
VALUES (?, ?, ?, ?, ?)`,
[id, text, date, authorMail, isAnonymous ? 1 : 0],
function(err) {
if (err) return res.status(500).json({ message: 'Błąd serwera przy dodawaniu komentarza.' });
res.status(201).json({ id: this.lastID });
}
);
});