-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.js
715 lines (581 loc) · 18 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
const express = require('express');
const passport = require('passport');
const GitHubStrategy = require('passport-github2').Strategy;
const mongoose = require('mongoose');
const cors = require('cors');
const axios = require('axios')
const { exec } = require('child_process');
const path = require('path');
const rateLimit = require('express-rate-limit');
const session = require('express-session');
const User = require('./models/userModel');
const Project = require('./models/projectModel');
const GoogleUser = require('./models/googleModel');
const { count } = require('console');
// Initialize Express
const app = express();
const port = 4000;
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
next()
})
app.use(cors())
app.use(express.json());
mongoose.connect('mongodb+srv://precogsai:[email protected]', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('error', console.error);
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
});
// Configure session management
app.use(
session({ secret: 'secrect-key-for----secion', resave: false, saveUninitialized: true })
);
// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());
// GitHub OAuth Configuration
passport.use(
new GitHubStrategy(
{
clientID: 'ca94a374c4d560c632e2',
clientSecret: '34e2ccd44b932c58155d64c50f5e7a377179d9c8',
callbackURL: 'http://localhost:4000/auth/github/callback',
},
(accessToken, refreshToken, profile, done) => {
console.log(accessToken)
// Store user data in MongoDB
User.findOneAndUpdate(
{ githubId: profile.id },
{ username: profile.username, accessToken },
{ upsert: true, new: true }
)
.then(user => {
if (!user) {
// If user not found, you might want to create a new user here
// You can return done(null, newUser) in that case
}
done(null, user);
})
.catch(err => {
console.error(err);
done(err);
});
}
)
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id)
.then(user => {
done(null, user);
})
.catch(err => {
done(err, null);
});
});
// Define routes for authentication and dashboard
app.get('/auth/github', passport.authenticate('github', { scope: ['user:email', 'repo'] }));
app.get(
'/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/' }),
(req, res) => {
// res.redirect('/dashboard');
res.json({
success: true,
message: "User logged in successfully",
user: req.user,
});
}
);
app.get('/dashboard', (req, res) => {
res.send('Hello World');
});
// github repo with access
app.get('/access/githubrepo', async (req, res) => {
try {
// const githubAccessToken = "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";
const githubAccessToken = "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";
// Function to fetch all pages of repositories recursively
async function fetchRepositories(url, repositories = []) {
try {
const response = await axios.get(url, {
headers: {
Authorization: `token ${githubAccessToken}`,
},
params: {
visibility: 'all',
per_page: 50,
},
});
const pageRepositories = response.data;
// const projects=await Project.find();
// project of auth user
const projects = await Project.find({ owner: "6593c7cb95a0c6626594f131" });
// Add the 'access' property to each repository with the value 'false'
const repositoriesWithAccess = pageRepositories.map(repo => (
{
access: projects.some(project => project.name.toLowerCase() === repo.name.toLowerCase()),
...repo,
}
));
repositories = repositories.concat(repositoriesWithAccess);
// Check if there are more pages
const nextPageLink = response.headers.link;
if (nextPageLink && nextPageLink.includes('rel="next"')) {
const nextPageUrl = nextPageLink
.split(', ')
.find(link => link.includes('rel="next"'))
.split(';')[0]
.slice(1, -1);
return fetchRepositories(nextPageUrl, repositories);
}
return repositories;
} catch (error) {
throw error;
}
}
const repositories = await fetchRepositories('https://api.github.com/user/repos');
res.json({
success: true,
message: "Repositories fetched successfully",
Total_Repositories: repositories.length,
repositories: repositories,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
// get all user
app.get('/getusers', async (req, res) => {
try {
const users = await User.find().populate('projects');
res.json({
success: true,
message: "Users fetched successfully",
users: users,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
// get all project of a user
app.get('/userprojects', async (req, res) => {
try {
const userId = "6593c7cb95a0c6626594f131";
// Retrieve user and populate the projects field
const user = await User.findById(userId).populate('projects');
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({
success: true,
message: "User projects retrieved successfully",
Total: user.projects.length,
userProjects: user.projects,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
// create multiple project in one go
app.post('/createproject', async (req, res) => {
try {
const projectsData = req.body;
const userId = "6593c7cb95a0c6626594f131";
console.log(req.body)
const savedProjects = []
// Use Promise.all to concurrently save multiple projects
await Promise.all(projectsData.map(async (projectData) => {
projectData.owner = userId;
const newProject = new Project(projectData);
const savedProject = await newProject.save();
savedProjects.push(savedProject);
}));
// Update the user's projects array
const user = await User.findByIdAndUpdate(
userId,
{ $push: { projects: { $each: savedProjects } } },
{ new: true }
);
res.json({
success: true,
message: "Projects created successfully",
projects: savedProjects,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
// get all projects
app.get('/getprojects', async (req, res) => {
try {
const projects = await Project.find();
res.json({
success: true,
message: "Projects fetched successfully",
projects: projects,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
// get project by id
app.get('/getproject/:projectId', async (req, res) => {
try {
const projectId = req.params.projectId;
// console.log(projectId)
const project = await Project.findById(projectId);
// const project = await Project.findOne({ id: projectId })
// .populate('owner');
if (!project) {
return res.status(404).json({ error: 'Project not found' });
}
res.json({
success: true,
message: "Project retrieved successfully",
project: project,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
//get overview of project
app.get('/getoverview/:projectId', async (req, res) => {
try {
const projectId = req.params.projectId;
// console.log(projectId)
const project = await Project.findById(projectId);
// const project = await Project.findOne({ id: projectId })
// .populate('owner');
if (!project) {
return res.status(404).json({ error: 'Project not found' });
}
res.json({
success: true,
message: "Project retrieved successfully",
overview: {
_id: project._id,
name: project.name,
full_name: project.full_name,
githubLink: project.githubLink,
html_url: project.html_url,
id: project.id,
language: project.language,
owner: project.owner,
createdAt: project.createdAt,
updatedAt: project.updatedAt,
project_info: {
environment: project.environment,
projectScope: project.projectScope,
businessPriority: project.businessPriority,
projectType: project.projectType,
},
}
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
//update project by id
app.put('/updateproject/:projectId', async (req, res) => {
try {
const projectId = req.params.projectId;
const projectData = req.body;
const updatedProject = await Project.findByIdAndUpdate(
projectId,
projectData,
{ new: true }
);
if (!updatedProject) {
return res.status(404).json({ error: 'Project not found' });
}
res.json({
success: true,
message: "Project updated successfully",
project: updatedProject,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
app.put('/update/:projectId', async (req, res) => {
const projectId = req.params.projectId;
const projectData = req.body;
console.log(projectData)
const updatedProject = await Project.findByIdAndUpdate(
projectId,
projectData,
{ new: true }
);
if (!updatedProject) {
return res.status(404).json({ error: 'Project not found' });
}
res.status(200).json({
success: true,
message: "Project updated successfully",
project: updatedProject,
});
});
// app.put('/update/:projectId', async (req, res) => {
// const projectId = req.params.projectId;
// try {
// const project = await Project.findById(projectId);
// if (!project) {
// return res.status(404).json({ error: 'Project not found' });
// }
// const { key, value } = req.body;
// if (key && Object.keys(project.overview).includes(key)) {
// project.overview[key] = value;
// const updatedProject = await project.save();
// res.status(200).json({
// message: `Updated ${key} to ${value}`,
// overview: updatedProject.overview,
// success: true,
// });
// } else {
// res.status(400).json({ error: 'Invalid key or value' });
// }
// } catch (error) {
// console.error(error);
// res.status(500).json({ error: 'Internal Server Error' });
// }
// });
// Delete a project and remove it from user projects
app.delete('/deleteproject/:projectId', async (req, res) => {
try {
const projectId = req.params.projectId;
// Find the project and get the associated user ID
const project = await Project.findById(projectId);
if (!project) {
return res.status(404).json({ error: 'Project not found' });
}
const userId = project.owner;
// Delete the project
const deletedProject = await Project.findByIdAndRemove(projectId);
if (!deletedProject) {
return res.status(404).json({ error: 'Project not found' });
}
// Remove the project from the user's projects array
const updatedUser = await User.findByIdAndUpdate(
userId,
{ $pull: { projects: projectId } },
{ new: true }
);
res.json({
success: true,
message: "Project deleted successfully and removed from user's projects",
deletedProject: deletedProject,
// user: updatedUser,
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
//get user all project status
app.get('/get-dashboard-activity', async (req, res) => {
const userId = "6593c7cb95a0c6626594f131";
try {
const statusCounts = await Project.aggregate([
{
$match: {
owner: new mongoose.Types.ObjectId(userId),
},
},
{
$group: {
_id: '$issue_status',
count: { $sum: 1 },
},
},
]);
const result = {
open: 0,
fixed: 0,
ignored: 0,
};
statusCounts.forEach((statusCount) => {
result[statusCount._id] = statusCount.count;
});
const total_issues = result.open + result.fixed + result.ignored;
// const total_projects = await Project.countDocuments({ owner: userId });
const total_projects = await Project.find({ owner: userId });
const total_projects_count = total_projects.length;
//TODO: change total_scans to actual number of scans
const total_scans = 5;
//TODO: change LOC to actual number of lines of code
const LineofCode = 4356;
res.status(200).json({
success: true,
message: "Dashboard Activity fetched successfully",
dashboard_activity: [
{ TotalScans: total_scans },
{ Projects: total_projects_count },
{ TotalIssues: total_issues },
{ OpenIssues: result.open },
{ FixedIssues: result.fixed },
{ IgnoredIssues: result.ignored },
{ LineOfCode: LineofCode },
]
});
} catch (error) {
// console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
//CHILD PROCESS FOR PYTHON SCRIPT
app.post('/scan-code', (req, res) => {
const { code } = req.body;
// console.log(req.body)
// Execute Python script as a child process
const pythonScript = 'dummy_vuln_model.py';
const command = `python ${pythonScript} "${code}"`;
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return res.status(500).json({ error: 'Internal Server Error' });
}
if (stderr) {
console.error(`Error: ${stderr}`);
return res.status(400).json({ error: 'Bad Request' });
}
const vulnerabilities = stdout.trim()
res.status(200).json({
success: true,
message: 'Code scanned successfully',
vulnerabilities: vulnerabilities,
});
});
});
app.get('/', (req, res) => {
res.status(200).json({
success: true,
message: 'Welcome to Precog',
});
});
app.use(express.static(path.join(__dirname, 'public')));
// Create a rate limiter middleware with a limit of 100 requests per minute
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 10, // 100 requests per minute
handler: (req, res) => {
// Redirect to the "/tomanyreq" route when the limit is exceeded
res.sendFile(path.join(__dirname, 'public', 'index.html'));
},
});
// Apply the rate limiter to all routes that start with /api
app.use('/api', limiter);
app.get('/api/v1', (req, res) => {
res.status(200).json({
success: true,
message: 'Rate limit testing',
});
});
// Serve static files (including the HTML file) from the "public" directory
// app.use(express.static(path.join(__dirname, 'public')));
// Define your API routes here
// // Define a route for handling too many requests
// app.get('/rate-limit-exceeded', (req, res) => {
// res.sendFile(path.join(__dirname, 'public', 'index.html'));
// });
// // search project
// const GITHUB_API_BASE_URL = 'https://api.github.com';
// app.get('/searchprojects', async (req, res) => {
// try {
// const accessToken = "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";
// const { query } = req.query;
// if (!query) {
// return res.status(400).json({ error: 'Missing query parameter' });
// }
// if (!accessToken) {
// return res.status(401).json({ error: 'Access token is required' });
// }
// const headers = {
// Authorization: `token ${accessToken}`,
// };
// const searchResponse = await axios.get(`${GITHUB_API_BASE_URL}/search/repositories`, {
// params: {
// q: query,
// per_page: 10, // Adjust the number of results per page as needed
// },
// headers,
// });
// const projects = searchResponse.data.items.map((item) => ({
// id: item.id,
// name: item.name,
// description: item.description,
// url: item.html_url,
// owner: item.owner.login,
// }));
// res.json({
// success: true,
// message: 'Projects retrieved successfully',
// projects: projects,
// });
// } catch (error) {
// console.error(error);
// res.status(error.response?.status || 500).json({ error: 'Internal server error' });
// }
// });
// // signin with google
// app.post('/auth/google', async (req, res) => {
// const { name, email, photo, role, _id } = req.body;
// if (!name || !email || !photo || !role || !_id) {
// return res.status(400).json({ error: "All fields are required" })
// }
// let user = await GoogleUser.findById(_id);
// if (user) {
// return res.status(200).json({
// success: true,
// message: `Welcome back ${user.name}`,
// })
// }
// const newUser = new GoogleUser({
// _id,
// name,
// email,
// photo,
// role,
// });
// await newUser.save();
// res.status(200).json({
// success: true,
// message: `Welcome ${newUser.name}`,
// })
// });
// // get user by id
// app.get('/getuser/:userId', async (req, res) => {
// try {
// const userId = req.params.userId;
// const user = await GoogleUser.findById(userId);
// if (!user) {
// return res.status(404).json({ error: "User not found" })
// }
// res.json({
// success: true,
// message: "User retrieved successfully",
// user: user,
// })
// } catch (error) {
// console.error(error);
// res.status(500).json({ error: "Internal server error" })
// }
// });
// Start the server
app.listen(port, () => {
console.log(`Server is running on port http://localhost:${port}`);
});