-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
442 lines (407 loc) · 11.6 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
const express = require('express');
const cors = require('cors');
const path = require('path');
const bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
const app = express();
const HTTP_PORT = process.env.PORT || 8080;
const manager = require('./manager.js');
const m = manager(
'mongodb+srv://BrizzAdmin:sF0xMTodOoy7zaTG@brizz-bodhi.mongodb.net/BrizzDB?retryWrites=true&w=majority',
{ useUnifiedTopology: true }
);
app.use(bodyParser.json());
app.use(cors());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// JWT-----------------------------------------------------------------------------------------------------
const jwt = require('jsonwebtoken');
const passport = require('passport');
const passportJWT = require('passport-jwt');
// JSON Web Token Setup
const ExtractJwt = passportJWT.ExtractJwt;
const JwtStrategy = passportJWT.Strategy;
// Configure its options
const jwtOptions = {};
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
jwtOptions.secretOrKey = 'big-long-string-from-lastpass.com/generatepassword.php';
// Add Support for Incoming JSON Entities
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function (req, res, next) {
if (
req.headers &&
req.headers.authorization &&
req.headers.authorization.split(' ')[0] === 'JWT'
) {
jwt.verify(req.headers.authorization.split(' ')[1], jwtOptions.secretOrKey, function (
err,
decode
) {
if (err) req.user = undefined;
req.user = decode;
next();
});
} else {
req.user = undefined;
next();
}
});
const strategy = new JwtStrategy(jwtOptions, function (jwt_payload, next) {
console.log('payload received', jwt_payload);
if (jwt_payload) {
// Attach the token's contents to the request
// It will be available as "req.user" in the route handler functions
next(null, {
_id: jwt_payload._id,
});
} else {
next(null, false);
}
});
// Activate the security system
passport.use(strategy);
app.use(passport.initialize());
app.use(passport.session());
// ***** User Methods *****
// Get One User by Id
app.get('/api/users/:email', passport.authenticate('jwt', { session: false }), (req, res) => {
if (req.user) {
const { _id } = req.user;
// Call the Manager Method
m.usersGetById(_id)
.then((data) => {
res.json(data);
})
.catch(() => {
res.status(404).json({ message: 'Resource not found' });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
});
// User Create // debugged
app.post('/api/users/create', (req, res) => {
m.usersRegister(req.body)
.then((data) => {
// Configure the payload with data and claims
const payload = {
_id: data._id,
email: data.email,
};
const token = jwt.sign(payload, jwtOptions.secretOrKey, {
expiresIn: 1000 * 10000000,
});
res.json({ message: data, token });
})
.catch((msg) => {
res.status(400).json({ message: msg.message });
});
});
// User Login // debugged
app.post('/api/users/login', (req, res) => {
m.usersLogin(req.body)
.then((data) => {
// Configure the payload with data and claims
const payload = {
_id: data._id,
email: data.email,
};
const token = jwt.sign(payload, jwtOptions.secretOrKey, {
expiresIn: 1000 * 10000000,
});
// Return the result
res.json({ message: 'Login was successful', token: token, _id: data._id });
})
.catch((msg) => {
res.status(400).json({ message: msg.message });
});
});
// User Update // debugged
app.post(
'/api/users/:email/update',
passport.authenticate('jwt', { session: false }),
(req, res) => {
if (req.user) {
// Call the manager method
const { _id } = req.user;
m.userUpdate(_id, req.body)
.then((data) => {
res.json(data);
})
.catch((msg) => {
res.status(404).json({ message: 'Resource not found' });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
}
);
// ***** Program Methods *****
// Get All Programs
app.get('/api/programs', passport.authenticate('jwt', { session: false }), (req, res) => {
if (req.user) {
// Call the Manager Method
m.programGetAll()
.then((data) => {
res.json(data);
})
.catch(() => {
res.status(404).json({ message: 'Resource not found' });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
});
// Get Matched Programs
app.get('/api/programs/matchedprograms/:email', passport.authenticate('jwt', { session: false }), (req, res) => {
if (req.user) {
// Call the Manager Method
const { _id } = req.user;
m.programGetMatched(_id)
.then((data) => {
console.log('data');
res.json(data);
})
.catch((error) => {
res.status(404).json({ message: error });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
});
// Get One Program
app.get(
'/api/programs/:programId',
passport.authenticate('jwt', { session: false }),
(req, res) => {
if (req.user) {
// Call the Manager Method
m.programGetById(req.params.programId)
.then((data) => {
res.json(data);
})
.catch(() => {
res.status(404).json({ message: 'Resource not found' });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
}
);
// Add New Program
app.post('/api/programs', passport.authenticate('jwt', { session: false }), (req, res) => {
m.programAdd(req.body)
.then((data) => {
res.json(data);
})
.catch((error) => {
res.status(500).json({ message: error });
});
});
// Edit Program
app.put('/api/programs/:programId', (req, res) => {
m.programEdit(req.body)
.then((data) => {
res.json(data);
})
.catch(() => {
res.status(404).json({ message: 'Program Not Found, Update Failed' });
});
});
// Delete Program
app.delete('/api/programs/:programId', (req, res) => {
m.programDelete(req.params.programId)
.then(() => {
res.status(204).end();
})
.catch(() => {
res.status(404).json({ message: 'Program Not Found, Delete Failed' });
});
});
// ***** Admin Methods *****
// Get One Admin by Id
app.get('/api/admins/:adminId', passport.authenticate('jwt', { session: false }), (req, res) => {
// Call the Manager Method
m.adminGetById(req.params.adminId)
.then((data) => {
res.json(data);
})
.catch(() => {
res.status(404).json({ message: 'Resource not found' });
});
});
// Admin Create // debugged
app.post('/api/admins/create', (req, res) => {
m.adminRegister(req.body)
.then((data) => {
// Configure the payload with data and claims
const payload = {
_id: data._id,
email: data.email,
};
const token = jwt.sign(payload, jwtOptions.secretOrKey, {
expiresIn: 1000 * 10000000,
});
res.json({ message: data, token });
})
.catch((msg) => {
res.status(400).json({ message: msg.message });
});
});
// Admin Login // debugged
app.post('/api/admins/login', (req, res) => {
m.adminLogin(req.body)
.then((data) => {
// Configure the payload with data and claims
const payload = {
_id: data._id,
email: data.email,
};
const token = jwt.sign(payload, jwtOptions.secretOrKey, {
expiresIn: 1000 * 10000000,
});
// Return the result
res.json({ message: 'Login was successful', token: token, _id: data._id });
})
.catch((msg) => {
res.status(400).json({ message: msg.message });
});
});
// Admin Update // debugged
app.post(
'/api/admins/:email/update',
passport.authenticate('jwt', { session: false }),
(req, res) => {
if (req.user) {
// Call the manager method
const { _id } = req.user;
m.adminUpdate(_id, req.body)
.then((data) => {
res.json(data);
})
.catch((msg) => {
res.status(404).json({ message: 'Resource not found' });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
}
);
// Admin Update Temp Programs // debugged
app.put(
'/api/admins/:adminID/updateProgramTemp',
passport.authenticate('jwt', { session: false }),
(req, res) => {
if (req.user) {
// Call the manager method
console.log(req.body);
m.adminCartSave(req.params.adminID, req.body)
.then((data) => {
res.json(data);
})
.catch((msg) => {
res.status(404).json({ message: 'Resource not found' });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
}
);
// Admin Update Temp Programs // debugged
app.put(
'/api/admins/:adminID/updateProgramFull',
passport.authenticate('jwt', { session: false }),
(req, res) => {
if (req.user) {
// Call the manager method
m.adminCartSaveFull(req.params.adminID, req.body)
.then((data) => {
res.json(data);
})
.catch((msg) => {
res.status(404).json({ message: 'Resource not found' });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
}
);
// Admin Password Reset
app.put('/api/admins/:passwordReset', (req, res) => {
var newPassword = makePassword(6);
m.adminPassReset(req.params.passwordReset, newPassword)
.then((data) => {
var transporter = nodemailer.createTransport({
service: 'outlook',
auth: {
user: 'devbrizz@hotmail.com',
pass: 'eIc^XxvzuPld',
},
});
var mailOptions = {
to: data.email,
from: 'devbrizz@hotmail.com',
subject: 'Admin Password Reset',
text:
'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Your new password is: ' +
newPassword +
'\n\n' +
'Use this Password as your new password to log into the Admin Website.\n',
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.json(data);
})
.catch((msg) => {
res.status(404).json({ message: 'Resource not found' });
});
});
// -------------- Questionnaire --------------
// save questionnaire results
app.post(
'/api/users/:email/updateresults',
passport.authenticate('jwt', { session: false }),
(req, res) => {
if (req.user) {
// Call the manager method
const { _id } = req.user;
m.userSaveResults(_id, req.body)
.then((data) => {
res.json(data);
})
.catch((msg) => {
res.status(404).json({ message: 'Resource not found' });
});
} else {
res.status(401).json({ message: 'Not authorized' });
}
}
);
// Attempt to Connect to the Database, Start Listening for Requests
m.connect()
.then(() => {
app.listen(HTTP_PORT, () => {
console.log('Ready to handle requests on port ' + HTTP_PORT);
});
})
.catch((err) => {
console.log('Unable to start the server:\n' + err);
process.exit();
});
function makePassword(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}