-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
392 lines (338 loc) · 12.7 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
const UCI = require('UCI');
const MYRMEYDB = require('./myrmeydb.js');
const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const path = require('path');
const config = require('./config.json');
let serverInitiated = false;
const STATS = {
searchScheduleRequests: 0,
getCourseDetailsRequests: 0
};
const services = {};
if (config.watchlist.enable) {
services.watchlist = require('./watchlist.js');
services.watchlist.init(UCI.SOC, MYRMEYDB, config.watchlist.gmail_auth, config.watchlist.interval);
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(path.join(__dirname, 'web/build')));
/**
* generateMyrmeyId
*
* Generates a MyrmeyId given the student's hashed id and any additional data that should be a part of the jwt. The generated
* MyrmeyId is a jwt that can be used to authenticate student with MyrmeyAssist specific resources, such as the MyrmeyMessenger.
* @param {string} id The student's hashed id
* @param {object} data Any additional data that might be required by other Myrmey resources
* @return {string} The MyrmeyId jwt
*/
function generateMyrmeyId(id, data) {
let signObject = Object.assign({
id
}, data);
return jwt.sign(signObject, config.salt);
}
function getStudentData(auth, res) {
console.log(`Pulling information for: ${auth}`);
return Promise.all([UCI.STUDENT.getDegreeWorks(auth), UCI.STUDENT.getCourses(auth)])
.then((studentData) => {
let hashedId = crypto.createHash('sha256').update(`${studentData[0].student.id}${studentData[0].student.name}${config.salt}`).digest('hex');
console.log(`Generating MyrmeyId`);
let myrmeyid = generateMyrmeyId(hashedId, {
courses: Object.keys(studentData[1].inProgress)
});
console.log(`Adding Grades to MyrmeyDB`);
MYRMEYDB.addGrades(hashedId, studentData[1].completed);
console.log(`Getting Manually Added Completed Courses`);
MYRMEYDB.getCompletedCourses(hashedId)
.then((manualCompletedCourses) => {
studentData[1].completed = Object.assign(studentData[1].completed, manualCompletedCourses);
res.send({
success: true,
data: {
myrmeyid: myrmeyid,
studentInfo: studentData[0].student,
advice: studentData[0].advice,
courses: studentData[1]
}
});
});
})
.catch((err) => {
console.error(err);
})
}
function getCourseDetails(courseName, res) {
let courseDeptNum = /^(.+)\s(.+)$/.exec(courseName);
let dbSelector = {
dept: courseDeptNum[1],
num: courseDeptNum[2]
}
let searchScheduleParams = {
Dept: courseDeptNum[1],
CourseNum: courseDeptNum[2]
}
Promise.all([UCI.SOC.getCourseDetails([courseName]), MYRMEYDB.getGrades(dbSelector), searchSchedule(searchScheduleParams)])
.then((response) => {
let course = response[0][courseName];
if (!course) {
res.send({
success: false, error: 'Invalid Course'
});
return;
}
course.dept = courseDeptNum[1];
course.num = courseDeptNum[2];
course.offerings = [];
//If there are offerings add them, otherwise just leave it as an empty array.
if (response[2].length > 0) {
course.offerings = response[2][0].offerings;
}
let courseGrades = {};
//Go through the results of the db grade lookup for the course, organizing the grades by professor.
response[1].forEach((row) => {
if (courseGrades[row.instructor] === undefined) {
let ratemyprofessor = UCI.PROFS.getProfessor(row.instructor);
courseGrades[row.instructor] = {
instructor: {
name: row.instructor,
rmp: ratemyprofessor
},
A: 0,
B: 0,
C: 0,
D: 0,
F: 0,
P: 0,
NP: 0
};
}
courseGrades[row.instructor][row.grade[0]] += 1; //Use row.grade[0] to treat +/- the same. A+/- = A
})
course.gradeDistributions = [];
Object.keys(courseGrades).forEach((instructor) => {
course.gradeDistributions.push(courseGrades[instructor]);
});
res.send({ success: true, data: course });
})
.catch((err) => {
console.error(err);
res.send({ success: false, error: err });
})
}
const offeringBlacklist = ["Nor", "Place", "Req", "Rstr", "Sec", "Textbooks", "Web"]; //The columns to remove before passing onto the frontend
function searchSchedule(search, res) {
return UCI.SOC.searchSchedule(search)
.then((results) => {
//We have the results go through and modify the instructors to add their ratemyprofessor object and remove blacklisted columns
results.forEach((course) => {
course.offerings.forEach((offering) => {
offeringBlacklist.forEach((blacklistedColumn) => {
offering[blacklistedColumn] = undefined;
});
offering.Time = offering.Time.trim();
offering.Instructor = offering.Instructor.map((instructor) => {
let rmp = UCI.PROFS.getProfessor(instructor);
return {
name: instructor,
rmp
}
})
})
});
if (res) {
res.send({
success: true,
data: results
});
return Promise.resolve();
}
return results;
});
}
app.post('/api/login', (req, res) => {
console.log(`[LOGIN REQUEST]`);
if (req.body.ucinetid_auth) {
auth = `ucinetid_auth=${req.body.ucinetid_auth}`
getStudentData(auth, res);
return;
}
UCI.STUDENT.login(req.body.ucinetid, req.body.password)
.then((auth) => {
getStudentData(auth, res);
})
.catch((error) => {
console.error(error);
res.send({
success: false,
error
})
})
});
app.get('/api/getCourseDetails', (req, res) => {
//console.log(`[getCourseDetails REQUEST]`);
STATS.getCourseDetailsRequests++;
updateConsole();
if (!req.query.course) {
res.send({ success: false, error: 'ERROR: Please provide a course.' });
return;
}
getCourseDetails(req.query.course, res);
});
app.post('/api/searchSchedule', (req, res) => {
if (!serverInitiated) {
res.send({
success: false,
error: 'MyrmeyAssist was just updated and is currently restarting. Please try again in 1-2 minutes.'
})
return;
}
//console.log(`[searchSchedule REQUEST]`);
STATS.searchScheduleRequests++;
updateConsole();
if (req.body.InstrName === '' && req.body.CourseCodes === '' && req.body.Dept === 'ALL' && req.body.Breadth === 'ANY') {
res.send({
success: false,
error: 'ERROR: You must specify an Instructor, Course Code range, Department, or Breadth category.'
});
return;
}
searchSchedule(req.body, res);
});
app.post('/api/addCompletedCourse', (req, res) => {
console.log(`[addCompletedCourse REQUEST]`);
if (!req.body.myrmeyid || !req.body.courseName) {
res.send({
success: false,
error: 'ERROR: Invalid course name or id specified.'
});
return;
}
//Verify the student's myrmeyid before adding their completed course
jwt.verify(req.body.myrmeyid, config.salt, (error, decoded) => {
if (error) {
res.send({
success: false,
error
});
return;
}
MYRMEYDB.addCompletedCourse(decoded.id, req.body.courseName)
.then(() => {
res.send({ success: true })
})
});
});
app.post('/api/addWatchlist', (req, res) => {
console.log(`[addWatchlist REQUEST]`);
if (!req.body.email || !req.body.code) {
res.send({
success: false,
error: 'ERROR: Invalid email or code specified.'
});
return;
}
MYRMEYDB.addWatch(req.body.email, req.body.code)
.then(() => {
res.send({ success: true });
})
.catch((err) => {
if (err.detail.includes('already exists')) {
res.send({ success: false, error: `${req.body.code} is already on your watchlist.` });
}
});
//Disabled while login is disabled
/* if (!req.body.myrmeyid || !req.body.email || !req.body.code) {
res.send({
success: false,
error: 'ERROR: Invalid email, code or id specified.'
});
return;
} */
//[Disabled while login is disabled] Verify the student's myrmeyid before adding their request to the watchlist
/* jwt.verify(req.body.myrmeyid, config.salt, (error, decoded) => {
if (error) {
res.send({
success: false,
error
});
return;
}
MYRMEYDB.addWatch(req.body.email, req.body.code)
.then(() => {
res.send({ success: true });
})
.catch((err) => {
if (err.detail.includes('already exists')) {
res.send({ success: false, error: `${req.body.code} is already on your watchlist.` });
}
});
}); */
});
function approveDomains(opts, certs, cb) {
// This is where you check your database and associated
// email addresses with domains and agreements and such
// The domains being approved for the first time are listed in opts.domains
// Certs being renewed are listed in certs.altnames
if (certs) {
opts.domains = ['myrmeyassist.com', 'www.myrmeyassist.com'];
}
else {
opts.email = '[email protected]';
opts.agreeTos = true;
}
// NOTE: you can also change other options such as `challengeType` and `challenge`
// opts.challengeType = 'http-01';
// opts.challenge = require('le-challenge-fs').create({});
cb(null, { options: opts, certs: certs });
}
function startProdServer() {
// returns an instance of node-greenlock with additional helper methods
var lex = require('greenlock-express').create({
// set to https://acme-v01.api.letsencrypt.org/directory in production
server: 'https://acme-v01.api.letsencrypt.org/directory'
// If you wish to replace the default plugins, you may do so here
//
, challenges: { 'http-01': require('le-challenge-fs').create({ webrootPath: '/tmp/acme-challenges' }) }
, store: require('le-store-certbot').create({ webrootPath: '/tmp/acme-challenges' })
// You probably wouldn't need to replace the default sni handler
// See https://git.daplie.com/Daplie/le-sni-auto if you think you do
//, sni: require('le-sni-auto').create({})
, approveDomains: approveDomains
});
// handles acme-challenge and redirects to https
require('http').createServer(lex.middleware(require('redirect-https')())).listen(80, function () {
console.log("Listening for ACME http-01 challenges on", this.address());
});
// handles your app
require('https').createServer(lex.httpsOptions, lex.middleware(app)).listen(443, function () {
console.log("Listening for ACME tls-sni-01 challenges and serve app on", this.address());
});
}
function updateConsole(){
console.reset();
console.log();
console.log(`searchScheduleRequests: ${STATS.searchScheduleRequests}`);
console.log(`getCourseDetailsRequests: ${STATS.getCourseDetailsRequests}`);
}
console.reset = function () {
return process.stdout.write('\033c');
}
if (config.production) {
startProdServer();
}
else {
app.listen(8080);
}
UCI.SOC.init()
.then(() => {
return Promise.all([UCI.PROFS.refreshProfs(), UCI.SOC.loadAll()]);
})
.then(() => {
serverInitiated = true;
})