Skip to content
This repository has been archived by the owner on Nov 14, 2017. It is now read-only.

Commit

Permalink
Merge pull request #91 from lorderikir/master
Browse files Browse the repository at this point in the history
HTTPS Update
  • Loading branch information
ericjiang97 committed Jan 18, 2017
2 parents 13f00a7 + 1abfc5f commit d9ec25b
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 39 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ node_modules

# npm debug
npm-debug.log

# SSL Cert Directory
ssl
106 changes: 67 additions & 39 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
// =============================================================================

// call the packages we need
var express = require('express'); // call express
var bodyParser = require('body-parser');
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;
Expand All @@ -14,45 +14,66 @@ 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 ienoopen = require("ienoopen");
var xssFilter = require("x-xss-protection");
var frameguard = require("frameguard");
var hpkp = require("hpkp");
var csp = require("helmet-csp");

// MODULES
var spec = require('./app/specialisations/specialRoute');
var basic = require('./app/basic/route');
var spec = require("./app/specialisations/specialRoute");
var basic = require("./app/basic/route");

// VARIABLES
var db;
var app = express(); // define our app using express
var cors = require('cors');
var cors = require("cors");
var collectionUnits = "units";
var collectionCourses = "courses";

// HTTP/HTTPS Setup
var fs = require("fs");
var http = require("http");
var https = require("https");
var enableSSL = true;

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'}));


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(frameguard({action: "deny"}))
app.use(hpkp({
maxAge: 1209600,
sha256s: ['AbCdEf123=', "ZyXwVu456"],
sha256s: ["AbCdEf123=", "ZyXwVu456"],

setIf: function(req,res){
return req.secure
}
}));
app.use(csp({
directives: {
scriptSrc: ["'self'", "'unsafe-inline'"]
scriptSrc: ["'self'","'unsafe-inline'"]
},
reportOnly: false,
setAllHeaders: false,
Expand All @@ -63,8 +84,8 @@ app.use(csp({
// MUST HAVE MONGODB ON LOCALHOST


console.log('Attempting to connect to mongoDB backend.')

console.log("Attempting to connect to mongoDB backend.")
var address = "mongodb://mplanAdmin:Dr6BnHNJydXACJ4@api.monplan.tech:45956/unitsDatabase?authSource=admin"
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(address, function (err, database) {
if (err) {
Expand All @@ -76,11 +97,18 @@ mongodb.MongoClient.connect(address, function (err, database) {
db = database;
console.log("Database connection ready");

// Initialize the app.
var server = app.listen(process.env.PORT || 3000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
var httpServer = http.createServer(app);
httpServer.listen(3000);

if(enableSSL){
console.log("Initialising HTTPS Server");
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(4000);
} 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
Expand All @@ -89,25 +117,25 @@ var router = express.Router(); // get an instance of the express Ro
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' });
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);
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);
app.use("/api", router);

// SPECIALISATION ROUTES
app.get('/spec/', spec.allSpec);
app.get('/spec/:id', spec.findSpec);
app.get("/spec/", spec.allSpec);
app.get("/spec/:id", spec.findSpec);


app.get('/basic/:id', basic.downloadInfo)
app.get("/basic/:id", basic.downloadInfo)

/* "/unitRatings"
* GET: finds all units
Expand All @@ -132,7 +160,7 @@ app.get("/units/:id", function(req, res) {
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({'msg': 'No Unit Data'})
res.status(404).json({"msg": "No Unit Data"})
}
});
});
Expand All @@ -158,13 +186,13 @@ app.post("/units/rating/:id", function(req,res) {
var uploadEnjRating = (newEnjoyRating + oldEnjoyRating)/2
db.collection(collectionUnits).update({ UnitCode: unitCode }, {"$set": {enjoyRating: uploadEnjRating, learnRating: uploadUnitRating}});
res.status(200).json({'msg': 'Successfully updated'})
res.status(200).json({"msg": "Successfully updated"})
} else {
res.status(404).json({'msg': 'No Unit Data'})
res.status(404).json({"msg": "No Unit Data"})
}
});
} else {
res.status(404).json({'msg': 'Invalid Body'})
res.status(404).json({"msg": "Invalid Body"})
}
});
*/
Expand All @@ -177,7 +205,7 @@ app.get("/courses/:id", function(req, res) {
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({'msg': 'No Unit Data'})
res.status(404).json({"msg": "No Unit Data"})
}
});
});
Expand All @@ -190,7 +218,7 @@ app.get("/courses/info/:id", function(req, res) {
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({'msg': 'No Course Information Data'})
res.status(404).json({"msg": "No Course Information Data"})
}
});
});
Expand All @@ -203,7 +231,7 @@ app.get("/rules/:id", function(req, res) {
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json('Missing Rule Data')
res.status(404).json("Missing Rule Data")
}
});
});
Expand All @@ -223,7 +251,7 @@ app.get("/snaps/:id", function(req, res) {
if(doc !== null) {
res.status(200).json(doc);
} else {
res.status(404).json({'msg': 'No snapshot Data'})
res.status(404).json({"msg": "No snapshot Data"})
}
});
});
Expand All @@ -232,14 +260,14 @@ 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) {
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'})
res.status(404).json({"msg": "No snapshot Data"})
}

});
Expand Down

0 comments on commit d9ec25b

Please sign in to comment.