-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
916 lines (766 loc) · 32.1 KB
/
server.js
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
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const multer = require('multer');
const fs = require('fs');
const session = require('express-session');
const config = require('./config');
const app = express();
app.use(session({
secret: 'mercury-app-center-secret',
resave: true,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true
},
rolling: true
}));
const corsOptions = {
origin: config.urls.base(),
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'Accept', 'Cache-Control'],
credentials: true
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/icons', express.static(path.join(__dirname, 'uploads/icons')));
app.use('/projects', express.static(path.join(__dirname, 'uploads/projects')));
app.options('*', cors(corsOptions));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', config.urls.base());
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Accept');
res.header('Access-Control-Allow-Credentials', true);
res.header('Cache-Control', 'no-store');
next();
});
// Authentication middleware
const isAuthenticated = (req, res, next) => {
if (!req.session.username) {
return res.status(401).json({ success: false, error: 'User not authenticated' });
}
next();
};
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadPath = './uploads/temp';
fs.mkdirSync(uploadPath, { recursive: true });
cb(null, uploadPath);
},
filename: function (req, file, cb) {
cb(null, `${Date.now()}-${file.originalname}`);
}
});
const upload = multer({
storage: storage,
fileFilter: function (req, file, cb) {
if (file.originalname.endsWith('.app') ||
file.originalname.endsWith('.ipa') ||
file.originalname.endsWith('.apk')) {
cb(null, true);
} else {
cb(new Error('Invalid file type. Only .ipa, .apk, and .app files are allowed.'));
}
}
}).single('file');
app.post('/api/projects', async (req, res) => {
try {
if (!req.session.username) {
return res.status(401).json({ success: false, error: 'User not authenticated' });
}
if (req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Only admin users can create projects' });
}
const { name } = req.body;
if (!name) {
return res.status(400).json({ success: false, error: 'Project name is required' });
}
const projectsFile = path.join(__dirname, 'data', 'projects.json');
let data = { projects: [] };
try {
if (fs.existsSync(projectsFile)) {
const fileContent = fs.readFileSync(projectsFile, 'utf8');
if (fileContent.trim()) {
data = JSON.parse(fileContent);
}
}
} catch (error) {
console.error('Error reading projects file:', error);
}
const newProject = {
id: Date.now().toString(),
name,
owner: req.session.username,
created: new Date().toISOString(),
versions: []
};
if (!Array.isArray(data.projects)) {
data.projects = [];
}
// Create project directories
const projectDir = path.join(__dirname, 'uploads', 'projects', name);
const iosDir = path.join(projectDir, 'ios');
const androidDir = path.join(projectDir, 'android');
const tvosDir = path.join(projectDir, 'tvos');
const androidtvDir = path.join(projectDir, 'androidtv');
try {
// Create all platform directories
if (!fs.existsSync(projectDir)) {
fs.mkdirSync(projectDir, { recursive: true, mode: 0o777 });
fs.mkdirSync(iosDir, { recursive: true, mode: 0o777 });
fs.mkdirSync(androidDir, { recursive: true, mode: 0o777 });
fs.mkdirSync(tvosDir, { recursive: true, mode: 0o777 });
fs.mkdirSync(androidtvDir, { recursive: true, mode: 0o777 });
}
// Add project to list
data.projects.push(newProject);
// Update projects.json file
fs.writeFileSync(projectsFile, JSON.stringify(data, null, 2), { mode: 0o666 });
res.status(201).json({ success: true, project: newProject });
} catch (error) {
console.error('Error creating project:', error);
res.status(500).json({
success: false,
error: `Failed to create project: ${error.message}. Please check directory permissions.`
});
}
} catch (error) {
console.error('Project creation error:', error);
res.status(500).json({
success: false,
error: 'Failed to create project: ' + error.message
});
}
});
app.delete('/api/projects/:projectId', async (req, res) => {
try {
if (!req.session.username) {
return res.status(401).json({ success: false, error: 'User not authenticated' });
}
if (req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Only admin users can delete projects' });
}
const { projectId } = req.params;
const projectsFile = './data/projects.json';
let data = JSON.parse(fs.readFileSync(projectsFile, 'utf8'));
const projectIndex = data.projects.findIndex(p => p.id === projectId);
if (projectIndex === -1) {
return res.status(404).json({ success: false, error: 'Project not found' });
}
const projectName = data.projects[projectIndex].name;
const projectDir = path.join(__dirname, 'uploads', 'projects', projectName);
if (fs.existsSync(projectDir)) {
fs.rmSync(projectDir, { recursive: true, force: true });
}
data.projects.splice(projectIndex, 1);
fs.writeFileSync(projectsFile, JSON.stringify(data, null, 2));
res.json({ success: true, message: 'Project deleted successfully' });
} catch (error) {
console.error('Delete error:', error);
res.status(500).json({ success: false, error: 'Failed to delete project' });
}
});
app.post('/api/upload', (req, res) => {
upload(req, res, function(err) {
// File upload validation errors should be bypassed for URL-only platforms
if (err && !(req.body.platform === 'ios' || req.body.platform === 'tvos')) {
console.error('Upload error:', err);
return res.status(400).json({
success: false,
error: err.message
});
}
try {
if (!req.session.username) {
return res.status(401).json({ success: false, error: 'User not authenticated' });
}
if (req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Only admin users can upload files' });
}
const { projectId, platform, version, notes, environment, url } = req.body;
if (!projectId || !platform || !version || !environment) {
return res.status(400).json({
success: false,
error: 'Missing required fields'
});
}
// Check that URL is provided for iOS/tvOS platforms
if ((platform === 'ios' || platform === 'tvos') && !url) {
return res.status(400).json({
success: false,
error: 'Public test URL is required for iOS and Apple TV platforms'
});
}
// Check that file is provided for other platforms
if (platform !== 'ios' && platform !== 'tvos' && !req.file) {
return res.status(400).json({
success: false,
error: 'App file is required for this platform'
});
}
const projectsFile = path.join(__dirname, 'data', 'projects.json');
let data = JSON.parse(fs.readFileSync(projectsFile, 'utf8'));
const project = data.projects.find(p => p.id === projectId);
if (!project) {
return res.status(404).json({
success: false,
error: 'Project not found'
});
}
// Version check - show error if same version and platform already exists
const existingVersion = project.versions?.find(v =>
v.version === version && v.platform === platform.toLowerCase()
);
if (existingVersion) {
return res.status(400).json({
success: false,
error: `Version ${version} already exists for ${platform}. Please use a different version number.`
});
}
let newVersion;
// Handle URL uploads for iOS and tvOS platforms
if (platform === 'ios' || platform === 'tvos') {
if (!url) {
return res.status(400).json({
success: false,
error: 'Public test URL is required for iOS and Apple TV platforms'
});
}
newVersion = {
id: Date.now().toString(),
platform: platform.toLowerCase(),
version: version || 'URL Only',
environment: environment || 'production',
notes: notes || '',
url: url,
uploadedBy: req.session.username,
uploadedAt: new Date().toISOString()
};
}
// Handle file uploads for other platforms
else {
const fileName = `${version}-${req.file.originalname}`;
const projectDir = path.join(__dirname, 'uploads', 'projects', project.name);
const platformDir = path.join(projectDir, platform.toLowerCase());
// Create directories
fs.mkdirSync(projectDir, { recursive: true });
fs.mkdirSync(platformDir, { recursive: true });
// Copy the file
const filePath = path.join(platformDir, fileName);
fs.copyFileSync(req.file.path, filePath);
fs.unlinkSync(req.file.path); // Delete temporary file
newVersion = {
id: Date.now().toString(),
platform: platform.toLowerCase(),
version,
environment,
notes,
file: fileName,
uploadedBy: req.session.username,
uploadedAt: new Date().toISOString()
};
}
if (!Array.isArray(project.versions)) {
project.versions = [];
}
project.versions.push(newVersion);
project.versions.sort((a, b) => new Date(b.uploadedAt) - new Date(a.uploadedAt));
fs.writeFileSync(projectsFile, JSON.stringify(data, null, 2));
res.json({
success: true,
version: newVersion
});
} catch (error) {
// In case of error, clean up the temporary file
if (req.file && req.file.path) {
fs.unlinkSync(req.file.path);
}
console.error('Upload error:', error);
res.status(500).json({
success: false,
error: 'Failed to upload file: ' + error.message
});
}
});
});
app.get('/api/projects', async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const startIndex = (page - 1) * limit;
const projectsFile = './data/projects.json';
if (!fs.existsSync(projectsFile)) {
return res.json({
projects: [],
totalPages: 0,
currentPage: page
});
}
const data = JSON.parse(fs.readFileSync(projectsFile, 'utf8'));
const projects = data.projects || [];
// Sort with most recent uploads at the top
projects.sort((a, b) => new Date(b.created) - new Date(a.created));
// Sort with most recent uploads at the top
const paginatedProjects = projects.slice(startIndex, startIndex + limit);
const totalPages = Math.ceil(projects.length / limit);
res.json({
projects: paginatedProjects,
totalPages,
currentPage: page
});
} catch (error) {
console.error('Error listing projects:', error);
res.status(500).json({ error: 'Failed to load projects' });
}
});
app.get('/api/download/:projectId/:versionId', (req, res) => {
try {
const { projectId, versionId } = req.params;
const projectsFile = './data/projects.json';
const fileContent = fs.readFileSync(projectsFile, 'utf8');
const data = JSON.parse(fileContent);
if (!data || !data.projects || !Array.isArray(data.projects)) {
return res.status(500).json({ error: 'Invalid data structure' });
}
const project = data.projects.find(p => p.id === projectId);
if (!project) {
return res.status(404).json({ error: 'Project not found' });
}
const version = project.versions.find(v => v.id === versionId);
if (!version) {
return res.status(404).json({ error: 'Version not found' });
}
// For iOS and Apple TV platforms with URL, redirect to the test URL
if ((version.platform === 'ios' || version.platform === 'tvos') && version.url) {
return res.redirect(version.url);
}
// For file-based platforms, serve the file
const filePath = path.join(__dirname, 'uploads', 'projects', project.name, version.platform, version.file);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found on disk' });
}
// Get file stats for content length
const stat = fs.statSync(filePath);
const fileSize = stat.size;
// Handle range requests for partial content
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = (end - start) + 1;
const file = fs.createReadStream(filePath, { start, end });
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${version.file}"`,
'Cache-Control': 'public, max-age=3600'
};
res.writeHead(206, head);
file.pipe(res);
} else {
// Stream the entire file with optimized settings
const head = {
'Content-Length': fileSize,
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${version.file}"`,
'Accept-Ranges': 'bytes',
'Cache-Control': 'public, max-age=3600'
};
res.writeHead(200, head);
// Use a larger highWaterMark for faster streaming
const stream = fs.createReadStream(filePath, {
highWaterMark: 64 * 1024 // 64KB chunks
});
// Handle stream errors
stream.on('error', (error) => {
console.error('Stream error:', error);
if (!res.headersSent) {
res.status(500).json({ error: 'Failed to stream file' });
}
});
stream.pipe(res);
}
} catch (error) {
console.error('Download error:', error);
if (!res.headersSent) {
res.status(500).json({ error: 'Failed to download file' });
}
}
});
app.delete('/api/projects/:projectId/versions/:versionId', async (req, res) => {
try {
if (!req.session.username) {
return res.status(401).json({ success: false, error: 'User not authenticated' });
}
if (req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Only admin users can delete versions' });
}
const { projectId, versionId } = req.params;
const projectsFile = path.join(__dirname, 'data', 'projects.json');
let data = JSON.parse(fs.readFileSync(projectsFile, 'utf8'));
const project = data.projects.find(p => p.id === projectId);
if (!project) {
return res.status(404).json({ success: false, error: 'Project not found' });
}
const versionIndex = project.versions.findIndex(v => v.id === versionId);
if (versionIndex === -1) {
return res.status(404).json({ success: false, error: 'Version not found' });
}
const version = project.versions[versionIndex];
const filePath = path.join(__dirname, 'uploads', 'projects', project.name, version.platform, version.file);
// Only delete the file, not the folder
if (fs.existsSync(filePath)) {
try {
fs.unlinkSync(filePath);
} catch (fileError) {
console.error('File deletion error:', fileError);
}
}
// Remove version from the project
project.versions.splice(versionIndex, 1);
// Update the project
fs.writeFileSync(projectsFile, JSON.stringify(data, null, 2));
res.status(200).json({ success: true, message: 'Version deleted successfully' });
} catch (error) {
console.error('Delete version error:', error);
res.status(500).json({ success: false, error: 'Failed to delete version: ' + error.message });
}
});
app.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
// Read users from file
const usersFile = path.join(__dirname, 'data', 'users.json');
if (!fs.existsSync(usersFile)) {
return res.status(500).json({ success: false, message: 'User database not found' });
}
const userData = JSON.parse(fs.readFileSync(usersFile, 'utf8'));
const user = userData.users.find(u => u.username === username && u.password === password);
if (!user) {
return res.status(401).json({
success: false,
message: 'Invalid username or password'
});
}
// Check if user is approved
if (!user.approved) {
return res.status(403).json({
success: false,
message: 'Your account is pending approval by an administrator'
});
}
// Set session data
req.session.username = user.username;
req.session.userId = user.id;
req.session.role = user.role;
req.session.isAuthenticated = true;
req.session.save((err) => {
if (err) {
console.error('Session save error:', err);
return res.status(500).json({ success: false, message: 'Login failed' });
}
res.json({
success: true,
user: {
username: user.username,
displayName: user.username,
role: user.role
}
});
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ success: false, message: 'Login failed' });
}
});
// Register new user
app.post('/api/register', async (req, res) => {
try {
const { username, password, email, fullName } = req.body;
// Validate input
if (!username || !password) {
return res.status(400).json({ success: false, error: 'Username and password are required' });
}
// Read current users
const usersFile = path.join(__dirname, 'data', 'users.json');
let userData = { users: [] };
if (fs.existsSync(usersFile)) {
userData = JSON.parse(fs.readFileSync(usersFile, 'utf8'));
}
// Check if user already exists
if (userData.users.some(u => u.username === username)) {
return res.status(400).json({ success: false, error: 'Username already exists' });
}
// Create new user object
const newUser = {
id: Date.now().toString(),
username,
password,
email: email || '',
fullName: fullName || '',
role: 'user',
approved: false,
created: new Date().toISOString()
};
// Add user to array
userData.users.push(newUser);
// Save to file
fs.writeFileSync(usersFile, JSON.stringify(userData, null, 2));
res.status(201).json({
success: true,
message: 'Registration successful. Your account is pending approval by an administrator.'
});
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({ success: false, error: 'Registration failed' });
}
});
// Admin-only API: Get all users
app.get('/api/users', async (req, res) => {
try {
// Check if user is admin
if (!req.session.username || req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Unauthorized' });
}
// Read users file
const usersFile = path.join(__dirname, 'data', 'users.json');
if (!fs.existsSync(usersFile)) {
return res.status(200).json({ users: [] });
}
const userData = JSON.parse(fs.readFileSync(usersFile, 'utf8'));
// Remove passwords before sending
const safeUsers = userData.users.map(({ password, ...user }) => user);
res.json({ users: safeUsers });
} catch (error) {
console.error('Get users error:', error);
res.status(500).json({ success: false, error: 'Failed to get users' });
}
});
// Admin-only API: Approve or reject user
app.put('/api/users/:userId/approval', async (req, res) => {
try {
// Check if user is admin
if (!req.session.username || req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Unauthorized' });
}
const { userId } = req.params;
const { approved } = req.body;
if (approved === undefined) {
return res.status(400).json({ success: false, error: 'Approval status required' });
}
// Read users file
const usersFile = path.join(__dirname, 'data', 'users.json');
const userData = JSON.parse(fs.readFileSync(usersFile, 'utf8'));
// Find user
const userIndex = userData.users.findIndex(u => u.id === userId);
if (userIndex === -1) {
return res.status(404).json({ success: false, error: 'User not found' });
}
// Prevent modifying own account
if (userData.users[userIndex].username === req.session.username) {
return res.status(403).json({ success: false, error: 'Cannot modify your own account' });
}
// Update approval status
userData.users[userIndex].approved = approved;
// Save to file
fs.writeFileSync(usersFile, JSON.stringify(userData, null, 2));
res.json({
success: true,
message: `User ${approved ? 'approved' : 'rejected'} successfully`
});
} catch (error) {
console.error('User approval error:', error);
res.status(500).json({ success: false, error: 'Failed to update user approval status' });
}
});
// Admin-only API: Change user role to admin
app.put('/api/users/:userId/role', async (req, res) => {
try {
// Check if user is admin
if (!req.session.username || req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Unauthorized' });
}
const { userId } = req.params;
const { role } = req.body;
if (!role || !['admin', 'user'].includes(role)) {
return res.status(400).json({ success: false, error: 'Valid role required (admin or user)' });
}
// Read users file
const usersFile = path.join(__dirname, 'data', 'users.json');
const userData = JSON.parse(fs.readFileSync(usersFile, 'utf8'));
// Find user
const userIndex = userData.users.findIndex(u => u.id === userId);
if (userIndex === -1) {
return res.status(404).json({ success: false, error: 'User not found' });
}
// Prevent modifying own account
if (userData.users[userIndex].username === req.session.username) {
return res.status(403).json({ success: false, error: 'Cannot modify your own account' });
}
// Update role
userData.users[userIndex].role = role;
// Save to file
fs.writeFileSync(usersFile, JSON.stringify(userData, null, 2));
res.json({
success: true,
message: `User role updated to ${role} successfully`
});
} catch (error) {
console.error('User role update error:', error);
res.status(500).json({ success: false, error: 'Failed to update user role' });
}
});
// Admin-only API: Delete user
app.delete('/api/users/:userId', async (req, res) => {
try {
// Check if user is admin
if (!req.session.username || req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Unauthorized' });
}
const { userId } = req.params;
// Read users file
const usersFile = path.join(__dirname, 'data', 'users.json');
const userData = JSON.parse(fs.readFileSync(usersFile, 'utf8'));
// Find user
const userIndex = userData.users.findIndex(u => u.id === userId);
if (userIndex === -1) {
return res.status(404).json({ success: false, error: 'User not found' });
}
// Prevent deleting own account
if (userData.users[userIndex].username === req.session.username) {
return res.status(403).json({ success: false, error: 'Cannot delete your own account' });
}
// Remove user
userData.users.splice(userIndex, 1);
// Save to file
fs.writeFileSync(usersFile, JSON.stringify(userData, null, 2));
res.json({
success: true,
message: 'User deleted successfully'
});
} catch (error) {
console.error('User deletion error:', error);
res.status(500).json({ success: false, error: 'Failed to delete user' });
}
});
// Check admin status
app.get('/api/check-admin', (req, res) => {
if (req.session && req.session.username && req.session.role === 'admin') {
res.json({
isAdmin: true,
username: req.session.username
});
} else {
res.json({
isAdmin: false
});
}
});
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error('Logout error:', err);
return res.status(500).json({ success: false, message: 'Logout failed' });
}
res.json({ success: true, message: 'Logged out successfully' });
});
});
app.get('/api/check-session', (req, res) => {
if (req.session && req.session.username) {
res.json({
isLoggedIn: true,
username: req.session.username,
userRole: req.session.role
});
} else {
res.json({
isLoggedIn: false
});
}
});
// Version update endpoint
app.put('/api/projects/:projectId/versions/:versionId', isAuthenticated, async (req, res) => {
try {
if (req.session.role !== 'admin') {
return res.status(403).json({ success: false, error: 'Admin access required' });
}
const { projectId, versionId } = req.params;
const { version, environment, notes, url, platform } = req.body;
const projectsFile = './data/projects.json';
if (!fs.existsSync(projectsFile)) {
return res.status(404).json({ success: false, error: 'Projects file not found' });
}
const data = JSON.parse(fs.readFileSync(projectsFile, 'utf8'));
const projectIndex = data.projects.findIndex(p => p.id === projectId);
if (projectIndex === -1) {
return res.status(404).json({ success: false, error: 'Project not found' });
}
const project = data.projects[projectIndex];
const versionIndex = project.versions.findIndex(v => v.id === versionId);
if (versionIndex === -1) {
return res.status(404).json({ success: false, error: 'Version not found' });
}
// Update the version fields
const versionToUpdate = project.versions[versionIndex];
versionToUpdate.version = version;
versionToUpdate.environment = environment;
versionToUpdate.notes = notes;
versionToUpdate.url = url;
versionToUpdate.platform = platform;
versionToUpdate.updatedAt = new Date().toISOString();
// Write the updated data back to the file
fs.writeFileSync(projectsFile, JSON.stringify(data, null, 2));
res.json({
success: true,
version: versionToUpdate
});
} catch (error) {
console.error('Version update error:', error);
res.status(500).json({
success: false,
error: 'Failed to update version: ' + error.message
});
}
});
// GET a specific version
app.get('/api/projects/:projectId/versions/:versionId', isAuthenticated, async (req, res) => {
try {
const { projectId, versionId } = req.params;
const projectsFile = './data/projects.json';
if (!fs.existsSync(projectsFile)) {
return res.status(404).json({ success: false, error: 'Projects file not found' });
}
const data = JSON.parse(fs.readFileSync(projectsFile, 'utf8'));
const project = data.projects.find(p => p.id === projectId);
if (!project) {
return res.status(404).json({ success: false, error: 'Project not found' });
}
const version = project.versions.find(v => v.id === versionId);
if (!version) {
return res.status(404).json({ success: false, error: 'Version not found' });
}
res.json({
success: true,
version
});
} catch (error) {
console.error('Get version error:', error);
res.status(500).json({
success: false,
error: 'Failed to get version: ' + error.message
});
}
});
// Get port from config
app.listen(config.server.port, () => {
console.log(`Server running on ${config.urls.base()}`);
console.log(`Local IP address: ${config.server.host}`);
});