-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
824 lines (697 loc) · 25.3 KB
/
server.js
File metadata and controls
824 lines (697 loc) · 25.3 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
const express = require('express');
const path = require('path');
const compression = require('compression');
const helmet = require('helmet');
const cors = require('cors');
const crypto = require('crypto');
const db = require('./lib/database');
const app = express();
const PORT = process.env.PORT || process.env.NODEJS_PORT || 5000;
// Admin credentials (in production, use environment variables and proper hashing)
const ADMIN_USERNAME = process.env.ADMIN_USERNAME || 'admin';
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'admin123';
// Session storage (in production, use Redis or database)
const sessions = new Map();
// Security middleware - CSP disabled temporarily for Cloudinary testing
app.use(helmet({
contentSecurityPolicy: false
}));
// Enable CORS
app.use(cors());
// Enable compression
app.use(compression());
// Parse JSON bodies
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Session middleware
function generateSessionId() {
return crypto.randomBytes(32).toString('hex');
}
function createSession(userId) {
const sessionId = generateSessionId();
const session = {
id: sessionId,
userId,
createdAt: new Date(),
lastActivity: new Date()
};
sessions.set(sessionId, session);
return sessionId;
}
function validateSession(sessionId) {
const session = sessions.get(sessionId);
if (!session) return null;
// Check if session expired (24 hours)
const now = new Date();
const sessionAge = now - session.lastActivity;
if (sessionAge > 24 * 60 * 60 * 1000) {
sessions.delete(sessionId);
return null;
}
// Update last activity
session.lastActivity = now;
return session;
}
function requireAuth(req, res, next) {
const sessionId = req.headers['x-session-id'] || req.cookies?.sessionId;
const session = validateSession(sessionId);
if (!session) {
return res.status(401).json({
success: false,
message: 'Authentication required'
});
}
req.session = session;
next();
}
// Try to load optional dependencies for file uploads
let multer, sharp;
try {
multer = require('multer');
sharp = require('sharp');
} catch (error) {
console.log('Image upload dependencies not available. File upload will be disabled.');
}
const fs = require('fs').promises;
const fsSync = require('fs');
// Ensure uploads directory exists and configure multer only if available
let uploadsDir, upload;
if (multer && sharp) {
uploadsDir = path.join(__dirname, 'uploads');
fs.mkdir(uploadsDir, { recursive: true }).catch(console.error);
// Configure multer for memory storage
upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit
fileFilter: (req, file, cb) => {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Only image files are allowed'), false);
}
}
});
}
// Serve uploads directory if it exists
if (uploadsDir) {
app.use('/uploads', express.static(uploadsDir, {
maxAge: '7d',
etag: true
}));
}
// Serve static files with proper headers
app.use(express.static(path.join(__dirname), {
maxAge: '1d',
etag: true,
setHeaders: (res, path) => {
if (path.endsWith('.css')) {
res.setHeader('Content-Type', 'text/css');
}
if (path.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
}
}
}));
// Serve admin static files
app.use('/admin', express.static(path.join(__dirname, 'admin'), {
maxAge: '1h',
etag: true,
setHeaders: (res, path) => {
if (path.endsWith('.css')) {
res.setHeader('Content-Type', 'text/css');
}
if (path.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
}
}
}));
// Explicit routes for CSS files
app.get('/styles.css', (req, res) => {
res.setHeader('Content-Type', 'text/css');
res.sendFile(path.join(__dirname, 'styles.css'));
});
app.get('/admin/admin-styles.css', (req, res) => {
res.setHeader('Content-Type', 'text/css');
res.sendFile(path.join(__dirname, 'admin', 'admin-styles.css'));
});
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/admin', (req, res) => {
res.redirect('/admin/');
});
app.get('/admin/', (req, res) => {
res.sendFile(path.join(__dirname, 'admin', 'index.html'));
});
app.get('/admin/dashboard', (req, res) => {
res.sendFile(path.join(__dirname, 'admin', 'dashboard.html'));
});
// Authentication endpoints
app.post('/admin/login', async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({
success: false,
message: 'חסרים פרטי התחברות'
});
}
if (username === ADMIN_USERNAME && password === ADMIN_PASSWORD) {
const sessionId = createSession('admin');
res.json({
success: true,
sessionId,
message: 'התחברות בוצעה בהצלחה'
});
} else {
res.status(401).json({
success: false,
message: 'שם משתמש או סיסמה שגויים'
});
}
});
app.post('/admin/logout', requireAuth, (req, res) => {
const sessionId = req.headers['x-session-id'] || req.cookies?.sessionId;
if (sessionId) {
sessions.delete(sessionId);
}
res.json({
success: true,
message: 'התנתקות בוצעה בהצלחה'
});
});
app.get('/admin/auth/verify', (req, res) => {
const sessionId = req.headers['x-session-id'] || req.cookies?.sessionId;
const session = validateSession(sessionId);
if (session) {
res.json({
success: true,
authenticated: true
});
} else {
res.status(401).json({
success: false,
authenticated: false
});
}
});
// Services endpoints
app.post('/admin/services', requireAuth, async (req, res) => {
try {
const serviceData = req.body;
if (!serviceData.name || !serviceData.description) {
return res.status(400).json({
success: false,
message: 'חסרים שדות חובה'
});
}
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const siteData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
if (!siteData.services) {
siteData.services = [];
}
// Add new service
const newService = {
id: Date.now(),
name: serviceData.name,
description: serviceData.description,
icon: serviceData.icon || 'default',
active: true,
order: siteData.services.length,
...serviceData
};
siteData.services.push(newService);
await fs.writeFile(dataPath, JSON.stringify(siteData, null, 2));
res.json({
success: true,
service: newService,
message: 'השירות נוסף בהצלחה'
});
} catch (error) {
console.error('Error adding service:', error);
res.status(500).json({
success: false,
message: 'שגיאה בהוספת השירות'
});
}
});
app.put('/admin/services/:id', requireAuth, async (req, res) => {
try {
const serviceId = parseInt(req.params.id);
const serviceData = req.body;
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const siteData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
const serviceIndex = siteData.services?.findIndex(s => s.id === serviceId);
if (serviceIndex === -1) {
return res.status(404).json({
success: false,
message: 'השירות לא נמצא'
});
}
siteData.services[serviceIndex] = { ...siteData.services[serviceIndex], ...serviceData };
await fs.writeFile(dataPath, JSON.stringify(siteData, null, 2));
res.json({
success: true,
service: siteData.services[serviceIndex],
message: 'השירות עודכן בהצלחה'
});
} catch (error) {
console.error('Error updating service:', error);
res.status(500).json({
success: false,
message: 'שגיאה בעדכון השירות'
});
}
});
app.delete('/admin/services/:id', requireAuth, async (req, res) => {
try {
const serviceId = parseInt(req.params.id);
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const siteData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
const originalLength = siteData.services?.length || 0;
siteData.services = siteData.services?.filter(s => s.id !== serviceId) || [];
if (siteData.services.length === originalLength) {
return res.status(404).json({
success: false,
message: 'השירות לא נמצא'
});
}
await fs.writeFile(dataPath, JSON.stringify(siteData, null, 2));
res.json({
success: true,
message: 'השירות נמחק בהצלחה'
});
} catch (error) {
console.error('Error deleting service:', error);
res.status(500).json({
success: false,
message: 'שגיאה במחיקת השירות'
});
}
});
// Projects endpoints
app.delete('/admin/projects/:id', requireAuth, async (req, res) => {
try {
const projectId = parseInt(req.params.id);
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const siteData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
const originalLength = siteData.projects?.length || 0;
siteData.projects = siteData.projects?.filter(p => p.id !== projectId) || [];
if (siteData.projects.length === originalLength) {
return res.status(404).json({
success: false,
message: 'הפרויקט לא נמצא'
});
}
await fs.writeFile(dataPath, JSON.stringify(siteData, null, 2));
res.json({
success: true,
message: 'הפרויקט נמחק בהצלחה'
});
} catch (error) {
console.error('Error deleting project:', error);
res.status(500).json({
success: false,
message: 'שגיאה במחיקת הפרויקט'
});
}
});
// Contact submissions endpoints
app.patch('/admin/submissions/:id', requireAuth, async (req, res) => {
try {
const submissionId = parseInt(req.params.id);
const { status, price, deadline, notes, lastUpdated } = req.body;
console.log('PATCH /admin/submissions:', submissionId);
console.log('Request body:', req.body);
console.log('Status received:', status);
const validStatuses = ['new', 'contacted', 'quoted', 'approved', 'in_development', 'completed', 'cancelled', 'read', 'replied'];
if (status && !validStatuses.includes(status)) {
console.log('Invalid status:', status, 'Valid statuses:', validStatuses);
return res.status(400).json({
success: false,
message: 'סטטוס לא תקין'
});
}
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const siteData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
const submission = siteData.contact?.submissions?.find(s => s.id === submissionId);
if (!submission) {
return res.status(404).json({
success: false,
message: 'הפנייה לא נמצאה'
});
}
// Update fields if provided
if (status) submission.status = status;
if (price !== undefined) submission.price = price;
if (deadline !== undefined) submission.deadline = deadline;
if (notes !== undefined) submission.notes = notes;
if (lastUpdated) submission.lastUpdated = lastUpdated;
await fs.writeFile(dataPath, JSON.stringify(siteData, null, 2));
res.json({
success: true,
submission,
message: 'הפנייה עודכנה בהצלחה'
});
} catch (error) {
console.error('Error updating submission:', error);
res.status(500).json({
success: false,
message: 'שגיאה בעדכון הפנייה'
});
}
});
app.delete('/admin/submissions/:id', requireAuth, async (req, res) => {
try {
const submissionId = parseInt(req.params.id);
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const siteData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
if (!siteData.contact?.submissions) {
return res.status(404).json({
success: false,
message: 'הפנייה לא נמצאה'
});
}
const originalLength = siteData.contact.submissions.length;
siteData.contact.submissions = siteData.contact.submissions.filter(s => s.id !== submissionId);
if (siteData.contact.submissions.length === originalLength) {
return res.status(404).json({
success: false,
message: 'הפנייה לא נמצאה'
});
}
await fs.writeFile(dataPath, JSON.stringify(siteData, null, 2));
res.json({
success: true,
message: 'הפנייה נמחקה בהצלחה'
});
} catch (error) {
console.error('Error deleting submission:', error);
res.status(500).json({
success: false,
message: 'שגיאה במחיקת הפנייה'
});
}
});
// Settings endpoint
app.post('/admin/settings', requireAuth, async (req, res) => {
try {
const settingsData = req.body;
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const siteData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
siteData.settings = { ...siteData.settings, ...settingsData };
await fs.writeFile(dataPath, JSON.stringify(siteData, null, 2));
res.json({
success: true,
settings: siteData.settings,
message: 'ההגדרות נשמרו בהצלחה'
});
} catch (error) {
console.error('Error saving settings:', error);
res.status(500).json({
success: false,
message: 'שגיאה בשמירת ההגדרות'
});
}
});
// Image upload endpoint
app.post('/upload-image', (req, res, next) => {
// Check if upload functionality is available
if (!upload || !sharp) {
return res.status(503).json({
success: false,
message: 'העלאת תמונות אינה זמינה כרגע'
});
}
upload.single('image')(req, res, async (err) => {
if (err) {
return res.status(400).json({
success: false,
message: err.message
});
}
try {
if (!req.file) {
return res.status(400).json({
success: false,
message: 'לא נמצא קובץ תמונה'
});
}
// Generate unique filename
const timestamp = Date.now();
const randomString = Math.random().toString(36).substring(7);
const filename = `project_${timestamp}_${randomString}.webp`;
const filepath = path.join(uploadsDir, filename);
// Process image with Sharp: resize, optimize, convert to WebP
await sharp(req.file.buffer)
.resize(600, 400, {
fit: 'cover',
position: 'center'
})
.webp({
quality: 85,
effort: 6
})
.toFile(filepath);
// Return the image URL
const imageUrl = `/uploads/${filename}`;
res.json({
success: true,
imageUrl: imageUrl,
message: 'התמונה הועלתה בהצלחה'
});
} catch (error) {
console.error('Image upload error:', error);
res.status(500).json({
success: false,
message: 'שגיאה בהעלאת התמונה'
});
}
});
});
// Contact form endpoint
app.post('/contact', async (req, res) => {
const { name, email, phone, projectType, budget, timeline, description } = req.body;
// Basic validation
if (!name || !email || !phone || !description) {
return res.status(400).json({
success: false,
message: 'חסרים שדות חובה'
});
}
// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return res.status(400).json({
success: false,
message: 'כתובת אימייל לא תקינה'
});
}
try {
// Save contact form submission to site data
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const siteData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
// Initialize contact submissions if not exists
if (!siteData.contact) {
siteData.contact = { fields: [], submissions: [] };
}
if (!siteData.contact.submissions) {
siteData.contact.submissions = [];
}
// Create new submission
const newSubmission = {
id: Date.now(),
name,
email,
phone,
projectType,
budget,
timeline,
description,
timestamp: new Date().toISOString(),
status: 'new' // new, read, replied
};
// Add to submissions array
siteData.contact.submissions.unshift(newSubmission); // Add to beginning
// Keep only last 100 submissions
if (siteData.contact.submissions.length > 100) {
siteData.contact.submissions = siteData.contact.submissions.slice(0, 100);
}
// Save back to file
await fs.writeFile(dataPath, JSON.stringify(siteData, null, 2));
// Contact form submission processed successfully
res.json({
success: true,
message: 'תודה על פנייתך! נחזור אליך בהקדם.'
});
} catch (error) {
console.error('Error saving contact submission:', error);
res.status(500).json({
success: false,
message: 'שגיאה בשמירת הפנייה. נסה שוב מאוחר יותר.'
});
}
});
// Site data endpoint
app.get('/site-data', async (req, res) => {
try {
const siteData = await db.getSiteData();
res.json(siteData);
} catch (error) {
console.error('Error reading site data:', error);
// Try to return the original data file as fallback
try {
const fallbackPath = path.join(__dirname, 'data', 'siteData.json');
const fallbackData = await fs.readFile(fallbackPath, 'utf8');
const jsonData = JSON.parse(fallbackData);
res.json(jsonData);
} catch (fallbackError) {
console.error('Fallback also failed:', fallbackError);
res.status(500).json({
success: false,
message: 'שגיאה בטעינת הנתונים'
});
}
}
});
// Site data update endpoint
app.post('/site-data', async (req, res) => {
try {
const updatedData = req.body;
// Validate data structure
if (!updatedData || typeof updatedData !== 'object') {
return res.status(400).json({
success: false,
message: 'נתונים לא תקינים'
});
}
// Save to Supabase
const result = await db.updateSiteData(updatedData);
if (result.success) {
res.json({
success: true,
message: 'הנתונים נשמרו בהצלחה ל-Supabase'
});
} else {
res.status(500).json({
success: false,
message: 'שגיאה בשמירת הנתונים: ' + result.error
});
}
} catch (error) {
console.error('Error saving site data:', error);
res.status(500).json({
success: false,
message: 'שגיאה בשמירת הנתונים: ' + error.message
});
}
});
// Project reorder endpoint
app.post('/admin/projects/reorder', requireAuth, async (req, res) => {
try {
const { projectOrder } = req.body;
if (!Array.isArray(projectOrder)) {
return res.status(400).json({
success: false,
message: 'Invalid project order data'
});
}
// Get current data from Supabase
const currentData = await db.getSiteData();
// Update project order
if (currentData.projects && Array.isArray(currentData.projects)) {
// Create a map of current projects
const projectMap = new Map();
currentData.projects.forEach(project => {
projectMap.set(project.id, project);
});
// Reorder projects based on the new order
const reorderedProjects = [];
projectOrder.forEach(orderItem => {
const project = projectMap.get(orderItem.id);
if (project) {
project.order = orderItem.order;
reorderedProjects.push(project);
}
});
// Sort by order and update the data
reorderedProjects.sort((a, b) => (a.order || 0) - (b.order || 0));
currentData.projects = reorderedProjects;
}
// Save back to Supabase
const updateResult = await db.updateSiteData(currentData);
if (!updateResult.success) {
throw new Error(updateResult.error);
}
res.json({
success: true,
message: 'סידור הפרויקטים עודכן בהצלחה'
});
} catch (error) {
console.error('Error reordering projects:', error);
res.status(500).json({
success: false,
message: 'שגיאה בעדכון סידור הפרויקטים: ' + error.message
});
}
});
// Alternative update endpoint for specific data
app.post('/update-project', async (req, res) => {
try {
const { projectId, projectData } = req.body;
if (!projectId || !projectData) {
return res.status(400).json({
success: false,
message: 'Missing project data'
});
}
// Read current data
const dataPath = path.join(__dirname, 'data', 'siteData.json');
const currentData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
// Update specific project
const projectIndex = currentData.projects.findIndex(p => p.id === projectId);
if (projectIndex !== -1) {
currentData.projects[projectIndex] = projectData;
}
// Save back
await fs.writeFile(dataPath, JSON.stringify(currentData, null, 2));
res.json({
success: true,
message: 'Project updated successfully'
});
} catch (error) {
console.error('Error updating project:', error);
res.status(500).json({
success: false,
message: error.message
});
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
environment: process.env.NODE_ENV || 'development'
});
});
// 404 handler
app.use((req, res) => {
res.status(404).sendFile(path.join(__dirname, 'index.html'));
});
// Error handler
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({
success: false,
message: 'שגיאת שרת פנימית'
});
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📱 Website: http://localhost:${PORT}`);
console.log(`⚙️ Admin Panel: http://localhost:${PORT}/admin`);
});
module.exports = app;