This repository has been archived by the owner on Nov 14, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
309 lines (264 loc) · 8.65 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
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require("express"); // call express
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectId = require("mongodb").ObjectID;
var BSON = require("mongodb").BSONPure;
// SECURITY MODULES
var helmet = require("helmet");
var hidePoweredBy = require("hide-powered-by");
var session = require("express-session");
var nosniff = require("dont-sniff-mimetype");
var ienoopen = require("ienoopen");
var xssFilter = require("x-xss-protection");
var frameguard = require("frameguard");
var hpkp = require("hpkp");
var csp = require("helmet-csp");
var hsts = require("hsts");
// HTTP/HTTPS Setup
var fs = require("fs");
var http = require("http");
var https = require("https");
var enableSSL = true;
// MODULES
var spec = require("./app/specialisations/specialRoute");
var basic = require("./app/basic/route");
var announce = require("./app/announcements/announce");
// VARIABLES
var db;
var app = express(); // define our app using express
var cors = require("cors");
var collectionUnits = "units";
var collectionCourses = "courses";
try {
var pkey = fs.readFileSync("./ssl/server.key","utf8");
var cert = fs.readFileSync("./ssl/server.crt","utf8");
console.log("SSL Directory Detected! Setting up HTTPS configuration");
var credentials = {key: pkey, cert: cert};
enableSSL = true;
} catch(err){
console.log("No SSL Directory Detected");
console.log("Setting enableSSL VARIABLE to false");
enableSSL = false;
}
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
console.log("Deploying Security Measures")
app.use(hidePoweredBy({setTo: "Coffee"}));
app.use(nosniff());
app.use(ienoopen());
app.use(xssFilter());
app.use(frameguard({action: "deny"}))
app.use(hpkp({
maxAge: 1209600, // Max Age is 14 days
sha256s: ["AbCdEf123=", "ZyXwVu456"],
setIf: function(req,res){
return req.secure
}
}));
app.use(csp({
directives: {
scriptSrc: ["'self'","'unsafe-inline'"]
},
reportOnly: false,
setAllHeaders: false,
disabledAndroid: false,
browserSniff: false
}));
app.use(hsts({
maxAge: 1209600, // Max Age is 14 days
//includeSubDomains: true,
//preload: true, //use bake-into chrome HSTS (implement HSTS into main site, then enable this)
force: true //always set the header
}));
// MUST HAVE MONGODB ON LOCALHOST
console.log("Attempting to connect to mongoDB backend.")
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(address, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
var httpServer = http.createServer(app);
httpServer.listen(4000);
if(enableSSL){
console.log("Initialising HTTPS Server");
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(5000);
} else {
console.log("Enabling HTTPS Server is false.");
console.log("To enable place SSL Cert and Key inside the ssl directory");
}
console.log("Ready to Go!")
});
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
var v02 = express.Router();
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get("/", function(req, res) {
res.json({ message: "This is the monPlan API. Please read the API documentation at: https://github.com/monashunitplanner/monplan-api" });
});
app.use(cors());
app.set("etag", false);
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use("/api", router);
// SPECIALISATION ROUTES
app.get("/spec/", spec.allSpec);
app.get("/spec/:id", spec.findSpec);
app.get("/announce", function(req, res) {
res.status(200).send(JSON.parse(fs.readFileSync("announcements.json", 'utf8')));
});
app.get("/basic/:id", basic.downloadInfo);
/* "/unitRatings"
* GET: finds all units
*/
app.get("/units/", function(req, res) {
db.collection(collectionUnits).find({}).toArray(function(err, docs) {
if (err) {
handleError(res, err.message, "Failed to get units.");
} else {
res.status(200).json(docs);
}
});
});
app.get("/units/:id", function(req, res) {
db.collection(collectionUnits).findOne({ UnitCode: (req.params.id) }, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get unit Data");
}
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({"msg": "No Unit Data"})
}
});
});
/*
app.post("/units/rating/:id", function(req,res) {
var rating = req.body;
var newLearnRating = parseInt(rating.learnrating, 10);
var newEnjoyRating = parseInt(rating.enjoyrating, 10);
console.log("Updating Unit Rating")
if(1<newLearnRating<5 && 1<newEnjoyRating<5){
var unitCode = (req.params.id);
db.collection(collectionUnits).findOne({ UnitCode: unitCode }, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get unit Data");
}
if(doc !== null) {
var oldEnjoyRating = doc.enjoyRating
var oldUnitRating = doc.learnRating
var uploadUnitRating = (newLearnRating + oldUnitRating)/2
var uploadEnjRating = (newEnjoyRating + oldEnjoyRating)/2
db.collection(collectionUnits).update({ UnitCode: unitCode }, {"$set": {enjoyRating: uploadEnjRating, learnRating: uploadUnitRating}});
res.status(200).json({"msg": "Successfully updated"})
} else {
res.status(404).json({"msg": "No Unit Data"})
}
});
} else {
res.status(404).json({"msg": "Invalid Body"})
}
});
*/
app.get("/courses/:id", function(req, res) {
db.collection(collectionCourses).findOne({ courseCode: (req.params.id) }, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get course map Data");
}
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({"msg": "No Unit Data"})
}
});
});
app.get("/courses/info/:id", function(req, res) {
db.collection("courseInfo").findOne({ courseCode: (req.params.id) }, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get course information Data");
}
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({"msg": "No Course Information Data"})
}
});
});
app.get("/rules/:id", function(req, res) {
db.collection("rules").find({ unitCode: (req.params.id) }).toArray(function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get unit rules");
}
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json("Missing Rule Data")
}
});
});
//User Anonymous Snapshots
app.get("/snaps/:id", function(req, res) {
//attempt to hash id, if fail return error 418
try {
var id = new ObjectId(req.params.id)
} catch(err) {
res.status(418).send("I'm a teapot.");
}
db.collection("snapshots").findOne({"_id": id}, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get snapshot Data");
}
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({"msg": "No snapshot Data"})
}
});
});
app.post("/snaps/", function(req, res) {
var postBody = req.body;
var courseDet = postBody.course
if(postBody.course !== null || postBody.course !== ""){
db.collection("snapshots").insertOne({"snapshotData": courseDet}, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get snapshot Data");
}
if(doc !== null) {
res.status(200).json(doc.insertedId);
} else {
res.status(404).json({"msg": "No snapshot Data"})
}
});
}
});
//User Testing Snapshot
app.get("/snaps/testing", function(req, res) {
//attempt to hash id, if fail return error 418
try {
var id = new ObjectId()
} catch(err) {
res.status(418).send("I'm a teapot.");
}
db.collection("snapshots").findOne({"_id": id}, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get snapshot Data");
}
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({"msg": "No snapshot Data"})
}
});
});