Server for my portfolio

index.js 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. var fs = require('fs');
  2. var compression = require('compression')
  3. var https = require('https');
  4. var express = require('express');
  5. var path = require('path');
  6. var forceSSL = require('express-force-ssl');
  7. var bodyParser = require('body-parser');
  8. var serveIndex = require('serve-index');
  9. var basic_auth = require('basic-auth');
  10. var FileStreamRotator = require('file-stream-rotator');
  11. var morgan = require('morgan');
  12. var hsts = require('hsts');
  13. var route_manager = require("../ip-project-server/utils/route-manager.js");
  14. var scheduler = require("../ip-project-server/presenters/schedule-controller.js");
  15. var app = express();
  16. var logDirectory = 'log'
  17. var nicklist = {};
  18. /*
  19. Basic administration stuff
  20. */
  21. // Set up authentication and existing events.
  22. var log_passwd = fs.readFileSync('../ip-project-server/logpasswd', 'utf-8');
  23. var auth = function (req, res, next) {
  24. function unauthorized(res) {
  25. res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
  26. return res.sendStatus(401);
  27. };
  28. var user = basic_auth(req);
  29. if (!user || !user.name || !user.pass) {
  30. return unauthorized(res);
  31. };
  32. if (user.name === 'logs' && user.pass === log_passwd.trim()) {
  33. return next();
  34. } else {
  35. return unauthorized(res);
  36. };
  37. };
  38. fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
  39. var accessLogStream = FileStreamRotator.getStream({
  40. date_format: 'YYYYMMDD',
  41. filename: logDirectory + '/access-%DATE%.log',
  42. frequency: 'daily',
  43. verbose: false
  44. })
  45. scheduler.register_existing_events();
  46. /*
  47. Set up middleware, included logging and headers.
  48. */
  49. // Always use SSL, comes first.
  50. app.use(compression());
  51. app.use(forceSSL);
  52. app.use(hsts({
  53. maxAge: 31536000000,
  54. includeSubDomains: true, // Must be enabled to be approved by Google
  55. preload: true
  56. }))
  57. app.use(bodyParser.json()); // for parsing application/json
  58. app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
  59. // Send CORS headers on api route.
  60. app.use('/soc-api/*', function(req, res, next) {
  61. res.header("Access-Control-Allow-Origin", "*");
  62. res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  63. next();
  64. });
  65. // Logging comes next
  66. app.use(morgan('short', {stream: accessLogStream}))
  67. app.use(morgan('short'));
  68. /*
  69. Set up the individual routes for each part of my portfolio
  70. */
  71. // Check the /soc-api/ routes.
  72. app.use('/soc-api/v1', route_manager);
  73. // Serve the log files
  74. app.use('/log', auth, express.static('log'));
  75. app.use('/log', auth, serveIndex('log', {'icons': true}));
  76. // Static site fallback
  77. app.use('/', express.static('../www/'));
  78. // 404 Anything Else
  79. app.use(function (req,res,next) {
  80. res.status(404).sendFile(path.resolve('../www_res/404/index.html'));
  81. });
  82. /*
  83. Below here we set up the servers and choose which ports they will listen on.
  84. */
  85. var prkey = fs.readFileSync('key.pem');
  86. var certi = fs.readFileSync('cert.pem');
  87. var capem = fs.readFileSync('ca.pem');
  88. var s = https.createServer({
  89. key: prkey,
  90. cert: certi,
  91. ca: capem
  92. }, app).listen(443, function() {
  93. console.log('Now accepting HTTPS connections on port 443.');
  94. });
  95. app.listen(80, function () {
  96. console.log('Now accepting HTTP connections on port 80.');
  97. });
  98. function getRandomInt(min, max) {
  99. min = Math.ceil(min);
  100. max = Math.floor(max);
  101. return Math.floor(Math.random() * (max - min)) + min;
  102. }
  103. var io = require('socket.io')(s);
  104. io.on('connection', function(socket){
  105. console.log('a user connected');
  106. nicklist[socket.id] = getRandomInt(0,99999);
  107. socket.on('chat message', function(msg){
  108. console.log(msg.nick + '#' + nicklist[socket.id] + ': ' + msg.msg);
  109. msg.nick = msg.nick + '#' + nicklist[socket.id];
  110. io.emit('chat message', msg);
  111. });
  112. socket.on('disconnect', function(){
  113. console.log('user disconnected');
  114. delete nicklist[socket.id];
  115. });
  116. });