-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
1904 lines (1563 loc) · 70.3 KB
/
database.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
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 path = require('path');
const sql = require("mssql");
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
const session = require('express-session');
const mysql = require("mysql");
const MSSQLStore = require('connect-mssql')(session);
const app = express();
const PORT = 9000;
const multer = require('multer');
const fileUpload = require('express-fileupload');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
// Set up static files serving
app.use(express.static(path.join(__dirname, 'views')));
// Now you can access the 'views' directory from the browser
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'ads'
});
const usersRoutes = require('./routes/users');
// Mount the user routes at the '/user' base path
app.use('/users', usersRoutes);
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL:', err);
} else {
console.log('Connected to MySQL database');
}
});
// Routes
app.get("/", function (req, res) {
const username = req.cookies.username;
const logged = req.cookies.logged;
const teacher = req.cookies.teacher;
const developer = req.cookies.developer;
const admin = req.cookies.admin;
if (username && logged === 'true') {
// If the user is logged in, redirect to the user panel page
res.redirect(`/student user/userpanel.html?username=${username}`);
} else if (teacher && logged === 'true') {
// If the user is a teacher, redirect to the teacher page
res.redirect(`/teacher and MU.html?username=${username}`);
} else if (developer && logged === 'true') {
// If the user is a teacher, redirect to the teacher page
res.redirect(`/teacher and MU.html?username=${username}`);
} else {
// If the user is not logged in, serve the index.html page
res.sendFile(path.join(__dirname, "index.html"));
}
});
app.post("/student", (req, res) => {
const username = req.body.username;
const password = req.body.password;
const query = "SELECT * FROM student WHERE username = ? AND password = ?";
const request = new sql.Request();
request.input('username', sql.NVarChar, username);
request.input('password', sql.NVarChar, password);
connection.query(query, [username, password], (error, results) => {
if (error) {
console.error("Error occurred during login:", error);
res.status(500).send("Internal server error");
} else if (results.length > 0) {
// Set cookies for username and login status
res.cookie('username', username, { maxAge: 3 * 24 * 60 * 60 * 1000 });
res.cookie('student', 'student', { maxAge: 3 * 24 * 60 * 60 * 1000 });
res.cookie('logged', 'true', { maxAge: 3 * 24 * 60 * 60 * 1000 });
// Set session variable
req.cookies.user = username;
// Redirect to the user panel page
res.redirect("/student user/userpanel.html");
} else {
// Render the login page with an error message
res.redirect("/student/student login.html?error=Invalid Username or Password");
}
});
});
app.get("/logout", (req, res) => {
// Clear cookies and session and redirect to index.html
res.clearCookie('username');
res.clearCookie('logged');
res.clearCookie('student');
res.clearCookie('teacher');
res.clearCookie('developer');
res.clearCookie('admin');
res.redirect("/index.html");
});
app.get("/student/userpanel", (req, res) => {
if (req.session.user) {
res.redirect("student user/userpanel.html");
} else {
res.redirect("/login");
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
/*------------------------------------student register ---------------------------------*/
app.post('/register', (req, res) => {
try {
const {username, email, password} = req.body;
// SQL query with default values for columns not specified in the registration form
const query = 'INSERT INTO student (username, email, password) VALUES (?, ?, ?)';
connection.query(query, [username, email, password], (error, results) => {
if (error) {
console.error("Error occurred during registration:", error);
res.redirect('/student/student register.html');
} else {
// Check if the query was successful
if (results.affectedRows > 0) {
// Assuming `student` is a property in the results object
const teacher = results.teacher; // Adjust this line according to your query results
res.cookie('username', username);
res.cookie('student', 'student');
res.cookie('logged', 'true'); // Add this line to set the 'logged' cookie
// Redirect to the user panel page
req.cookies.user = username;
// Redirect to the user panel page
res.redirect('/student user/userpanel.html');
} else {
res.redirect('/teacher/teacher register.html');
}
}
});
} catch (error) {
console.error(error);
res.redirect('/teacher/teacher register.html');
}
});
app.get('/student/userpanel.html', (req, res) => {
if (req.loggedInUser) {
res.sendFile(path.join(__dirname, 'student user/userpanel.html'));
} else {
res.redirect('/login');
}
});
/*------------------------------------student register ---------------------------------*/
/*------------------------------------teacher login ---------------------------------*/
app.post("/log", (req, res) => {
const username = req.body.username;
const password = req.body.password;
const query = "SELECT * FROM teacher WHERE username = ? AND password = ?"; const request = new sql.Request();
request.input('username', sql.NVarChar, username);
request.input('password', sql.NVarChar, password);
connection.query(query, [username, password], (error, results) => {
if (error) {
console.error("Error occurred during login:", error);
res.redirect("/");
} else if (results.length > 0) {
// Set cookies for username, teacher, and logged status
res.cookie('username', username);
res.cookie('teacher', 'teacher');
res.cookie('logged', 'true'); // Add this line to set the 'logged' cookie
// Redirect to the user panel page
req.cookies.user = username;
res.redirect(`/student user/userpanel.html?username=${username}`);
} else {
res.redirect("/teacher/teacher login.html?error=Invalid Username or Password");
}
});
});
/*------------------------------------teacher login ---------------------------------*/
/*------------------------------------teacher register ---------------------------------*/
app.post('/go', (req, res) => {
try {
const {username, email, password, teacher, university, college } = req.body;
// SQL query with default values for columns not specified in the registration form
const query = 'INSERT INTO teacher (username, email, password, teacher, university, college) VALUES ( ?, ?, ?, ?, ?, ?)';
connection.query(query, [username, email, password, teacher, university, college], (error, results) => {
if (error) {
console.error("Error occurred during registration:", error);
res.redirect('/student/student register.html');
} else {
// Check if the query was successful
if (results.affectedRows > 0) {
// Assuming `student` is a property in the results object
const teacher = results.teacher; // Adjust this line according to your query results
res.cookie('username', username);
res.cookie('teacher', 'teacher');
res.cookie('logged', 'true'); // Add this line to set the 'logged' cookie
// Redirect to the user panel page
req.cookies.user = username;
// Redirect to the user panel page
res.redirect('/student user/userpanel.html');
} else {
res.redirect('/teacher/teacher register.html');
}
}
});
} catch (error) {
console.error(error);
res.redirect('/teacher/teacher register.html');
}
});
app.get("/student/userpanel.html", (req, res) => {
if (req.loggedInUser) {
res.sendFile(path.join(__dirname, "student user/userpanel.html"));
} else {
res.redirect("/login");
}
});
/*------------------------------------teacher register ---------------------------------*/
/*------------------------------------developer login ---------------------------------*/
app.post("/MU", (req, res) => {
const username = req.body.username;
const password = req.body.password;
const query = "SELECT * FROM university WHERE username = ? AND password = ?"; const request = new sql.Request();
request.input('developer', sql.NVarChar, username);
request.input('password', sql.NVarChar, password);
connection.query(query, [username, password], (error, results) => {
if (error) {
console.error("Error occurred during login:", error);
res.redirect("/");
} else if (results.length > 0) {
// Set cookies for username, teacher, and logged status
res.cookie('username', username);
res.cookie('developer', 'developer');
res.cookie('logged', 'true'); // Add this line to set the 'logged' cookie
// Redirect to the user panel page
req.cookies.user = username;
res.redirect(`/student user/userpanel.html?username=${username}`);
} else {
res.redirect("/teacher/teacher login.html?error=Invalid Username or Password");
}
});
});
/*------------------------------------developer login ---------------------------------*/
/*------------------------------------developer register ---------------------------------*/
app.post('/MUR', (req, res) => {
try {
const { username, email, password} = req.body;
// SQL query with default values for columns not specified in the registration form
const query = 'INSERT INTO university (username, email, password) VALUES (?, ?, ?)';
// Assuming `--` is the default value for the teacher column
connection.query(query, [username, email, password], (error, results) => {
if (error) {
console.error("Error occurred during registration:", error);
res.redirect('/student/student register.html');
} else {
// Check if the query was successful
if (results.affectedRows > 0) {
// Assuming `student` is a property in the results object
const developer = results.developer; // Adjust this line according to your query results
res.cookie('username', username);
res.cookie('developer', 'developer');
res.cookie('logged', 'true'); // Add this line to set the 'logged' cookie
// Redirect to the user panel page
req.cookies.user = username;
// Redirect to the user panel page
res.redirect('/student user/userpanel.html');
} else {
res.redirect('/teacher/teacher register.html');
}
}
});
} catch (error) {
console.error(error);
res.redirect('/teacher/teacher register.html');
}
});
app.get("/student/userpanel.html", (req, res) => {
if (req.loggedInUser) {
res.sendFile(path.join(__dirname, "student user/userpanel.html"));
} else {
res.redirect("/login");
}
});
/*------------------------------------developer register ---------------------------------*/
/*------------------------------------file or folder upload---------------------------------*/
// database.js
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname));
app.use(express.json());
app.post("/upload", upload.array("files"), (req, res) => {
const files = req.files;
const projectName = req.body.projectName;
const inputUsername = req.body.username;
const summary = req.body.summary;
const front = req.body.front;
const back = req.body.back;
if (!files || files.length === 0 || !projectName) {
return res.status(400).send("Please provide a project name and select files to upload.");
}
// Check if the input username matches the one stored in cookies
const storedUsername = req.cookies.username;
if (inputUsername !== storedUsername) {
return res.status(401).send("Invalid username. Please log in with the correct username.");
}
let filesUploaded = 0;
// ...
files.forEach((file, index, array) => {
const filename = file.originalname;
const mimeType = file.mimetype;
const fileData = file.buffer;
const query = "INSERT INTO file (filename, mime_type, data, project_name, username, summary, front, back) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
connection.query(query, [filename, mimeType, fileData, projectName, inputUsername, summary, front, back], (err, result) => {
if (err) {
console.error("Error uploading file: ", err);
} else {
filesUploaded++;
if (filesUploaded === array.length) {
// All files have been uploaded
res.status(200).send("Files uploaded successfully");
}
}
});
});
});
// ...
app.post("/project", upload.array("files"), (req, res) => {
const files = req.files;
const projectName = req.body.projectName;
const inputUsername = req.body.username;
const summary = req.body.summary;
const front = req.body.front;
const back = req.body.back;
if (!files || files.length === 0 || !projectName) {
return res.status(400).send("Please provide a project name and select files to upload.");
}
// Check if the input username matches the one stored in cookies
const storedUsername = req.cookies.username;
if (inputUsername !== storedUsername) {
return res.status(401).send("Invalid username. Please log in with the correct username.");
}
let filesUploaded = 0;
files.forEach((file, index, array) => {
const filename = file.originalname;
const mimeType = file.mimetype;
const fileData = file.buffer;
const query = "INSERT INTO project (filename, mime_type, data, project_name, username, summary, front, back) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
connection.query(query, [filename, mimeType, fileData, projectName, inputUsername, summary, front, back], (err, result) => {
if (err) {
console.error("Error uploading file: ", err);
} else {
filesUploaded++;
if (filesUploaded === array.length) {
// All files have been uploaded
res.status(200).send("Files uploaded successfully");
}
}
});
});
});
app.get("/status", (req, res) => {
const query = "SELECT filename, project_name, summary FROM file";
connection.query(query, (err, results) => {
if (err) {
console.error("Error fetching data from database: ", err);
res.status(500).send("Internal Server Error");
} else {
res.render("status", { files: results });
}
});
});
// Assuming you have Express set up and your EJS view engine configured
// Update the route handler
app.set('views', path.join(__dirname, 'views'));
// Set the 'public' directory for static files
app.use(express.static(path.join(__dirname, 'public')));
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Define a route to fetch data from the 'student' table
app.get('/status', async (req, res) => {
try {
// Connect to MSSQL using dbConfig
await sql.connect(dbConfig);
// Query the database
const result = await sql.query('SELECT * FROM student');
// Render the 'status.ejs' page and pass the query results
res.render('status', { data: result.recordset, title: 'File Status' });
} catch (err) {
console.error('Error executing MSSQL query:', err);
res.status(500).send('Internal Server Error');
} finally {
// Close the MSSQL connection
sql.close();
}
});
// Serve the status.html file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'status.html'));
});
/*------------------------------------admin_student login---------------------------------*/
app.post("/admin", (req, res) => {
const username = req.body.username;
const password = req.body.password;
const query = "SELECT * FROM admin WHERE username = ? AND password = ?";
connection.query(query, [username, password], (error, results) => {
if (error) {
console.error("Error occurred during login:", error);
res.status(500).send("Internal server error");
} else if (results.length > 0) {
// Set cookies for username and login status
res.cookie('admin', username);
res.cookie('logged', 'true');
// Set session variable (Note: Cookies are accessed through req.cookies, not req.cookies.user)
res.redirect("/admin/admin_home.html");
} else {
// Render the login page with an error message
res.redirect("/admin.html?error=Invalid Username or Password");
}
});
});
/*------------------------------------admin_student login---------------------------------*/
/*------------------------------------student fetch data---------------------------------*/
app.get('/student', (req, res) => {
try {
// Query the MySQL database
connection.query('SELECT * FROM student', (error, results, fields) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
// Render the 'student.ejs' page and pass the query results
res.render('student', { data: results, title: 'File Status' });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
// Handle other routes...
// Serve the student.html file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'student.html'));
});
/*------------------------------------student fetch data---------------------------------*/
/*------------------------------------teacher fetch data---------------------------------*/
app.get('/teacher', (req, res) => {
try {
// Query the MySQL database
connection.query('SELECT * FROM teacher', (error, results, fields) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
// Render the 'student.ejs' page and pass the query results
res.render('teacher', { data: results, title: 'File Status' });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
// Handle other routes...
// Serve the student.html file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'teacher.html'));
});
/*------------------------------------teacher fetch data---------------------------------*/
/*------------------------------------User file fetch data---------------------------------*/
// Add a new route for downloading files
app.get('/download/:id', (req, res) => {
const fileId = req.params.id;
// Query the MySQL database to get file information based on the provided id
connection.query('SELECT * FROM file WHERE id = ?', [fileId], (error, results, fields) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
// Assuming 'data' is the column with BLOB data and 'filename' is the original filename
const fileData = results[0].data; // Access the BLOB data from the first result (adjust as needed)
const filename = results[0].filename; // Access the filename from the first result (adjust as needed)
// Set response headers for file download
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', 'application/octet-stream');
// Send the BLOB data as the response
res.send(fileData);
}
});
});
app.get('/index', (req, res) => {
try {
// Query the MySQL database to select distinct username, project_name, and summary
connection.query('SELECT username, project_name, summary FROM file GROUP BY username, project_name, summary', (error, results, fields) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
// Render the 'index' page and pass the query results
res.render('index', { data: results, title: 'User Projects' });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
/*------------------------------------User file fetch data---------------------------------*/
// Add this route to handle getFileContent requests
// Your existing /index route remains unchanged
// Add a new route to handle the click on the project name
// Update the /user route to fetch distinct username and project_name
// Add this route in your main server file
// Add this route in your main server file (app.js or index.js)
// Add this route in your main server file (app.js or index.js)
// Route to delete a project
app.get('/user', (req, res) => {
try {
const storedUsername = req.cookies.username;
if (!storedUsername) {
return res.status(401).send('Unauthorized. Please log in.');
}
connection.query('SELECT DISTINCT username, project_name, summary FROM file WHERE username = ?', [storedUsername], (error, results) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
res.render('user', { data: results, title: 'User Projects' });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
// Route to delete a project
app.post('/user/delete', (req, res) => {
try {
const storedUsername = req.cookies.username;
const projectNamesToDelete = req.body.selectedProjects.map(project => project.projectName);
if (!projectNamesToDelete || projectNamesToDelete.length === 0) {
return res.status(400).json({ success: false, error: 'No projects selected for deletion.' });
}
const placeholders = projectNamesToDelete.map(() => '?').join(', ');
const deleteQuery = `DELETE FROM file WHERE project_name IN (${placeholders}) AND username = ?`;
console.log('Delete Query:', deleteQuery);
console.log('Delete Parameters:', [...projectNamesToDelete, storedUsername]);
connection.query(deleteQuery, [...projectNamesToDelete, storedUsername], (error, results) => {
if (error) {
console.error('Error deleting projects:', error);
res.status(500).json({ success: false, error: 'Internal Server Error' });
} else {
console.log('Deletion successful. Rows affected:', results.affectedRows);
// Fetch updated data from the server
connection.query('SELECT DISTINCT username, project_name FROM file WHERE username = ?', [storedUsername], (error, results) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).json({ success: false, error: 'Internal Server Error' });
} else {
res.json({
success: true,
deletedProjects: projectNamesToDelete,
updatedData: results,
});
}
});
}
});
} catch (err) {
console.error('Error handling deletion:', err);
res.status(500).json({ success: false, error: 'Internal Server Error' });
}
});
// Add a new route to handle the click on the project name and fetch related files
app.get('/related/:username/:projectName', (req, res) => {
const storedUsername = req.cookies.username;
const projectName = req.params.projectName;
try {
// Check if the username is present in cookies
if (!storedUsername) {
return res.status(401).send('Unauthorized. Please log in.');
}
// Query the MySQL database to fetch files related to the stored username and project name
const query = `
SELECT *
FROM file
WHERE username = ? AND project_name = ?
`;
connection.query(query, [storedUsername, projectName], (error, results, fields) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
// Render the 'related' page and pass the query results
res.render('related', { data: results, title: 'Related Files', username: storedUsername, projectName });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
app.get('/related', (req, res) => {
try {
// Query the MySQL database
connection.query('SELECT * FROM file', (error, results, fields) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
// Render the 'index' page and pass the query results
res.render('related', { data: results, title: 'File List' });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
app.get('/getFileContent/:id', (req, res) => {
const fileId = req.params.id;
try {
// Query the MySQL database to fetch the content of the file with the given ID
const query = `
SELECT data
FROM file
WHERE id = ?
`;
connection.query(query, [fileId], (error, results, fields) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else if (results.length === 0) {
// If no file with the given ID is found, return a 404 Not Found response
res.status(404).send('File Not Found');
} else {
// Return the content of the file
res.send(results[0].data);
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
app.get('/userdata', (req, res) => {
try {
// Query the MySQL database
connection.query('SELECT * FROM file', (error, results, fields) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
// Render the 'index' page and pass the query results
res.render('userdata', { data: results, title: 'File List' });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
app.get('/profile', (req, res) => {
try {
const storedUsername = req.cookies.username;
if (!storedUsername) {
return res.status(401).send('Unauthorized. Please log in.');
}
connection.query('SELECT DISTINCT username, email, password, lang, exp, professional, education, skill FROM student WHERE username = ?', [storedUsername], (error, results) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
res.render('profile', { data: results, title: 'User Profile' });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
app.get('/teacher_profile', (req, res) => {
try {
const storedUsername = req.cookies.username;
if (!storedUsername) {
return res.status(401).send('Unauthorized. Please log in.');
}
connection.query('SELECT DISTINCT username, email, password, lang, exp, professional, education, skill FROM student WHERE username = ?', [storedUsername], (error, results) => {
if (error) {
console.error('Error executing MySQL query:', error);
res.status(500).send('Internal Server Error');
} else {
res.render('teacher_profile', { data: results, title: 'User teacher_profile' });
}
});
} catch (err) {
console.error('Error handling MySQL query:', err);
res.status(500).send('Internal Server Error');
}
});
/*
app.post("/profile/image", (req, res) => {
try {
const storedUsername = req.cookies.username;
if (!storedUsername) {
return res.status(401).send("Invalid username. Please log in with the correct username.");
}
if (!req.files || !req.files.image) {
console.error("No image file uploaded.");
return res.status(400).send("No image file uploaded.");
}
const image = req.files.image;
const imageData = image.data;
const updateQuery = "UPDATE student SET image=? WHERE username=?";
connection.query(updateQuery, [imageData, storedUsername], (err, result) => {
if (err) {
console.error("Error updating image:", err);
res.redirect("../profile");
} else {
res.redirect("../profile");
res.status(200).end();
}
});
} catch (error) {
console.error("Error in image update route:", error);
res.redirect("../profile");
res.status(500).send("Internal Server Error");
}
});
*/
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public')); // Assuming your static files are in the 'public' folder
app.use(fileUpload());
app.post("/profile/data", (req, res) => {
try {
const storedUsername = req.cookies.username;
if (!storedUsername) {
return res.status(401).send("Invalid username. Please log in with the correct username.");
}
const { lang, skill, exp, professional, education } = req.body;
const updateQuery = `
UPDATE student
SET lang=TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM lang), ''), ''), ?)),
skill=TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM skill), ''), ''), ?)),
exp=TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM exp), ''), ''), ?)),
professional=TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM professional), ''), ''), ?)),
education=TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM education), ''), ''), ?))
WHERE username=?
`;
connection.query(
updateQuery,
[lang, skill, exp, professional, education, storedUsername],
(err, result) => {
if (err) {
console.error("Error updating profile data:", err);
res.redirect("../profile");
} else {
res.status(200).send("Profile updated successfully");
}
}
);
} catch (error) {
console.error("Error in profile data update route:", error);
res.status(500).send("Internal Server Error");
}
});
app.post("/teacher_profile/data", (req, res) => {
try {
const storedUsername = req.cookies.username;
if (!storedUsername) {
return res.status(401).send("Invalid username. Please log in with the correct username.");
}
const { lang, skill, exp, professional, education } = req.body;
const updateQuery = `
UPDATE student
SET lang = TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM lang), ''), ''), ?)),
skill = TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM skill), ''), ''), ?)),
exp = TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM exp), ''), ''), ?)),
professional = TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM professional), ''), ''), ?)),
education = TRIM(BOTH ',' FROM CONCAT_WS(', ', IFNULL(NULLIF(TRIM(BOTH ',' FROM education), ''), ''), ?))
WHERE username = ?
`;
connection.query(updateQuery, [lang, skill, exp, professional, education, storedUsername], (err, result) => {
if (err) {
console.error("Error updating profile data:", err);
res.status(500).send("Error updating profile data");
} else {
console.log("Profile updated successfully");
res.status(200).send("Profile updated successfully");
}
});
} catch (error) {
console.error("Error in profile data update route:", error);
res.status(500).send("Internal Server Error");
}
});
app.post('/removeSkill', (req, res) => {
// Extract the username from the request
const storedUsername = req.cookies.username;
// Check if the username is defined
if (!storedUsername) {
return res.status(401).send("Invalid username. Please log in with the correct username.");
}
// Extract the skill to remove from the request body
const langToRemove = req.body.langName;
// Fetch the current list of skills from the database
connection.query('SELECT lang FROM student WHERE username = ?', [storedUsername], (err, result) => {
if (err) {
console.error("Error fetching skills:", err);
res.status(500).send("Error fetching skills");
} else {
// Extract the skills from the result
const currentLang = result[0].lang.split(',').map(lang => lang.trim());
const updatedLang = currentLang.filter(lang => lang !== langToRemove);
const updatedLangString = updatedLang.join(', ');
// Update the 'student' table with the updated skills
// Update the 'student' table with the updated skills
connection.query('UPDATE student SET lang = ? WHERE username = ?', [updatedLangString, storedUsername], (err, result) => {
if (err) {
console.error("Error updating skills:", err);
res.status(500).send("Error updating skills");
} else {
console.log("Skill removed successfully");
res.status(200).send("Skill removed successfully");
}
});
}
});