var express = require('express'),
  forceSSL = require('express-force-ssl'),
  fs = require('fs'),
  path = require('path'),
  bodyParser = require('body-parser'),
  http = require('http'),
  https = require('https'),
  jwtMiddleware = require('express-jwt'),
  helmet = require('helmet'),
  routes = require('./server/routes'),
  config = require('./server/config/env.json'),
  notFoundError = require('./server/errors/notFoundError');

var credentials = {
  key: fs.readFileSync('./server/config/ssl/key.pem'),
  cert: fs.readFileSync('./server/config/ssl/cert.pem')
};

var app = express();

app.use(forceSSL);

// default Content security policy is to allow content loading only from same origin
// defaultSrc applies as a fallback to all sources not defined
app.use(helmet.csp({
  defaultSrc: ["'self'"],
  // scriptSrc: [],
  styleSrc: ["'self'", "'unsafe-inline'"], // permit inline css
  // imgSrc: [],
  // connectSrc: [],                      // ajax, web sockets
  // fontSrc: [],
  // objectSrc: [],                       // object, embed, applet
  // mediaSrc: [],                        // audio, video
  // frameSrc: []
}));

app.use(express.static(__dirname + '/client'));
// only accepts content-type application/json
app.use(bodyParser.json());

// Auth Middleware
// routes starting with /api will be checked for jwt token (except /api/login)
// app.all('/api/*', [require('./server/middlewares/authRequest')]);
app.use('/api/*', jwtMiddleware({ secret: config.jwtSecret}).unless({path: ['/api/login', '/api/register']}));

app.use(routes);

//return 404 on not matched routes
app.all('*', function(req, res, next) {
  next(new notFoundError('404'));
});

// error handler
app.use(function(err, req, res, next) {
  var code, msg; //default http 500

  switch (err.name) {
  case 'UnauthorizedError':
    code = err.status;
    msg = { message: 'Unauthorized' };
    break;
  case 'NotFoundError':
    code = err.status;
    msg = { message: 'Not Found' };
    break;
  case 'BadRequestError':
    code = err.status;
    msg = err.inner;
    break;
  default:
    code = 500;
    msg = { message: 'Internal Server Error' }; //default http 500
  }

  res.status(code).json(msg);
});

app.set('httpsPort', process.env.httpsPort || 8443);
app.set('port', process.env.PORT || 8000);

// Start the server
var secureServer = https.createServer(credentials, app).listen(app.get('httpsPort'), function() {
  console.log('Express secure server listening on port ' + secureServer.address().port);
});

var server = http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + server.address().port);
});;


@@ -592,27 +592,83 @@
 );%0A%0A
-app.use(forceSSL);%0A
+// Force use of https%0Aapp.use(forceSSL);%0A%0A// Content Security Policy Header
 %0A// 
@@ -1186,24 +1186,1102 @@
 c: %5B%5D%0A%7D));%0A%0A
+// Add X-XSS-Protection header%0A// X-XSS-Protection: 1; mode=block%0A// http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx%0Aapp.use(helmet.xssFilter());%0A%0A// Implement header X-Frame-Options: Deny%0A// Deny - Does not allow your page to be served inside any frames.%0A// Prevents clickjacking attacks%0Aapp.use(helmet.frameguard('deny'));%0A%0A// Implement header Strict-Transport-Security%0A// Response header -%3E Strict-Transport-Security: max-age=7776000; includeSubDomains%0A// HTTP Strict-Transport-Security (HSTS) enforces secure (HTTP over SSL/TLS) connections to the server. %0A// This reduces impact of bugs in web applications leaking session data through cookies and external links %0A// and defends against Man-in-the-middle attacks. %0A// HSTS also disables the ability for user's to ignore SSL negotiation warnings.%0A// It basically tells user agents to interact with it in the future only over HTTPS.%0Aapp.use(helmet.hsts(%7B%0A  maxAge: 7776000000,     // 90 days%0A  includeSubdomains: true%0A%7D));%0A%0A// Hide X-Powered-By header%0Aapp.use(helmet.hidePoweredBy());%0A%0A
 app.use(expr
@@ -2491,78 +2491,26 @@
 ogin
-)%0A// app.all('/api/*', %5Brequire('./server/middlewares/authRequest')%5D);
+ && /api/register)
 %0Aapp
@@ -2614,24 +2614,41 @@
 ster'%5D%7D));%0A%0A
+// Define routes%0A
 app.use(rout

implement various protections for xss, clickjacking, mitm through http headers