-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
548 lines (507 loc) · 15.9 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
const Lesson = require('./models/lesson');
const Unit = require('./models/unit');
const Subject = require('./models/subject');
const User = require('./models/user');
const bodyParser = require('body-parser');
const config = require('./config');
const mongoose = require('mongoose');
const moment = require('moment');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const passport = require('passport');
const BasicStrategy = require('passport-http').BasicStrategy;
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(express.static('public'));
mongoose.Promise = global.Promise;
// ---------------- RUN/CLOSE SERVER -----------------------------------------------------
let server = undefined;
function runServer(urlToUse) {
return new Promise((resolve, reject) => {
mongoose.connect(urlToUse, err => {
if (err) {
return reject(err);
}
server = app.listen(config.PORT, () => {
console.log(`Listening on localhost:${config.PORT}`);
resolve();
}).on('error', err => {
mongoose.disconnect();
reject(err);
});
});
});
}
if (require.main === module) {
runServer(config.DATABASE_URL).catch(err => console.error(err));
}
function closeServer() {
return mongoose.disconnect().then(() => new Promise((resolve, reject) => {
console.log('Closing server');
server.close(err => {
if (err) {
return reject(err);
}
resolve();
});
}));
}
// ---------------USER ENDPOINTS-------------------------------------
// POST -----------------------------------
// creating a new user
app.post('/users/create', (req, res) => {
//take the input from the payload
let username = req.body.username;
let password = req.body.password;
let name = req.body.name;
//exclude spaces from the username and password
username = username.trim();
password = password.trim();
//search if the user exists in the databse
User
.findOne({
username: req.body.username
}, function (err, items) {
//if the database search failed...
if (err) {
//return an error
return res.status(500).json({
message: "Database connection failed."
});
}
//if that user is not in the database...
if (!items) {
//generate the encryption key (Salt)
bcrypt.genSalt(10, (err, salt) => {
//if the encryption key fails...
if (err) {
//display an error
return res.status(500).json({
message: 'Encryption key failed'
});
}
//using the encryption key above, encrypt the password (hash)
bcrypt.hash(password, salt, (err, hash) => {
//if encrypting the password fails...
if (err) {
//display an error
return res.status(500).json({
message: 'Password encryption failed'
});
}
//add the new user to the database
User.create({
username,
password: hash,
name,
}, (err, item) => {
//if adding to the database fails...
if (err) {
//display an error
return res.status(500).json({
message: 'Adding user to the database failed'
});
}
//if the user is created...
if (item) {
//return the created user
console.log(`User \`${username}\` created.`);
return res.json(item);
}
});
});
});
}
//if the user exists in the database...
else {
//return an error
return res.status(401).json({
message: "User already exists!"
});
};
});
});
// signing in a user
app.post('/users/signin', function (req, res) {
//take the values from the payload
const user = req.body.username;
const pw = req.body.password;
//search in the database for a user with the existing username
User
.findOne({
username: req.body.username
}, function (err, items) {
//if the database search failed...
if (err) {
//return an error
return res.status(500).json({
message: "Database connection failed."
});
}
//if that user is not in the database...
if (!items) {
//return an error
return res.status(401).json({
message: "User not found!"
});
} else {
//if the user is found, validate the password
items.validatePassword(req.body.password, function (err, isValid) {
//if password validation failed...
if (err) {
//display an error
console.log('There was an error validating the password.');
}
//if the password is not valid...
if (!isValid) {
//display an error
return res.status(401).json({
message: "Password not valid."
});
}
//if the username and password are valid return the username
else {
return res.json(items);
}
});
};
});
});
// -------------SUBJECT ENDPOINTS------------------------------------
// POST -----------------------------------------
// creating a new subject
app.post('/subject/create', (req, res) => {
const {
subjectName,
user_id
} = req.body;
console.log(req.body);
Subject.create({
subjectName,
user_id
}, (err, item) => {
if (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
}
if (item) {
console.log(`${subjectName} added.`);
return res.status(201).json(item);
}
});
});
// PUT --------------------------------------
app.put('/subject/:id', function (req, res) {
let toUpdate = {};
let updateableFields = ['subjectName'];
updateableFields.forEach(function (field) {
if (field in req.body) {
toUpdate[field] = req.body[field];
}
});
Subject
.findByIdAndUpdate(req.params.id, {
$set: toUpdate
}).exec().then(function (subject) {
return res.status(204).end();
}).catch(function (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
});
});
// GET ------------------------------------
// accessing all of a user's subjects
app.get('/subjects/:user_id', function (req, res) {
Subject
.find()
.sort('subjectName')
.then(function (subjects) {
let subjectOutput = [];
subjects.map(function (subject) {
if (subject.user_id == req.params.user_id) {
subjectOutput.push(subject);
}
});
res.json({
subjectOutput
});
})
.catch(function (err) {
console.error(err);
res.status(500).json({
message: 'Internal server error'
});
});
});
// accessing a single subject by id
app.get('/subject/:id', function (req, res) {
Subject
.findById(req.params.id).exec().then(function (subject) {
return res.json(subject);
})
.catch(function (subject) {
console.error(err);
res.status(500).json({
message: 'Internal Server Error'
});
});
});
// DELETE ----------------------------------------
// deleting a subject by id
app.delete('/subject/:id', function (req, res) {
Subject.findByIdAndRemove(req.params.id).exec().then(function (subject) {
return res.status(204).end();
}).catch(function (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
});
});
// -------------UNIT ENDPOINTS------------------------------------------------
//POST-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
//creating a new unit
app.post('/unit/create', (req, res) => {
const {
title,
user_id,
class_id,
desc
} = req.body;
console.log(req.body);
Unit.create({
title,
user_id,
class_id,
desc
}, (err, item) => {
if (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
}
if (item) {
console.log(`${title} added.`);
return res.status(201).json(item);
}
});
});
// PUT --------------------------------------
app.put('/unit/:id', function (req, res) {
let toUpdate = {};
let updateableFields = ['title', 'desc', 'class_id'];
updateableFields.forEach(function (field) {
if (field in req.body) {
toUpdate[field] = req.body[field];
}
});
Unit
.findByIdAndUpdate(req.params.id, {
$set: toUpdate
}).exec().then(function (unit) {
return res.status(204).end();
}).catch(function (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
});
});
// GET ------------------------------------
// accessing all of a user's units
app.get('/units/:user_id', function (req, res) {
Unit
.find()
.sort('title')
.then(function (units) {
let unitOutput = [];
units.map(function (unit) {
if (unit.user_id == req.params.user_id) {
unitOutput.push(unit);
}
});
res.json({
unitOutput
});
})
.catch(function (err) {
console.error(err);
res.status(500).json({
message: 'Internal server error'
});
});
});
// accessing a single unit by id
app.get('/unit/:id', function (req, res) {
Unit
.findById(req.params.id).exec().then(function (unit) {
return res.json(unit);
})
.catch(function (unit) {
console.error(err);
res.status(500).json({
message: 'Internal Server Error'
});
});
});
// DELETE ----------------------------------------
// deleting a unit by id
app.delete('/unit/:id', function (req, res) {
Unit.findByIdAndRemove(req.params.id).exec().then(function (unit) {
return res.status(204).end();
}).catch(function (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
});
});
//delete many units by subject id
app.delete('/units/:id', function (req, res) {
console.log(req.params.id);
Unit.deleteMany({
class_id: req.params.id
}).exec().then(function (unit) {
return res.status(204).end();
}).catch(function (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
});
});
// -------------LESSON ENDPOINTS------------------------------------------------
// POST -----------------------------------------
// creating a new lesson
app.post('/lesson/create', (req, res) => {
const {
user_id,
title,
subject_id,
unit_id,
day,
stnds,
learningTargets,
lessonDetails,
assessment,
homework,
notes,
reflection
} = req.body;
console.log(req.body);
Lesson.create({
user_id,
title,
subject_id,
unit_id,
day,
stnds,
learningTargets,
lessonDetails,
assessment,
homework,
notes,
reflection
}, (err, item) => {
if (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
}
if (item) {
console.log(`Lesson \`${title}\` added.`);
return res.status(201).json(item);
}
});
});
// PUT --------------------------------------
app.put('/lesson/:id', function (req, res) {
let toUpdate = {};
let updateableFields = ['title', 'desc', 'day', 'stnds', 'learningTargets', 'lessonDetails', 'assessment', 'homework', 'notes', 'reflection'];
updateableFields.forEach(function (field) {
if (field in req.body) {
toUpdate[field] = req.body[field];
}
});
Lesson
.findByIdAndUpdate(req.params.id, {
$set: toUpdate
}).exec().then(function (lesson) {
return res.status(204).end();
}).catch(function (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
});
});
// GET ------------------------------------
// accessing all of a user's lessons
app.get('/lessons/:user_id', function (req, res) {
Lesson
.find()
.sort('day')
.then(function (lessons) {
let lessonOutput = [];
lessons.map(function (lesson) {
if (lesson.user_id == req.params.user_id) {
lessonOutput.push(lesson);
}
});
res.json({
lessonOutput
});
})
.catch(function (err) {
console.error(err);
res.status(500).json({
message: 'Internal server error'
});
});
});
// accessing a single lesson by id
app.get('/lesson/:id', function (req, res) {
Lesson
.findById(req.params.id).exec().then(function (lesson) {
return res.json(lesson);
})
.catch(function (lesson) {
console.error(err);
res.status(500).json({
message: 'Internal Server Error'
});
});
});
// DELETE ----------------------------------------
// deleting a lesson by id
app.delete('/lesson/:id', function (req, res) {
Lesson.findByIdAndRemove(req.params.id).exec().then(function (lesson) {
return res.status(204).end();
}).catch(function (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
});
});
//delete many lessons by unit id
app.delete('/lessons/:id', function (req, res) {
console.log(req.params.id);
Lesson.deleteMany({
unit_id: req.params.id
}).exec().then(function (unit) {
return res.status(204).end();
}).catch(function (err) {
return res.status(500).json({
message: 'Internal Server Error'
});
});
});
// MISC ------------------------------------------
// catch-all endpoint if client makes request to non-existent endpoint
app.use('*', (req, res) => {
res.status(404).json({
message: 'Not Found'
});
});
exports.app = app;
exports.runServer = runServer;
exports.closeServer = closeServer;