-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
326 lines (281 loc) · 10.3 KB
/
index.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
const express = require('express');
const path = require('path');
const dotenv = require('dotenv');
const connectDB = require('./models/db');
const routes = require('./routes');
const Interview = require('./models/Interview');
const Student = require('./models/student');
const Job = require('./models/Job');
const jobRoutes = require('./routes/jobRoutes');
const studentRoutes = require('./routes/studentRoutes');
const authRoutes = require('./routes/authRoutes');
const interviewRoutes = require('./routes/interviewRoutes');
const passport = require('passport');
const session = require('express-session');
const flash = require('connect-flash');
const passportConfig = require('./config/passportConfig');
const { isAuthenticated, isEmployee } = require('./middleware/auth');
const apiRoutes = require('./routes/apiRoutes');
dotenv.config();
const app = express();
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// Logging middleware
app.use((req, res, next) => {
console.log(`Request URL: ${req.url}`);
next();
});
// Configure Passport
passportConfig(passport);
// Connect to database
connectDB();
// View engine setup
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Routes
app.use('/api', routes);
app.use('/jobs', isAuthenticated, jobRoutes);
app.use('/students', isAuthenticated, studentRoutes);
app.use('/', authRoutes);
app.use('/interviews', isAuthenticated, interviewRoutes);
app.use('/interviews', interviewRoutes);
app.use('/jobs', jobRoutes);
app.use('/api', apiRoutes);
// Magic login routes
app.post("/auth/magiclogin", passport.authenticate('magiclogin', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
app.get("/auth/magiclogin/callback", passport.authenticate('magiclogin', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
// Render the magic login page
app.get('/magiclogin', (req, res) => {
res.render('magicLogin', { title: 'Magic Login' });
});
// Route for initiating Google OAuth authentication
app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
// Route for handling Google OAuth callback
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
res.redirect('/');
});
// Home route
app.get('/', (req, res) => {
res.render('home', { user: req.user });
});
// Route that requires employee authorization
app.get('/employees-only', isEmployee, (req, res) => {
res.send('Welcome, employee!');
});
// Interview routes
app.get('/interviews/add', isAuthenticated, (req, res) => {
res.render('addInterview');
});
// Student routes
app.get('/students/add', isAuthenticated, (req, res) => {
res.render('addStudent');
});
// Fetch and render student list
app.get('/students', isAuthenticated, async (req, res) => {
try {
const studentList = await Student.find({});
res.render('studentList', { student_list: studentList });
} catch (error) {
console.error('Error fetching student data:', error);
res.status(500).send('Error fetching student data: ' + error.message);
}
});
// Add new student
app.post('/students/add', isAuthenticated, async (req, res) => {
try {
const { name, college, status, batch, courseScores } = req.body;
const newStudent = new Student({ name, college, status, batch, courseScores });
await newStudent.save();
res.redirect('/students');
} catch (error) {
console.error('Error adding student:', error);
res.status(500).send('Error adding student: ' + error.message);
}
});
// Handle form submission to delete a student
app.post('/students/delete', isAuthenticated, async (req, res) => {
try {
if (!req.body.studentId) {
throw new Error('Student ID is required for deletion.');
}
await Student.findByIdAndDelete(req.body.studentId);
res.redirect('/students');
} catch (err) {
console.error('Error in deleting student: ', err);
res.status(500).send('Error in deleting student: ' + err.message);
}
});
// Logout route
app.get('/logout', (req, res) => {
req.logout(err => {
if (err) {
return next(err);
}
req.flash('success_msg', 'You are logged out');
res.redirect('/login');
});
});
// Error handling middleware
app.use((req, res, next) => {
const error = new Error('Not Found');
error.status = 404;
next(error);
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
message: err.message,
error: process.env.NODE_ENV === 'development' ? err : {}
});
});
// Server setup
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
//earlier use of my routes please ignore the below commented area
// Fetch and render interview list
/*app.get('/interviews', isAuthenticated, async (req, res) => {
try {
const interviewList = await Interview.find({});
res.render('interviewList', { interview_list: interviewList });
} catch (error) {
console.error('Error fetching interview data:', error);
res.status(500).send('Error fetching interview data: ' + error.message);
}
});
// Fetch and render interview details including allocated students
app.get('/interviews/:id', isAuthenticated, async (req, res) => {
try {
const interview = await Interview.findById(req.params.id)
.populate('allocatedStudents.student')
.exec();
const students = await Student.find({}); // Fetch all students
if (!interview) {
return res.status(404).send('Interview not found');
}
res.render('viewInterview', { interview, students });
} catch (error) {
console.error('Error fetching interview details:', error);
res.status(500).send('Error fetching interview details: ' + error.message);
}
});
// Add new interview
app.post('/interviews/add', isAuthenticated, async (req, res) => {
try {
const { company, date } = req.body;
const newInterview = new Interview({ company, date });
await newInterview.save();
res.redirect('/interviews');
} catch (error) {
console.error('Error adding interview:', error);
res.status(500).send('Error adding interview: ' + error.message);
}
});*/
// Handle form submission to delete an interview
/*app.post('/interviews/delete', isAuthenticated, async (req, res) => {
try {
if (!req.body.interviewId) {
throw new Error('Interview ID is required for deletion.');
}
await Interview.findByIdAndDelete(req.body.interviewId);
res.redirect('/interviews');
} catch (err) {
console.error('Error in deleting interview: ', err);
res.status(500).send('Error in deleting interview: ' + err.message);
}
});*/
// Handle form submission to allocate a student to an interview
/*app.post('/interviews/allocate', isAuthenticated, async (req, res) => {
try {
const { interviewId, studentId } = req.body;
// Find the interview
const interview = await Interview.findById(interviewId);
if (!interview) {
throw new Error('Interview not found');
}
// Find the student
const student = await Student.findById(studentId);
if (!student) {
throw new Error('Student not found');
}
// Add the student to the interview's allocated students
interview.allocatedStudents.push({ student: student._id });
await interview.save();
// Redirect back to the interview details page
res.redirect(`/interviews/${interviewId}`);
} catch (error) {
console.error('Error in allocating student:', error);
res.status(500).send('Error in allocating student: ' + error.message);
}
});
// Handle form submission to mark student result for an interview
app.post('/interviews/mark-result', isAuthenticated, async (req, res) => {
try {
const { interviewId, studentId, result } = req.body;
const interview = await Interview.findById(interviewId);
const student = await Student.findById(studentId);
if (!interview || !student) {
return res.status(404).json({ message: 'Interview or Student not found' });
}
interview.allocatedStudents.forEach(allocation => {
if (allocation.student.equals(studentId)) {
allocation.result = result;
}
});
await interview.save();
res.redirect(`/interviews/${interviewId}`);
} catch (err) {
console.error('Error in marking result: ', err);
res.status(500).send('Error in marking result: ' + err.message);
}
});*/
// Fetch and render job list
/*app.get('/jobs/add', isAuthenticated, async (req, res) => {
try {
const jobList = await Job.find({});
res.render('jobList', { job_list: jobList });
} catch (error) {
console.error('Error fetching job data:', error);
res.status(500).send('Error fetching job data: ' + error.message);
}
});*/
// Handle form submission to add a new job
/*app.post('/jobs/add', isAuthenticated, async (req, res) => {
try {
const { title, location } = req.body;
const newJob = new Job({ title, location });
await newJob.save();
res.redirect('/jobs/add');
} catch (error) {
console.error('Error adding job:', error);
res.status(500).send('Error adding job: ' + error.message);
}
});
// Handle form submission to delete a job
app.post('/jobs/delete', isAuthenticated, async (req, res) => {
try {
if (!req.body.jobId) {
throw new Error('Job ID is required for deletion.');
}
await Job.findByIdAndDelete(req.body.jobId);
res.redirect('/jobs/add');
} catch (err) {
console.error('Error in deleting job: ', err);
res.status(500).send('Error in deleting job: ' + err.message);
}
});*/