-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
311 lines (271 loc) · 9.99 KB
/
Copy pathserver.js
File metadata and controls
311 lines (271 loc) · 9.99 KB
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
/* eslint-disable max-len */
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const jwtAuth = require('./jwt_middleware');
const collections = require('./models');
const backend = require('./backend');
const PORT = process.env.PORT || 3001;
const secret = process.env.JWT_SECRET_KEY || 'pokTGERW54389e#@$%mans12$@!$!#$^#%$';
const studentDatasets = ['students-1.csv', 'dummies.csv', 'students-2.csv']; // ADD ALL DATASETS HERE
const applicationDatasets = ['applications-1.csv', 'dummyapps.csv', 'applications-2.csv'];// ADD ALL DATASETS HERE
app = express();
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(cookieParser());
mongoose.connect('mongodb://localhost/c4me', {useUnifiedTopology: true, useNewUrlParser: true});
app.get('/', (req, res)=>{
res.send('Testing');
});
app.post('/api/register', async (req, res)=>{
req.body.userid = req.body.userid.toLowerCase();
if (req.body.userid !== 'admin') {
try {
const newStudent = await backend.studentHandler.registerStudent(req.body.userid, req.body.password);
console.log('Created', newStudent);
res.status(200).json({status: 'OK'});
} catch (err) {
res.status(401).json({error: err.message});
}
} else {
res.status(401).json({error: 'userid or email already taken!'});
}
});
app.post('/api/login', (req, res) => {
const {userid, password} = req.body;
if (userid === 'admin' && password === 'admin') { // HARD CODED ADMIN
const payload = {userid: 'admin'};
const token = jwt.sign(payload, secret, {
expiresIn: '1d',
});
res.cookie('token', token, {httpOnly: false}).status(200).json({userid: 'admin'});
} else { // NORMAL STUDENTS
collections.Student.findOne({userid}).then((user)=>{
if (!user) {
res.status(401).json({error: 'Incorrect userid or password'});
} else {
user.isCorrectPassword(password, (same)=>{
if (!same) {
res.status(401).json({error: 'Incorrect userid or password'});
} else {
// Put values that we will need inside the token
const payload = {userid};
// Issue token
const token = jwt.sign(payload, secret, {
expiresIn: '1d',
});
res.cookie('token', token, {httpOnly: false}).status(200).send();
}
});
}
});
}
});
app.get('/deletestudents', async (req, res)=>{
await backend.adminHandler.deleteAllStudents();
res.status(200).send();
});
app.get('/importstudentdatasets', async (req, res) => {
const importAllStudents = studentDatasets.map(async (student) => {
await backend.adminHandler.importStudentProfiles(student);
});
await Promise.all(importAllStudents);
for (let i = 0; i < applicationDatasets.length; i++) {
await backend.adminHandler.importApplicationData(applicationDatasets[i]);
}
res.status(200).send();
});
app.get('/scrapecollegerankings', async (req, res)=>{
await backend.adminHandler.importCollegeRankings('./datasets/colleges.txt');
res.status(200).send();
});
app.get('/scrapecollegedata', async (req, res)=>{
await backend.adminHandler.importCollegeData('./datasets/colleges.txt');
await backend.adminHandler.importCollegeDescriptions('./datasets/colleges.txt');
res.status(200).send();
});
app.get('/importcollegescorecard', async (req, res)=>{
await backend.adminHandler.importScorecardData('./datasets/colleges.txt');
res.status(200).send();
});
// CHECKS IF WE ARE LOGGED IN OR NOT WITH MIDDLEWARE
app.get('/checkToken', jwtAuth, (req, res)=>{
res.status(200).json({userid: req.userid});
});
app.post('/searchforcolleges', async (req, res) => {
const colleges = await backend.collegeSearch.searchCollege(req.body.query);
res.status(200).send({colleges: colleges});
});
app.post('/retrievestudents', async (req, res) => {
const collegeName = req.body.query;
const applications = await collections.Application.find({college: collegeName, questionable: false}).lean();
console.log('Applications:', applications);
const userIdList = applications.map((application) => application.userid);
const students = await collections.Student.find({userid: {$in: userIdList}}).populate({path: 'applications'}).lean();
res.status(200).send({students: students});
});
app.post('/getuser', async (req, res) => {
try {
const user = await backend.studentHandler.getStudentProfile(req.body.userId);
res.status(200).json({user});
} catch (error) {
console.log(error);
res.status(401).json({err: 'User does not exist'});
}
});
app.post('/setStudentInfo', async (req, res) => {
try {
if ( (req.body.user.high_school_name && req.body.user.high_school_city )!== null ) {
req.body.user.high_school_name = req.body.user.high_school_name.toLowerCase();
req.body.user.high_school_city = req.body.user.high_school_city.toLowerCase();
}
await backend.studentHandler.editStudentInfo(req.body.user);
await backend.studentHandler.importStudentHS(req.body.user);
res.status(200).send({msg: 'Your profile have been update'});
} catch (e) {
res.status(200).json({err: 'High School Doesn\'t exist check School name, city and state'});
}
});
app.post('/calculateSimilarHighschools', async (req, res) => {
try {
const results = await backend.computeScores.calculateSimilarHighschools(req.body.name, req.body.city, req.body.state);
res.status(200).json({highschools: results});
} catch (e) {
console.log(e);
res.status(400).send();
}
});
app.post('/calculateCollegeScore', async (req, res) => {
const results = await backend.computeScores.calculateCollegeScore(req.body.student);
res.status(200).json({collegeScores: results});
});
app.post('/getapplications', async (req, res) => {
const userid = req.body.query;
const applications = await collections.Application.find({userid}).lean();
console.log('Applications:', applications);
res.status(200).send({applications: applications});
});
app.post('/updateapplications', async (req, res) => {
const {
statusTracker,
userid,
} = req.body;
const ids = Object.keys(statusTracker);
const student = await collections.Student.findOne({userid}).lean();
for (const _id of ids) {
await collections.Application.updateOne({_id}, {
status: statusTracker[_id].status,
});
try {
await backend.computeScores.isQuestionableApplication(statusTracker[_id].collegeName, student, _id);
} catch (err) {
console.err(err.message);
return;
}
}
const updatedApplications = await collections.Application.find({_id: {$in: ids}}).lean();
// console.log(updatedApplications);
res.status(200).send({
applications: updatedApplications,
});
});
app.post('/addapplication', async (req, res) => {
const {
userid,
college,
status,
statusTracker,
} = req.body;
const newApplication = {
userid,
college,
status,
questionable: false,
};
const doc = await collections.Application.create(newApplication);
let student = await collections.Student.findOne({userid}).lean();
try {
await backend.computeScores.isQuestionableApplication(college, student, doc._id);
} catch (err) {
console.log(err);
return;
}
student = await collections.Student.updateOne({userid}, {$push: {applications: doc._id}});
statusTracker[doc._id] = {
status,
collegeName: college,
};
student = await collections.Student.findOne({userid}).populate({path: 'applications'}).lean();
res.status(200).send({
applications: student.applications,
statusTracker,
});
});
app.post('/deleteapplication', async (req, res) => {
console.log('Deleting An Application');
const {
userid,
_id,
applications,
statusTracker,
} = req.body;
const deleted = await collections.Application.deleteOne({_id});
console.log('Deleted:', deleted);
await collections.Student.updateOne({userid}, {$pull: {applications: _id}});
const student = await collections.Student.findOne({userid}).lean();
console.log('Student Now:', student);
delete statusTracker[_id];
const updatedApplications = applications.filter((app) => app._id !== _id);
console.log('Status Tracker');
console.log(statusTracker);
console.log('Updated Applications');
console.log(updatedApplications);
res.status(200).send({
applications: updatedApplications,
statusTracker,
});
});
app.post('/retrievequestionableapps', async (req, res) => {
const questionableApps = await collections.Application.find({questionable: true});
res.status(200).send({
questionableApps,
});
});
app.post('/marknotquestionable', async (req, res) => {
const selectedApps = req.body.selectedApps;
const questionableApps = req.body.questionableApps;
console.log('selectedApps (server)', selectedApps);
console.log('questionableApps (server)', questionableApps);
for (const appId of selectedApps) {
await collections.Application.updateOne({_id: appId}, {
questionable: false,
});
const debugging = await collections.Application.findOne({_id: appId}).lean();
console.log(debugging);
}
const updatedQuestionableApps = questionableApps.filter((app) => !selectedApps.includes(app._id));
console.log('updatedQuestionableApps (server)', updatedQuestionableApps);
res.status(200).send({questionableApps: updatedQuestionableApps});
});
app.post('/getallhighschools', async (req, res) => {
const hs = await collections.HighSchool.find({}).lean();
res.status(200).send({highschools: hs});
});
app.post('/getcollegenames', async (req, res) => {
const colleges = await collections.College.find({}).lean();
const collegeNames = colleges.map((c) => c.name);
res.status(200).send({collegeNames});
});
app.post('/importahs', async (req, res) => {
try {
await backend.adminHandler.importHighschoolData(req.body.name, req.body.city, req.body.state);
res.status(200).send();
} catch (e) {
console.log(e);
res.status(404).send();
}
});
app.listen(PORT, ()=>{
console.log('Backend listening on port:', PORT);
});